package com.app.hxqh.udlld;

import com.alibaba.fastjson.JSONObject;
import com.app.hxqh.util.WorkFlowUtil;
import psdi.app.iface.spms.Spms2EamHandler;
import psdi.mbo.Mbo;
import psdi.mbo.MboRemote;
import psdi.mbo.MboSet;
import psdi.mbo.MboSetRemote;
import psdi.server.MXServer;
import psdi.util.MXApplicationException;
import psdi.util.MXException;
import psdi.workflow.WorkFlowServiceRemote;

import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 领料申请单/出库申请单Mbo
 */
public class UdlldMbo extends Mbo implements MboRemote {

    public UdlldMbo(MboSet ms) throws MXException, RemoteException {
        super(ms);
    }

    @Override
    public void save() throws MXException, RemoteException {
        super.save();
        if(isModified("STATUS")){
            setValue("STATUSDATE", new Date(), 2L);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String app = getThisMboSet().getApp();
        String appname=getString("APPNAME");
        String status=getString("STATUS");
        if ("UDLLD".equalsIgnoreCase(app) || "UDLLD".equalsIgnoreCase(appname) || "UDCLLLD".equalsIgnoreCase(app) || "UDCLLLD".equalsIgnoreCase(appname) ) {
            //当spms出库成功后，会更新eam领料单状态为 COMP，此时执行往EAM物资清单插入交易记录
            //psdi.app.iface.spms.Eam2SpmsService setStatusValue
            if("COMP".equalsIgnoreCase(status)){
                int udlldid=getInt("UDLLDID");
                String WONUM=getString("WONUM");//领料单号
                String orgid=getString("ORGID");
                String siteid=getString("SITEID");
                String workshop=getString("WORKSHOP");
                MboSetRemote deptCSet=getMboSet("$DEPT", "DEPT","SITEID='"+siteid+"' AND DEPTNUM='"+getString("WORKSHOP")+"'");
                String deptClass="";
                if(null!=deptCSet && !deptCSet.isEmpty()){
                    deptClass=deptCSet.getMbo(0).getString("DEPTTYPE");//部门类
                }
                MboSetRemote udlldSet=getMboSet("$UDLLDLINE","UDLLDLINE","PARENTID="+udlldid+" AND ORGID='"+orgid+"' AND SITEID='"+siteid+"'");
                int count=udlldSet.count();
                //EAM物资清单表 UDINVENTORY
                MboSetRemote udinvSet = MXServer.getMXServer().getMboSet("UDINVENTORY",MXServer.getMXServer().getSystemUserInfo());
                MboSetRemote udmatuSet = MXServer.getMXServer().getMboSet("UDMATUSETRANS",MXServer.getMXServer().getSystemUserInfo());
                MboSetRemote udreclistSet = MXServer.getMXServer().getMboSet("UDRECLIST",MXServer.getMXServer().getSystemUserInfo());//旧件回收清单
                MboSetRemote udrecSet = MXServer.getMXServer().getMboSet("UDRECOVERY",MXServer.getMXServer().getSystemUserInfo());//旧件回收主表
                MboSetRemote udreclineSet = MXServer.getMXServer().getMboSet("UDRECOVERYLINE",MXServer.getMXServer().getSystemUserInfo());//旧件回收子表
                if(null!=udlldSet && null!=udinvSet && null!=udmatuSet){
                    for(int i=0;i<count;i++){
                        MboRemote udlldMbo=udlldSet.getMbo(i);
                        String itemnum=udlldMbo.getString("ITEMNUM");
                        udinvSet.setWhere("ITEMNUM='"+itemnum+"' AND DEPTNUM='"+deptClass+"'");
                        udinvSet.reset();
                        if(null!=udinvSet && !udinvSet.isEmpty()){
                            //插入交易记录表
                            setudmatuSetValue( udmatuSet, itemnum, workshop, udlldMbo.getDouble("ACTUALQTYBASICUNIT"),udlldMbo,appname,"Storage");
                        }else{
                            MboRemote udinvMbo=udinvSet.add();
                            udinvMbo.setValue("ITEMNUM", itemnum);
                            udinvMbo.setValue("DEPTNUM", deptClass);
                            udinvMbo.setValue("ORGID", getString("ORGID"));
                            udinvMbo.setValue("SITEID", getString("SITEID"));
                            udinvMbo.getThisMboSet().save();
                            //插入交易记录表
                            setudmatuSetValue( udmatuSet, itemnum, workshop,udlldMbo.getDouble("ACTUALQTYBASICUNIT"), udlldMbo,appname,"Storage");
                        }
                        //-领料成功后，对需要回收的物料，生成到旧件回收任务应用中---一个领料单对应一个旧件回收任务-----liuxq start-----------
                        udreclistSet.setWhere(" itemnum='"+itemnum+"' and orgid='"+orgid+"' and siteid='"+siteid+"'");
                        udreclistSet.reset();
                        if(null!=udreclistSet && !udreclistSet.isEmpty()){
                            Double quantity = udlldMbo.getDouble("ACTUALQTYBASICUNIT");//实际出库数量
                            String CREATEBY = this.getString("CREATEBY");
                            Date STATUSDATE = this.getDate("STATUSDATE");
                            //先判断该领料单是否在旧件回收申请单
                            udrecSet.setWhere(" WONUM='"+WONUM+"' and siteid='"+siteid+"'");
                            udrecSet.reset();
                            if(udrecSet!=null && !udrecSet.isEmpty()){
                                Integer UDRECOVERYID = udrecSet.getMbo(0).getInt("UDRECOVERYID");
                                ((WorkFlowServiceRemote) MXServer.getMXServer().lookup("WORKFLOW")).initiateWorkflow("UDRECOVERY", udrecSet.getMbo(0));
                                insertUDRECOVERYLINE(udreclineSet,UDRECOVERYID,itemnum,quantity,udrecSet.getMbo(0));//插入明细

                            }else{
                                MboRemote recMbo = udrecSet.add();
                                Integer UDRECOVERYID = recMbo.getInt("UDRECOVERYID");
                                recMbo.setValue("RCNUM","JJHS"+UDRECOVERYID,11L);//旧件回收单号
                                recMbo.setValue("DESCRIPTION","JJHS-"+siteid+"-"+WONUM,11L);//描述-领料单创建
                                recMbo.setValue("STATUS","EDIT",11L);//状态
                                recMbo.setValue("WONUM",WONUM,11L);//领料申请单编号
                                recMbo.setValue("ORGID",orgid,11L);
                                recMbo.setValue("SITEID",siteid,11L);
                                recMbo.setValue("CREATEBY",CREATEBY,11L);
                                recMbo.setValue("CREATEDATE",STATUSDATE,11L);
                                ((WorkFlowServiceRemote) MXServer.getMXServer().lookup("WORKFLOW")).initiateWorkflow("UDRECOVERY", recMbo);
                                recMbo.getThisMboSet().save();//保存主表
                                insertUDRECOVERYLINE(udreclineSet,recMbo.getInt("UDRECOVERYID"),itemnum,quantity,recMbo);//插入明细
                            }
                        }
                        //-----------------------------------------------------------------------------------liuxq  end---------------
                    }
                }

            }
            if("EDIT".equalsIgnoreCase(status) || "CAN".equalsIgnoreCase(status) || "REJEDIT".equalsIgnoreCase(status)){//草稿
                MboSetRemote udlldlineSet=getMboSet("UDLLDLINE");
                if(null!=udlldlineSet && !udlldlineSet.isEmpty()){
                    for(int i=0;i<udlldlineSet.count();i++){
                        MboRemote lineMbo=udlldlineSet.getMbo(i);
                        lineMbo.setValue("UDWORKORDERID", getInt("UDWORKORDERID"), 2L);
                    }
                }
            }

        }
        //psdi.app.iface.spms.Eam2SpmsService setReturnStatusValue
        if ("UDTKD".equalsIgnoreCase(app) || "UDTKD".equalsIgnoreCase(appname) || "UDCLTKD".equalsIgnoreCase(app) || "UDCLTKD".equalsIgnoreCase(appname) ) {
            if("COMP".equalsIgnoreCase(status)){
                int udlldid=getInt("UDLLDID");
                String orgid=getString("ORGID");
                String siteid=getString("SITEID");
                String workshop=getString("WORKSHOP");
                MboSetRemote udlldSet=getMboSet("$UDLLDLINE","UDLLDLINE","PARENTID="+udlldid+" AND ORGID='"+orgid+"' AND SITEID='"+siteid+"'");
                int count=udlldSet.count();
                MboSetRemote udmatuSet = MXServer.getMXServer().getMboSet("UDMATUSETRANS",MXServer.getMXServer().getSystemUserInfo());
                if(null!=udlldSet && null!=udmatuSet){
                    for(int i=0;i<count;i++){
                        MboRemote udlldMbo=udlldSet.getMbo(i);
                        String itemnum=udlldMbo.getString("ITEMNUM");
                        //插入交易记录表
                        setudmatuSetValue( udmatuSet, itemnum, workshop, (-udlldMbo.getDouble("ORDERQTY")),udlldMbo,appname,"Distribute");
                    }
                }
            }
        }
    }

    /**
     * 插入交易记录表
     * @param udmatuSet
     * @param itemnum
     * @param workshop
     * @param udlldMbo
     * @throws RemoteException
     * @throws MXException
     */
    public void setudmatuSetValue(MboSetRemote udmatuSet,String itemnum,String workshop,double quantity,MboRemote udlldMbo,String appname,String issuetype) throws RemoteException, MXException {
        MboRemote udmatuMbo=udmatuSet.add();
        //ITEMNUM=:ITEMNUM and DEPTNUM=:DEPTNUM
        udmatuMbo.setValue("ITEMNUM", itemnum);
        udmatuMbo.setValue("DEPTNUM", workshop);
        udmatuMbo.setValue("QUANTITY", quantity);
        udmatuMbo.setValue("ISSUETYPE", issuetype);
        udmatuMbo.setValue("TRANSDATE", new Date());
        udmatuMbo.setValue("ENTERBY", getString("CREATEBY"));
        udmatuMbo.setValue("WONUM", getString("WONUM"));
        udmatuMbo.setValue("KOSTL", getString("KOSTL"));
        udmatuMbo.setValue("OUTBOUND", getString("OUTBOUND"));
        udmatuMbo.setValue("ORDERUNIT", udlldMbo.getString("ORDERUNIT"));
        udmatuMbo.setValue("BINNUM", udlldMbo.getString("BINNUM"));
        udmatuMbo.setValue("SJYDTYPE", udlldMbo.getString("SJYDTYPE"));
        udmatuMbo.setValue("AUFNR", udlldMbo.getString("AUFNR"));
        udmatuMbo.setValue("ORGID", udlldMbo.getString("ORGID"));
        udmatuMbo.setValue("SITEID", udlldMbo.getString("SITEID"));
        udmatuMbo.setValue("APPNAME", appname);
        udmatuMbo.getThisMboSet().save();
        //更新同步EAM物资清单状态
        udlldMbo.setValue("ISTBXBK", true);
        udlldMbo.setValue("TBXBKTME", new Date());
    }


    /**
     * 插入到旧件回收申请单明细表
     * @param ITEMNUM  物料编号
     * @param YYNUM    应还数量
     */
    public void insertUDRECOVERYLINE(MboSetRemote mboSet,Integer UDRECOVERYID,String ITEMNUM,Double YYNUM,MboRemote recMbo) throws RemoteException, MXException {
        MboRemote mbo = mboSet.add();//新增对象
        mbo.setValue("UDRECOVERYID",UDRECOVERYID,11L);//主子表关系
        mbo.setValue("ITEMNUM",ITEMNUM,11L);
        mbo.setValue("YYNUM",YYNUM,11L);
//        mbo.setValue("ISCANCEL",1,11L);
//        ((WorkFlowServiceRemote) MXServer.getMXServer().lookup("WORKFLOW")).initiateWorkflow("UDRECOVERY", recMbo);
        mbo.getThisMboSet().save();
    }



        @Override
    public MboRemote duplicate() throws MXException, RemoteException {
        return super.duplicate();
    }

    @Override
    public void add() throws MXException, RemoteException {
        super.add();
        String app = getThisMboSet().getApp();
        String appname=getString("APPNAME");
        String siteid=getString("SITEID");
        String userId = getThisMboSet().getUserName();//获取当前登录人
        if ( "UDLLD".equalsIgnoreCase(appname) || "UDLLD".equalsIgnoreCase(app)) {
            //1.”备注“，此选项改为“备件使用位置”，目前控制为GF51工厂必填，其他工厂暂不控制
            if("GF51".equalsIgnoreCase(siteid)){
                setFieldFlag("REMARKS", 128L, true);
            }else{
                setFieldFlag("REMARKS", 128L, false);
            }
        }
//        if ("UDLLD".equalsIgnoreCase(app) || "UDTKD".equalsIgnoreCase(app) || "UDLLD".equalsIgnoreCase(appname) || "UDTKD".equalsIgnoreCase(appname)) {
          String wonum="EAM"+getInt("UDLLDID");
          setValue("WONUM", wonum,2L);
          setValue("STATUS", "EDIT",2L);
          setValue("STATUSDATE", new Date(),2L);
          String userid=getUserInfo().getPersonId();
          MboSetRemote personSet=getMboSet("$PERSON", "PERSON","PERSONID='"+userid+"' ");
          if(null!=personSet && !personSet.isEmpty()){
//              setValue( "WORKSHOP", personSet.getMbo(0).getString("DEPARTMENT"),11L);
              setValue( "ORGID", personSet.getMbo(0).getString("LOCATIONORG"));
              setValue( "SITEID", personSet.getMbo(0).getString("LOCATIONSITE"));
          }
          MboSetRemote locSet=getMboSet("$LOCATIONS", "LOCATIONS","SITEID='"+getString("SITEID")+"' and TYPE='STOREROOM' ");
          if(null!=locSet && !locSet.isEmpty()){
              setValue("LOCNUM", locSet.getMbo(0).getString("LOCATION"),11L);
          }
//          MboSetRemote deptSet=getMboSet("$DEPT","DEPT","DEPTNUM=(SELECT DEPARTMENT FROM PERSON WHERE PERSONID='"+userid+"') AND SITEID='"+siteid+"' ");
//          if(null!=deptSet && !deptSet.isEmpty()){
////              setValue("UDZGR", deptSet.getMbo(0).getString("DIRECTOR"),11L);
//          }
          String displayname=getUserInfo().getPersonId();
          Date date=MXServer.getMXServer().getDate();
          String createdate=new SimpleDateFormat("yyyyMMdd").format(date);
//          String locdesc=getString("LOCATIONS.DESCRIPTION");
//          if("UDLLD".equalsIgnoreCase(app) || "UDLLD".equalsIgnoreCase(appname)){
              setValue("DESCRIPTION", siteid+"-"+displayname+"-"+createdate,2L);
              //新增的时候，成本中心默认是用户中的默认成本中心
//              if(isNew()){
//                  MboSetRemote userSet = MXServer.getMXServer().getMboSet("MAXUSER", MXServer.getMXServer().getSystemUserInfo());
//                  userSet.setWhere("USERID='"+userId+"'");
//                  userSet.reset();
//                  if(userSet!=null && !userSet.isEmpty()){
//                      String centerCost = userSet.getMbo(0).getString("MEMO");//默认成本中心
//                      setValue("KOSTL",centerCost,2L);//设置默认值
//                  }
//              }
//          }else if("UDTKD".equalsIgnoreCase(app) || "UDTKD".equalsIgnoreCase(appname)){
//              setValue("DESCRIPTION", siteid+"-"+locdesc+"-"+displayname+"-"+createdate,2L);
//          }
//        }
    }


    @Override
    public void init() throws MXException {
        super.init();
        try {
            String status = getString("STATUS");
            String appname=getString("APPNAME");
            String siteid=getString("SITEID");
            if("UDTKD".equalsIgnoreCase(appname) || "UDCLTKD".equalsIgnoreCase(appname)){//退库申请单&车辆退库单
                String[] mainFields = new String[] {"DESCRIPTION","WORKSHOP","LOCNUM","KOSTL","UDZGR","REMARKS","YWONUM","SJYDTYPE","AUFNR"};
                if("EDIT".equalsIgnoreCase(status) || "CAN".equalsIgnoreCase(status) || "REJEDIT".equalsIgnoreCase(status)){//草稿
                    setFieldFlag(mainFields, 7L, false);
                    getMboSet("UDLLDLINE").setFlag(7L, false);

                }
                if("INPRG".equalsIgnoreCase(status) || "SPMSSUC".equalsIgnoreCase(status) || "SPMSSFA".equalsIgnoreCase(status) ){//车间主任审核
                    setFieldFlag(mainFields, 7L, true);
                    getMboSet("UDLLDLINE").setFlag(7L, true);
                }
                if("COMP".equalsIgnoreCase(status) || "REJCAN".equalsIgnoreCase(status)){//完成
                    setFieldFlag(mainFields, 7L, true);
                    getMboSet("UDLLDLINE").setFlag(7L, true);
                }
            }else if ("UDLLD".equalsIgnoreCase(appname) || "UDCLLLD".equalsIgnoreCase(appname) ) {//领料申请单 &车辆领料单
                String[] mainFields2 = new String[] {"DESCRIPTION","WORKSHOP","LOCNUM","KOSTL","UDZGR","REMARKS","SJYDTYPE","AUFNR"};
                if("EDIT".equalsIgnoreCase(status) || "CAN".equalsIgnoreCase(status) || "REJEDIT".equalsIgnoreCase(status)){//草稿
                    setFieldFlag(mainFields2, 7L, false);
                    getMboSet("UDLLDLINE").setFlag(7L, false);
                    String sjydtype=getString("SJYDTYPE");
                    if("Z57".equalsIgnoreCase(sjydtype)){
                        setFieldFlag("AUFNR", 128L, true);
                    }else{
                        setFieldFlag("AUFNR", 7L, false);
                        setFieldFlag("AUFNR", 128L, false);

                    }
                    if ( "UDLLD".equalsIgnoreCase(appname) ) {
                        //1.”备注“，此选项改为“备件使用位置”，目前控制为GF51工厂必填，其他工厂暂不控制
                        if("GF51".equalsIgnoreCase(siteid)){
                            setFieldFlag("REMARKS", 128L, true);
                        }else{
                            setFieldFlag("REMARKS", 128L, false);
                        }
                    }
                }
                if("INPRG".equalsIgnoreCase(status)){//车间主任审核
                    setFieldFlag(mainFields2, 7L, true);
                    getMboSet("UDLLDLINE").setFlag(7L, true);
                }
                if("SPMSSUC".equalsIgnoreCase(status) || "SPMSSFA".equalsIgnoreCase(status) ){//TOSPMS
                    setFieldFlag(mainFields2, 7L, true);
                    getMboSet("UDLLDLINE").setFlag(7L, true);
                }
                if("COMP".equalsIgnoreCase(status) || "REJCAN".equalsIgnoreCase(status)){//完成
                    setFieldFlag(mainFields2, 7L, true);
                    getMboSet("UDLLDLINE").setFlag(7L, true);
//                    setFieldFlag("WOAPPNAME", 7L, true);
//                    setFieldFlag("WORKORDER", 7L, true);
                }
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }
}
