package com.engine.htsc.collaboration.service;

import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.collaboration.entity.CoWorkEntity;
import weaver.conn.RecordSet;
import weaver.formmode.setup.CodeBuild;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.util.HT_Util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class WorkflowCoWorkService extends Service {

    /**
     * 创建协作事项
     * @param coWorkEntity
     * @return
     */
    private Map<String, Object> createCoWork(CoWorkEntity coWorkEntity){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();

        try{
            if(coWorkEntity!=null){
                String xzmodeid = pb.getPropName("UF_XZSY_CUBEUUIUD");
                JSONObject jsonObject_rw = pb.getModeInfoByUUID(xzmodeid);
                int modeid = Util.getIntValue(jsonObject_rw.getString("modeid"));

                String uuid = UUID.randomUUID().toString();
                coWorkEntity.setModeuuid(uuid);
                coWorkEntity.setFormmodeid(modeid);
                coWorkEntity.setModedatacreatertype(0);
                coWorkEntity.setModedatacreatedate(TimeUtil.getCurrentDateString());
                coWorkEntity.setModedatacreatetime(TimeUtil.getOnlyCurrentTimeString());
                coWorkEntity.setCjrq(TimeUtil.getCurrentTimeString());

                Class<?> clazz = coWorkEntity.getClass();
                Field[] fields = clazz.getDeclaredFields();
                String insertFields = " insert into uf_xzsy(";
                String paramsStr  = " values(";
                Object[] values = new Object[fields.length];
                for(int i=0;i<fields.length;i++){
                    fields[i].setAccessible( true );
                    if(i==fields.length-1){
                        insertFields += fields[i].getName()+" )";
                        paramsStr += "? )";
                    }else{
                        insertFields += fields[i].getName()+",";
                        paramsStr += "?,";
                    }
                    try{
                        values[i] = fields[i].get(coWorkEntity);
                    }catch (Exception e){
                        new BaseBean().writeLog("保存任务数据错误："+e);
                    }
                }
                String insertSql = insertFields + paramsStr;
                bs.writeLog("insertSql:"+insertSql);
                boolean res = rs.executeQuery(insertSql,values);
                bs.writeLog("res:"+res);

                if(res){
                    int billid = 0;
                    rs.executeQuery("select id from uf_xzsy where modeuuid='"+uuid+"'" );
                    if (rs.next()) {
                        billid = Util.getIntValue( rs.getString( "id" ) );
                        bs.writeLog("billid:"+billid);
                        ModeRightInfo moderight = new ModeRightInfo();
                        moderight.editModeDataShare(coWorkEntity.getModedatacreater(),coWorkEntity.getFormmodeid(),billid);
                    }

                    int formid = 0 ;
                    rs.executeQuery("select formid from modeinfo where id= "+ modeid);
                    if(rs.next()){
                        formid = Util.getIntValue(Util.null2String(rs.getString("formid")));
                    }
                    bs.writeLog("formid:"+formid);

                    String xzbh = "";
                    rs.executeQuery("select id,codefieldid from ModeCode where modeid=? and isuse='1'", new Object[]{modeid});
                    if(rs.next()) {
                        CodeBuild codeBuild = new CodeBuild(rs.getInt("id"));
                        codeBuild.setModeId(modeid);
                        codeBuild.setLanguage(7);
                        xzbh = codeBuild.getModeCodeStr(formid,billid);
                    }
                    bs.writeLog("xzbh:"+xzbh);

                    String sql = " update uf_xzsy set xzbh='"+xzbh+"',cjzt=1 where id="+billid;
                    bs.writeLog(sql);
                    boolean bool = rs.execute(sql);
                    if(bool){
                        result.put("billid",billid);
                        result.put("modeid",modeid);
                        result.put("formid",formid);
                        result.put("status","1");
                        result.put("message","协作创建成功");
                    } else{
                        result.put("billid","0");
                        result.put("status","-1");
                        result.put("message","新建协作异常，请联系系统管理员");
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.put("billid","0");
            result.put("status","-2");
            result.put("message","系统错误,请联系系统管理员");
        }
        return result;
    }

    /**
     * 重要事项
     * @param requestid
     * @return
     */
    public Map<String, Object> createFromImportantMatters(User user, String requestid){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();

        try{
            CoWorkEntity coWorkEntity = new CoWorkEntity();
            coWorkEntity.setGllc(requestid);
            String sql = "";

            sql = "select requestnamenew from WORKFLOW_REQUESTBASE where requestid = '"+requestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                coWorkEntity.setBt(Util.null2String(rs.getString("requestnamenew"))+"协作事项");
            }

            int creater = user.getUID();
//            int creater = 11260;
            coWorkEntity.setModedatacreater(creater);
            coWorkEntity.setCjr(creater);
            sql = "select departmentid from HRMRESOURCE where id = '"+creater+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                coWorkEntity.setSzbm(Integer.parseInt(Util.null2String(rs.getString("departmentid"))));
            }
            HT_Util ht_util=new HT_Util();
            coWorkEntity.setSzjg(Integer.parseInt(ht_util.getszjg(Integer.toString(creater))));


            coWorkEntity.setYxj(2);//高中低
            coWorkEntity.setXzzt(0);//拟稿 进行中 已完成
            result = createCoWork(coWorkEntity);
        }catch (Exception e){
            e.printStackTrace();
            result.put("billid","1");
            result.put("status","-2");
            result.put("message","系统错误,请联系系统管理员");
        }
        return result;
    }

    /**
     * 公司收文-主办部门
     * @param requestid
     * @return
     */
    public Map<String, Object> createFromReceipt(User user, String requestid){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();

        try{
            CoWorkEntity coWorkEntity = new CoWorkEntity();

            String mainRequestid = "";
            String sql = "select mainrequestid from WORKFLOW_SUBWFREQUEST where subrequestid = '"+requestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainRequestid = Util.null2String(rs.getString("mainrequestid"));
                coWorkEntity.setGllc(mainRequestid);
            }

            sql = "select requestnamenew from WORKFLOW_REQUESTBASE where requestid = '"+mainRequestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                coWorkEntity.setBt(Util.null2String(rs.getString("requestnamenew"))+"协作事项");
            }

            String mainTableName = JAVATools.getMaintable(mainRequestid);
            sql = "select fj from "+mainTableName+" where requestid = '"+mainRequestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                coWorkEntity.setXgwj(Util.null2String(rs.getString("fj")));
            }

            sql = "select zdtzydren from uf_lcrwrywh where lcxinxi = 'gsswzbbm'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                coWorkEntity.setTzydr(Util.null2String(rs.getString("zdtzydren")));
            }

            int creater = user.getUID();
            coWorkEntity.setModedatacreater(creater);
            coWorkEntity.setCjr(creater);
            coWorkEntity.setSzbm(user.getUserDepartment());
            HT_Util ht_util=new HT_Util();
            coWorkEntity.setSzjg(Integer.parseInt(ht_util.getszjg(String.valueOf(creater))));


            coWorkEntity.setYxj(2);//高中低
            coWorkEntity.setXzzt(0);//拟稿 进行中 已完成
            result = createCoWork(coWorkEntity);
        }catch (Exception e){
            e.printStackTrace();
            result.put("billid","1");
            result.put("status","-2");
            result.put("message","系统错误,请联系系统管理员");
        }
        return result;
    }
}
