package com.webclient.beans.udprgather;

import com.alibaba.fastjson.JSONObject;
import psdi.app.iface.oa.Eam2OaPrHandler;
import psdi.app.iface.srm.Srm2EamHandler;
import psdi.mbo.MboRemote;
import psdi.mbo.MboSet;
import psdi.mbo.MboSetRemote;
import psdi.server.MXServer;
import psdi.util.MXApplicationException;
import psdi.util.MXApplicationYesNoCancelException;
import psdi.util.MXException;
import psdi.webclient.beans.pr.PRAppBean;
import psdi.webclient.system.beans.AppBean;
import psdi.webclient.system.beans.ResultsBean;
import psdi.webclient.system.controller.WebClientEvent;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.util.Date;

public class UdprgatherAppBean extends AppBean {

    public void initializeApp() throws MXException, RemoteException {
        super.initializeApp();
        ResultsBean resultsbean = app.getResultsBean();
        MboSetRemote set=resultsbean.getMboSet();
        String userid=set.getUserInfo().getPersonId();
        MboSetRemote pset= MXServer.getMXServer().getMboSet("person", set.getUserInfo());
        pset.setWhere("personid='"+userid+"'");
        if(!pset.isEmpty() && pset.count()>0){
            MboRemote per=pset.getMbo(0);
            //权限等级
            String aut=per.getString("UDAUTGRADE");
            String orgid=per.getString("LOCATIONORG");
            String siteid=per.getString("LOCATIONSITE");

            if("Level 1".equalsIgnoreCase(aut)){
                set.setWhere(" 1=1 ");
            }else if("Level 2".equalsIgnoreCase(aut)){
                set.setWhere(" ORGID='"+orgid+"' ");
            }else if("Level 3".equalsIgnoreCase(aut)){
                set.setWhere(" SITEID='"+siteid+"' ");
            }else if("Level 4".equalsIgnoreCase(aut)){
                set.setWhere(" ORGID='"+orgid+"' and SITEID='"+siteid+"' and REQUESTEDBY='"+userid+"'");
            }else{
                //没有等级
                set.setWhere("1=2");
            }
        }
        pset.close();

    }

    public void selectpr() throws Exception {
        app.getAppBean().save();
    }

