package psdi.webclient.beans.pmexec;
import java.rmi.RemoteException;

import psdi.app.workorder.WO;
import psdi.app.workorder.WORemote;
import psdi.app.workorder.WOSet;
import psdi.app.workorder.WOSetRemote;
import psdi.mbo.MboRemote;
import psdi.mbo.MboSetRemote;
import psdi.server.MXServer;
import psdi.util.MXApplicationException;
import psdi.util.MXException;
import psdi.webclient.system.beans.DataBean;
import psdi.webclient.system.controller.*;
import com.coolservlets.beans.method.DateConvertor;
import com.coolservlets.beans.method.genMethod;
import com.dbms.dbcon.*;
import com.report.*;
import psdi.security.ConnectionKey;
public class SpotrunlinesTableBean extends DataBean
{
    //String[] FldSingle = {"PROJECTID","PROJECTNAME","PROVINCE","CITY","COUNTY","VILLAGE","POSITION","LAND","LANDFORM","POWERTYPE","HEIGHTASL","FRESOURCE","DESIGDEPT","CONSTRUCTION","CAPINSTALL","UNITCAPACITY","POWERYEAR","EQUHOURS","STAINVESTMENT","DYNINVESTMENT","INVUNITKW","INVUNITELEDEG","CONINTEREST","WPCOSTUNIT","TDCOSTUNIT","FUCOSTUNIT","SBUNITPRICE","CONEXCAVATION","CONBACKFILL","CONCRETE","REINFORCED","TOWERDRUM","PERMANENTLAND","TEMPLAND","FIRGENERATING","TOTALTIME"};
    String[] FldSingle = {"SPOTRUNLINENUM","DESCRIPTION","POSITION","WORKTYPE","STATUS","POINTSTANDARD","POINTMETHOD","POINTDATUM","UNSUAL","FREQUENCY","FREQUNIT","TASKTIME","PERPLAN","PERACTUAL","PLANDATE","ACTDATE","ISEXCEPTION","VALUENUMBER","RECORDDESC","REMARKS","LOCATION","ASSETNUM"};
    public SpotrunlinesTableBean()
    {
    }

    public void initialize() throws MXException, RemoteException
    {
        /*
         * 初始化表格,重写了DataBean 中的 initialize() 方法。
         */
        super.initialize();
        /*
         * 初始化获得runlogtext_LOG_TEXT表的数据Bean
         */
        DataBean databean = app.getDataBean("spotrunlines_spotrunlines_22_table");
        int loop = databean.count();
        for(int i=0;i<loop;i++){
            if(databean.getMbo(i) != null){
                int nloop = FldSingle.length;
                for(int n=0;n<nloop;n++){
                    databean.getMbo(i).setFieldFlag(FldSingle[n],7L,false);
                }
            }
        }
        databean.refreshTable();
        sessionContext.queueRefreshEvent();
    }

    public int addrow() throws MXException

    {
        try {
            super.addrow();
            DataBean databean = app.getDataBean("spotrunlines_spotrunlines_22_table");
            int count = databean.count();
            //setValue("SPOTRUNLINESID","填写具体值",11L);//SPOTRUNLINES Unique identification
            //setValue("PROJECTNUM","填写具体值",11L);//SPOTRUNLINES Spot check Project No
            //开始自动设置编号 Begin
            String orgIdStr = getMbo().getOwner().getString("ORGID");
            orgIdStr = (orgIdStr == null) ? "":orgIdStr.trim().toUpperCase();
            String siteIdStr = getMbo().getOwner().getString("SITEID");
            siteIdStr =(siteIdStr == null) ? "":siteIdStr.trim();
            String preixstr ="ITE";
            String startnumstr = (DateConvertor.toDB2Date(DateConvertor.getCurrentDate())).substring(0,7);
            ConnectionKey connectionkey = getMbo().getUserInfo().getConnectionKey();//获得连接关键字
            String sKeynum =  getAutoKey(orgIdStr,siteIdStr,preixstr,startnumstr,connectionkey);
            setValue("SPOTRUNNUM",sKeynum,11L);//SPOTRUNLINES Department No
            //开始自动设置编号End
            String sDescription = sKeynum + " " + "Principaux messages";
            //setValue("SPOTRUNLINENUM",sDescription,11L);// Spot check Project No
            //setValue("POSITION","Informations de localisation",11L);// position
            //setValue("POINTDATUM","Informations de base",11L);// defining principle
            //setValue("PERPLAN","Informations sur le personnel",11L);// Implementation team
            //setValue("ISEXCEPTION","Résultats des contr?les ponctuels",11L);// Is Exception
            //setValue("SPOTRUNLINES5","填写具体值",11L);//SPOTRUNLINES Additional Fields 6
            setValue("ORGID",getMbo().getOwner().getString("ORGID"),11L);//
            setValue("SITEID",getMbo().getOwner().getString("SITEID"),11L);//
            setValue("PMPOINTNUM",getMbo().getOwner().getString("PMPOINTNUM"),11L);//
            setValue("SPOTRUNNUM",getMbo().getOwner().getString("SPOTRUNNUM"),11L);//
            //setValue("ISEXCEPTION","Résultats des contr?les ponctuels",11L);// Is Exception
            setValue("ISEXCEPTION", String.valueOf(0),11L);//PMPOINTNUM
            setValue("SPOTRUNLINES5", String.valueOf(0),11L);//PMPOINTNUM
            getMbo().setFieldFlag("SPOTRUNLINES5",7L,true);
            return 1;
        }
        catch (RemoteException remoteexception) {
            remoteexception.printStackTrace();
            throw new MXApplicationException("", "添加数据行有误，请与系统管理员联系！");
            //return 0;
        }
    }
    public int showdialog() throws MXException, RemoteException {
        RequestHandler.showDialog(sessionContext, "tabledocedit");
        return 1;
    }

