package psdi.webclient.beans.fincntrl;

import com.coolservlets.beans.method.DateConvertor;
import psdi.mbo.MboSetRemote;
import psdi.util.MXException;
import psdi.webclient.beans.workorder.WorkorderAppBean;

import java.rmi.RemoteException;

import com.coolservlets.beans.jdbc.MXConnection;
import com.dbms.dbcon.DBCon;
import com.dbms.dbcon.QueryResult;
import com.dbms.dbcon.ResultRow;
import psdi.mbo.MboSetRemote;
import psdi.security.ConnectionKey;
import psdi.server.MXServer;
import psdi.util.MXException;
import psdi.util.MXSession;
import psdi.webclient.system.beans.DataBean;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.util.Date;

public class CustFincntrlAppBean extends FincntrlAppBean {
    String[] FldMain = {"location", "assetnum", "failure", "problemcode", "STOREROOMMTLSTATUS", "istask", "AVAILSTATUSDATE", "apptrequired"};

    public void initializeApp() throws MXException, RemoteException {
        super.initializeApp();
    }

    public void initialize() throws MXException, RemoteException {
        super.initialize();
    }
    public synchronized boolean fetchRecordData() throws MXException, RemoteException {
        super.fetchRecordData();
        this.app.getAppBean().getMbo().setFlag(7L, false);//设置整个 mbo 所有字段不只读
        return true;
    }
    /**
     * 保存数据 2018-6-8 修改
     */
    public int SAVE() throws MXException, RemoteException {
        super.SAVE();
        return 1;
    }
    public int INSERT() throws MXException, RemoteException {
        super.INSERT();
        Date date = MXServer.getMXServer().getDate();
        String orgIdStr = getMbo().getInsertOrganization();
        orgIdStr = (orgIdStr == null) ? "":orgIdStr.trim().toUpperCase();
        String siteIdStr = getMbo().getInsertSite();
        siteIdStr =(siteIdStr == null) ? "":siteIdStr.trim();
        String sPersonid = getMbo().getUserInfo().getPersonId();
        sPersonid = (sPersonid == null) ? "" : sPersonid.trim();
        sPersonid = sPersonid.toUpperCase();
        String preixstr ="PRJ";
        String startnumstr = (DateConvertor.toDB2Date(DateConvertor.getCurrentDate())).substring(0,7);
        ConnectionKey connectionkey = getMbo().getUserInfo().getConnectionKey();//获得连接关键字
        String sKeynum =  getAutoKey(orgIdStr,siteIdStr,preixstr,startnumstr,connectionkey);
        sKeynum = (sKeynum == null)?"":sKeynum.trim();
        setValue("projectid",sKeynum,11L);//PMPOINTNUM
        getMbo().setFieldFlag("projectid",7L,true);
        setValue("createby", getMbo().getUserInfo().getUserName(), 11L);
        setValue("CREATEDATE", date.toLocaleString(),11L);
        setValue("WO18", getMbo().getUserInfo().getUserName(), 11L);
        setValue("lead", getMbo().getUserInfo().getUserName(), 11L);
        setValue("worktype", "PM", 11L);
        getMbo().setFieldFlag("reportedby", 7L, true);
        getMbo().setFieldFlag("WO18", 7L, true);
        //ConnectionKey connectionKey = getMbo().getUserInfo().getConnectionKey();
        String LaborDept[] = null;
        try {
            MboSetRemote nPersonSets = getMbo().getMboSet("$PERSON_TEMP", "PERSON");
            nPersonSets.setWhere("PERSONID ='" + sPersonid + "'");
            nPersonSets.reset();
            if (nPersonSets != null) {
                if (!nPersonSets.isEmpty()) {
                    String deptnum = nPersonSets.getMbo(0).getString("DEPARTMENT");
                    deptnum = (deptnum == null) ? "" : deptnum.trim();
                    String supervisor = nPersonSets.getMbo(0).getString("SUPERVISOR");
                    supervisor = (supervisor == null) ? "" : supervisor.trim();
                    setValue("APPLYDETP", deptnum, 11L);
                    //setValue("HDONGROUP", deptnum, 11L);
                    setValue("DUTY", supervisor, 11L);
                    getMbo().setFieldFlag("APPLYDETP", 7L, true);
                    //getMbo().setFieldFlag("HDONGROUP", 7L, true);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return 1;
    }

    /*
     *开始自动设置编号
     *
     */
    private  synchronized String  getAutoKey(String p_orgIdStr,String p_siteIdStr,String p_preixStr,String p_startnumStr,ConnectionKey connectionkey) throws MXException, RemoteException
    {
        //MXSession mxsession = sessionContext.getMXSession();
        String reKeyStr = "";
        try
        {
            //MXSession mxsession = sessionContext.getMXSession();
            //查找本年月自动编号的值
            StringBuffer sqllocal = new StringBuffer(300);
            sqllocal.append("select PREFIX,STARTNUM,SEED,SEEDLENGTH ").append(" from ").append("WTAUTOIDRULE").append(" where ORGID ="+"\'"+p_orgIdStr+"\'" + " AND SITEID ="+"\'"+p_siteIdStr+"\'"+ " AND RULETYPE ="+"\'"+"DATECYL"+"\'"
                    + " AND PREFIX ="+"\'"+p_preixStr+"\'"+ " AND STARTNUM ="+"\'"+p_startnumStr+"\'");
            //执行查询，返回一个结果集合
            //System.out.println("sqllocal.toString()"+sqllocal.toString());
            QueryResult result = DBCon.runQuery(sqllocal.toString(),connectionkey);
            if(result.size() >0){
                ResultRow resultRow = result.getRow(0);
                String seedStr = resultRow.getValue("SEED");
                String seedLenStr = resultRow.getValue("SEEDLENGTH");
                int seedLenInt = Integer.parseInt(seedLenStr);
                int newSeedInt = Integer.parseInt(seedStr);
                newSeedInt++;
                String setNewSeed = Integer.toString(newSeedInt);
                int loopCount = seedLenInt - seedStr.length();
                String newSeedStr = "";
                //补前导零
                for(int i=0;i<loopCount;i++){
                    newSeedStr = newSeedStr  + "0";
                }
                seedStr = newSeedStr + seedStr;
                reKeyStr = p_preixStr + p_startnumStr + "-"+seedStr;
                StringBuffer sqlupdate = new StringBuffer(300);
                sqlupdate.append("update WTAUTOIDRULE ").append("set SEED =" + setNewSeed).append(" where ORGID ="+"\'"+p_orgIdStr+"\'" + " AND SITEID ="+"\'"+p_siteIdStr+"\'"+ " AND RULETYPE ="+"\'"+"DATECYL"+"\'"
                        + " AND PREFIX ="+"\'"+p_preixStr+"\'"+ " AND STARTNUM ="+"\'"+p_startnumStr+"\'");
                DBCon.runUpdate(sqlupdate.toString(),connectionkey);
            }else{
                reKeyStr = p_preixStr + p_startnumStr + "-001";
                int newSeedInt = 2;
                String setNewSeed = Integer.toString(newSeedInt);
                StringBuffer sqlinsert = new StringBuffer(300);
                sqlinsert.append("insert into WTAUTOIDRULE(ORGID,SITEID,RULETYPE,PREFIX,STARTNUM,SEED,SEEDLENGTH,ROWSTAMP,WTAUTOIDRULEID,HASLD) ").append("values(").append("\'"+p_orgIdStr+"\',\'"+p_siteIdStr+"\',\'"+"DATECYL"+"\',\'"+
                        p_preixStr+"\',\'"+p_startnumStr+"\',"+setNewSeed+","+"3"+",\'\',WTAUTOIDRULEIDSEQ.NEXTVAL,0)");
                DBCon.runUpdate(sqlinsert.toString(),connectionkey);
            }
            //p_conn.commit();
        }
        catch(Exception exception) { }
        return reKeyStr;
    }
}