    /**
     * 提交到OA
     */
    public void SUBTOOA() throws Exception {
        MboRemote appMbo=app.getAppBean().getMbo();
        WebClientEvent webclientevent;
        webclientevent = this.clientSession.getCurrentEvent();
        if("TOOA".equalsIgnoreCase(appMbo.getString("STATUS")) || "SRM".equalsIgnoreCase(appMbo.getString("STATUS"))){
            this.clientSession.showMessageBox(webclientevent, new MXApplicationException("subtofactory", "subtofactory_dup", new String[0]));
            return;
        }

        MboSetRemote prlineSet = MXServer.getMXServer().getMboSet("PRLINE", MXServer.getMXServer().getSystemUserInfo());
        prlineSet.setWhere("PRLINEID in(SELECT max(PRLINEID) FROM PRLINE WHERE prnum='"+appMbo.getString("PRNUM")+"' and siteid='"+appMbo.getString("SITEID")+"' AND ORGID='"+appMbo.getString("ORGID")+"' GROUP BY ITEMNUM)");
        prlineSet.reset();
        if(null!=prlineSet && !prlineSet.isEmpty()){
            String str="";
            boolean sqFlag=false;
            for(int i=0;i<prlineSet.count();i++){
                MboRemote prlineMbo=prlineSet.getMbo(i);
                //系统自动触发数量+手动申请数量
                MboSetRemote prhset=appMbo.getMboSet("$PRLINE","PRLINE","prnum='"+appMbo.getString("PRNUM")+"' and siteid='"+appMbo.getString("SITEID")+"' AND ORGID='"+appMbo.getString("ORGID")+"' AND ITEMNUM='"+prlineMbo.getString("ITEMNUM")+"'");
                double apprquantity=0.0;
                if(null!=prhset && !prhset.isEmpty()){
                    apprquantity=prhset.sum("APPRQUANTITY");//批准数量(申请数量)
                }

                //库存数量
                MboSetRemote udkcSet=appMbo.getMboSet("$UDKC","UDKC","ITEMNUM='"+prlineMbo.getString("ITEMNUM")+"' and SITEID='"+appMbo.getString("SITEID")+"'");
                double kcsl=0.0;
                if(null!=udkcSet && !udkcSet.isEmpty()){
                    kcsl=udkcSet.sum("CURBALTOTAL");
                }

                //在途数量
                MboSetRemote uditemsafeSet=appMbo.getMboSet("UDITEMSAFE", "UDITEMSAFE", "ITEMNUM='"+prlineMbo.getString("ITEMNUM")+"' and SITEID='"+appMbo.getString("SITEID")+"' AND ORGID='"+appMbo.getString("ORGID")+"'");
                double ztsl=0.0;
                double zgkcl=0.0;
                if(null!=uditemsafeSet && !uditemsafeSet.isEmpty()){
                    ztsl=uditemsafeSet.sum("TRANSQT");//在途数量
                    zgkcl=uditemsafeSet.sum("UPQT");//最高库存量
                }

                //清单数量
                MboSetRemote qdslSet=appMbo.getMboSet("$UDMATUSETRANS", "UDMATUSETRANS","ITEMNUM ='"+prlineMbo.getString("ITEMNUM")+"' AND ORGID='"+appMbo.getString("ORGID")+"' AND SITEID='"+appMbo.getString("SITEID")+"'" );
                double qdsl=0.0;
                if(null!=qdslSet && !qdslSet.isEmpty()){
                    qdsl=qdslSet.sum("QUANTITY");
                }

                if((apprquantity+kcsl+ztsl+qdsl)>zgkcl && zgkcl>0){
                    str+=prlineMbo.getString("ITEMNUM")+",";
                    sqFlag=true;
                }
            }
            if(sqFlag){
                this.clientSession.showMessageBox(webclientevent, new MXApplicationException("subtofactory", "subtofactory_qgdyz", new String[]{str}));
                app.getAppBean().reloadTable();
                app.getAppBean().refreshTable();
                return;
            }
        }


        //最小包装量校验
        MboSetRemote eamitemsapSet = MXServer.getMXServer().getMboSet("EAMITEMSAP", MXServer.getMXServer().getSystemUserInfo());
        String sqlStr1="MATNR in(SELECT ITEMNUM FROM PRLINE WHERE PRLINEID in(SELECT max(PRLINEID) FROM PRLINE WHERE prnum='"+appMbo.getString("PRNUM")+"' and siteid='"+appMbo.getString("SITEID")+"' AND ORGID='"+appMbo.getString("ORGID")+"' GROUP BY ITEMNUM)) AND ZMOQ>0";
        eamitemsapSet.setWhere(sqlStr1);
        eamitemsapSet.reset();
        boolean flag2=false;
        if(null!=eamitemsapSet && !eamitemsapSet.isEmpty() && eamitemsapSet.count()>0){
            String str2="";
            for(int e=0;e<eamitemsapSet.count();e++){
                MboRemote eMbo=eamitemsapSet.getMbo(e);
                double zmoq=eMbo.getDouble("ZMOQ");//sqp物料主数据--最小包装量
                String eMatnr=eMbo.getString("MATNR");//sap物料号

                MboSetRemote prhset=appMbo.getMboSet("$PRLINE2","PRLINE","prnum='"+appMbo.getString("PRNUM")+"' and siteid='"+appMbo.getString("SITEID")+"' AND ORGID='"+appMbo.getString("ORGID")+"' AND ITEMNUM='"+eMatnr+"'");
                double appqua=prhset.sum("APPRQUANTITY");//批准数量
                if(appqua%zmoq!=0){
                    flag2=true;
                    str2+=eMatnr+",";
                }
            }
            if(flag2){
                this.clientSession.showMessageBox(webclientevent, new MXApplicationException("subtofactory", "subtofactory_zxbzs", new String[]{str2}));
                app.getAppBean().reloadTable();
                app.getAppBean().refreshTable();
                return;
            }
        }




        JSONObject result = new Eam2OaPrHandler().EAM_OA_PR_IDLE(appMbo);
        if(null!=result){
            JSONObject RESPONSE = (JSONObject) result.get("RESPONSE");
            if(null!=RESPONSE){
                JSONObject RETURN_DATA = (JSONObject) RESPONSE.get("RETURN_DATA");
                if(null!=RETURN_DATA){
                    String code=  RETURN_DATA.getString("code");
                    if("SUCCESS".equalsIgnoreCase(code)){
                        String doCreReqJsoData = RETURN_DATA.getString("data");
                        JSONObject doCreReqJso2 = JSONObject.parseObject(doCreReqJsoData);
                        String requestid=doCreReqJso2.getString("requestid");
                        if(null!=requestid && !"".equalsIgnoreCase(requestid)){
                            appMbo.setFieldFlag("STATUS", 7L, false);
                            appMbo.setFieldFlag("STATUSDATE", 7L, false);
                            appMbo.setValue("STATUS", "TOOA",2L);
                            appMbo.setValue("STATUSDATE", new Date(),2L);
                            appMbo.setFieldFlag("STATUS", 7L, true);
                            appMbo.setFieldFlag("STATUSDATE", 7L, true);
                            if(result.toString().getBytes(StandardCharsets.UTF_8).length<=4000){
                                appMbo.setValue("OARETURN", result.toString(), 2L);
                            }else{
                                appMbo.setValue("OARETURN", result.toString().substring(0,1333), 2L);
                            }
                            String pr1=appMbo.getString("PR1");
                            if("".equalsIgnoreCase(pr1) || null==pr1){
                                appMbo.setValue("pr1", (1+0)+"", 2L);
                            }else{
                                appMbo.setValue("pr1", (1+Integer.parseInt(pr1))+"", 2L);
                            }
                            appMbo.setValue("PR4", requestid, 2L);//OA流程ID号
                            appMbo.getThisMboSet().save();
                            app.getAppBean().reloadTable();
                            app.getAppBean().refreshTable();
                            this.clientSession.showMessageBox(webclientevent, new MXApplicationException("subtofactory", "subtofactory_srm", new String[]{"OA流程ID号"+requestid+""}));
                        }else{
                            if(result.toString().getBytes(StandardCharsets.UTF_8).length<=4000){
                                appMbo.setValue("OARETURN", result.toString(), 2L);
                            }else{
                                appMbo.setValue("OARETURN", result.toString().substring(0,1333), 2L);
                            }
                            appMbo.getThisMboSet().save();
                            app.getAppBean().reloadTable();
                            app.getAppBean().refreshTable();
                            this.clientSession.showMessageBox(webclientevent, new MXApplicationException("subtofactory", "subtofactory_oaerro", new String[]{result.toString()}));
                        }
                    }else{
                        if(result.toString().getBytes(StandardCharsets.UTF_8).length<=4000){
                            appMbo.setValue("OARETURN", result.toString(), 2L);
                        }else{
                            appMbo.setValue("OARETURN", result.toString().substring(0,1333), 2L);
                        }
                        appMbo.getThisMboSet().save();
                        app.getAppBean().reloadTable();
                        app.getAppBean().refreshTable();
                        this.clientSession.showMessageBox(webclientevent, new MXApplicationException("subtofactory", "subtofactory_oaerro", new String[]{RETURN_DATA.toString()}));
                    }
                }
            }
        }else{
            appMbo.setValue("OARETURN", "获取OA人员接口失败，请联系OA确认！", 2L);
            appMbo.getThisMboSet().save();
            app.getAppBean().reloadTable();
            app.getAppBean().refreshTable();
            this.clientSession.showMessageBox(webclientevent, new MXApplicationException("subtofactory", "subtofactory_oaerro", new String[]{"获取OA人员接口失败，请联系OA确认！"}));

        }
        System.gc();
    }