    public int createwo() throws MXException, RemoteException {
        MboSetRemote spotrunline = app.getAppBean().getMbo().getMboSet("SPOTRUN_SPOTRUNLINES");
        String fspotrunnum = spotrunline.getString("SPOTRUNNUM");
        fspotrunnum =(fspotrunnum == null)?"":fspotrunnum.trim();
        int count = spotrunline.count();
        if(count > 0){
            MboRemote linembo = spotrunline.getMbo();
            //点检执行编号
            String spotrunnum = linembo.getString("SPOTRUNNUM");
            spotrunnum =(spotrunnum == null)?"":spotrunnum.trim();
            String spotrunlinenum = linembo.getString("SPOTRUNLINENUM");
            spotrunlinenum =(spotrunlinenum == null)?"":spotrunlinenum.trim();
            String description = linembo.getString("DESCRIPTION");
            description =(description == null)?"":description.trim();
            String assetnum = linembo.getString("ASSETNUM");
            assetnum =(assetnum == null)?"":assetnum.trim();
            String location = linembo.getString("LOCATION");
            location =(location == null)?"":location.trim();
            WOSet woSet = (WOSet)linembo.getMboSet("$WORKORDER_TEMP","WORKORDER");
            //woSet.setAutoKeyFlag(false);
            WO woremote = (WO)woSet.add();
            String sPersonid = app.getAppBean().getMbo().getUserInfo().getPersonId();
            sPersonid =(sPersonid == null) ?"":sPersonid.trim();
            sPersonid = sPersonid.toUpperCase();
            woremote.setValue("reportedby", getMbo().getUserInfo().getUserName(),11L);
            woremote.setValue("WO18", getMbo().getUserInfo().getUserName(),11L);
            woremote.setValue("lead", getMbo().getUserInfo().getUserName(),11L);
            woremote.setValue("worktype", "PM", 11L);
            woremote.setFieldFlag("reportedby",7L,true);
            woremote.setFieldFlag("WO18",7L,true);
            woremote.setValue("WOLO10", "0");
            //long l = woremote.getUniqueIDValue();
            woremote.setValue("SPOTRUNNUM", spotrunnum);
            woremote.setValue("SPOTRUNLINENUM", spotrunlinenum);
            woremote.setValue("description", description+"点检项目异常");
            woremote.setValue("STATUS", "WAPPR",11L);
            woremote.setValue("ASSETNUM", assetnum,11L);
            woremote.setValue("LOCATION", location,11L);
            MboSetRemote nPersonSets = app.getAppBean().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();
                    woremote.setValue("HDDEPT", deptnum,11L);
                    woremote.setValue("HDONGROUP", deptnum,11L);
                    woremote.setFieldFlag("HDDEPT",7L,true);
                    woremote.setFieldFlag("HDONGROUP",7L,true);
                }
            }
            woSet.save();
            long l = woremote.getUniqueIDValue();
            sessionContext.queueEvent(new WebClientEvent("changeapp", app.getId(), "wodaily", null, null, l, sessionContext));
        }
        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;
                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;
    }
}