    /**
     * 提交到SRM按钮
     */
    public void SUBTOSRM() throws IOException, MXException {
        MboRemote appMbo=app.getAppBean().getMbo();
        WebClientEvent webclientevent;
        webclientevent = this.clientSession.getCurrentEvent();
        if("SRM".equalsIgnoreCase(appMbo.getString("STATUS"))){
            this.clientSession.showMessageBox(webclientevent, new MXApplicationException("prsubtosrm", "prsubtosrm_dup", new String[0]));
            return;
        }else if(!"TOOA".equalsIgnoreCase(appMbo.getString("STATUS"))){
            this.clientSession.showMessageBox(webclientevent, new MXApplicationException("prsubtosrm", "prsubtosrm_xoa", new String[0]));
            return;
        }
        JSONObject result = new Srm2EamHandler().EAM_TO_SRM_PR(appMbo);
        if(result.toString().getBytes(StandardCharsets.UTF_8).length<=4000){
            appMbo.setValue("JRESULT", result.toString(), 2L);
        }else{
            appMbo.setValue("JRESULT", result.toString().substring(0,1333), 2L);
        }

        JSONObject RESPONSE = (JSONObject) result.get("RESPONSE");
        if(null!=RESPONSE) {
            JSONObject RETURN_DATA = (JSONObject) RESPONSE.get("RETURN_DATA");
            if (null != RETURN_DATA) {
                String code = RETURN_DATA.getString("status");
                if ("S".equalsIgnoreCase(code)) {
                    appMbo.setFieldFlag("STATUS", 7L, false);
                    appMbo.setFieldFlag("STATUSDATE", 7L, false);
                    appMbo.setValue("STATUS", "SRM",2L);
                    appMbo.setValue("STATUSDATE", new Date(),2L);
                    appMbo.setFieldFlag("STATUS", 7L, true);
                    appMbo.setFieldFlag("STATUSDATE", 7L, true);
                    this.SAVE();
                    this.clientSession.showMessageBox(webclientevent, new MXApplicationException("prsubtosrm", "prsubtosrm_srm", new String[0]));
                }else{
                    this.clientSession.showMessageBox(webclientevent, new MXApplicationException("prsubtosrm", "prsubtosrm_fai", new String[]{RETURN_DATA.toString()}));
                    return;
                }
            }
        }

    }

    /**
     * 刷新工厂需求申请-明细状态查询子表
     * @throws IOException
     * @throws MXException
     */
    public void REFRESHLINESTATUS() throws IOException, MXException, ParseException {
        MboRemote appMbo=app.getAppBean().getMbo();
        String status=appMbo.getString("STATUS");
        WebClientEvent webclientevent;
        webclientevent = this.clientSession.getCurrentEvent();
        if("SRM".equalsIgnoreCase(status)){
            String prnum=appMbo.getString("PRNUM");
            String siteid=appMbo.getString("SITEID");
            MboSetRemote prlineSet = MXServer.getMXServer().getMboSet("PRLINE", MXServer.getMXServer().getSystemUserInfo());
            prlineSet.setWhere("prnum='"+prnum+"' and siteid='"+siteid+"'");
            prlineSet.reset();
            String udprnum=appMbo.getString("UDPRNUM");
            if(null!=prlineSet && !prlineSet.isEmpty()){
                for(int i=0;i<prlineSet.count();i++){
                    MboRemote prlineMbo=prlineSet.getMbo(i);
                    String prlinenum=prlineMbo.getString("PRLINENUM");
                    new Srm2EamHandler().EAM_TO_SRM_PRLINE(prlineMbo,udprnum,prlinenum);
                }
                app.getAppBean().reloadTable();
                app.getAppBean().refreshTable();
                this.clientSession.showMessageBox(webclientevent, new MXApplicationException("prsubtosrm", "prsubtosrm_srmline", new String[0]));
            }
        }else{
            this.clientSession.showMessageBox(webclientevent, new MXApplicationException("prsubtosrm", "prsubtosrm_error", new String[0]));
        }
    }


    @Override
    public int DELETE() throws MXException, RemoteException {
        MboRemote appMbo=app.getAppBean().getMbo();
        if(appMbo.isNew()){
            return super.DELETE();
        }
        int msgRet = MXApplicationYesNoCancelException.getUserInput("confirmcontinueid", MXServer.getMXServer(),this.clientSession.getUserInfo());
        if (msgRet < 0) {
            throw new MXApplicationYesNoCancelException("confirmcontinueid", "jspmessages", "deletconfirm");
        }
        if (msgRet == 8) {
            MboSetRemote pmSet=appMbo.getMboSet("$PR", "PR", "UDPRNUM='"+appMbo.getString("UDPRNUM")+"' AND ORGID='"+appMbo.getString("ORGID")+"' AND SITEID='"+appMbo.getString("SITEID")+"' AND STATUS='WAPPR' ");
            if(null!=pmSet && !pmSet.isEmpty()){
                MboSetRemote pmlineSet=appMbo.getMboSet("PRLINE");
                if(null==pmlineSet && pmlineSet.isEmpty()){
                    pmSet.deleteAll(2L);
                    pmSet.save();
                    this.clientSession.showMessageBox(this.clientSession.getCurrentEvent(), "system", "deleterecord", (Object[])null);
                    this.gotoTab(this.clientSession, "list");
                    initializeApp();
                }else{
                    this.clientSession.showMessageBox(this.clientSession.getCurrentEvent(), new MXApplicationException("prsubtosrm", "notdelete", new String[0]));
                }

            }else{
                return super.DELETE();
            }
        }
        return 1;
    }

}
