package com.api.customization.kq.util;

import com.alibaba.fastjson.JSON;
import com.engine.kq.biz.KQAttProcSetComInfo;
import com.engine.kq.biz.KQFlowActiontBiz;
import com.engine.kq.enums.KqSplitFlowTypeEnum;
import com.engine.kq.log.KQLog;
import com.engine.kq.wfset.bean.SplitBean;
import com.engine.kq.wfset.util.KQFlowEvectionUtil;
import com.engine.kq.wfset.util.KQFlowLeaveUtil;
import com.engine.kq.wfset.util.KQFlowOutUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KqCustomAction extends BaseBean implements Action {
    private KQLog kqLog = new KQLog();


    @Override
    public String execute(RequestInfo request) {
        //e8 的状态标识
        int DEDUCTION = 0;
        int FREEZE = 1;
        int RELEASE = 2;
        int CUSTOM = 3;
        this.writeLog("KqFreezeVacationAction", "do action on request:" + request.getRequestid());
        String requestid = request.getRequestid();
        kqLog.info("do KqFreezeVacationAction on requestid:"+requestid);
        int requestidInt = Util.getIntValue(requestid, 0);

        String workflowid = request.getWorkflowid();
        String formid = new WorkflowComInfo().getFormId(workflowid);
        KQAttProcSetComInfo kqAttProcSetComInfo = new KQAttProcSetComInfo();
        int cur_kqtype = Util.getIntValue(kqAttProcSetComInfo.getkqType(workflowid),-1);

        //解除限制吧
//        if(cur_kqtype != KqSplitFlowTypeEnum.LEAVE.getFlowtype()){
//            return Action.SUCCESS;
//        }

        try {
            List<SplitBean> splitBeans = new ArrayList<SplitBean>();
            List<String> custome_field = Lists.newArrayList();
            Map<String,String> custome_map = Maps.newHashMap();
            Map<String,String> result = new HashMap<>();

            KQFlowActiontBiz kqFlowActiontBiz = new KQFlowActiontBiz();
            ResourceComInfo rci = new ResourceComInfo();
            DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            RecordSet rs = new RecordSet();
            RecordSet rs1 = new RecordSet();
            String proc_set_sql = "select * from kq_att_proc_set where field001 = ? and field002 = ? ";
            rs.executeQuery(proc_set_sql, workflowid,formid);
            int kqtype = -1;
            String tableName = "";
            if(rs.next()){
                String proc_set_id = rs.getString("id");
                //得到这个考勤流程设置是否使用明细
                String usedetails = rs.getString("usedetail");
                 kqtype = Util.getIntValue(rs.getString("field006"));
                Map<String, String> map = new HashMap<>();
                if(requestidInt > 0){
                    map.put("requestId", "and t.requestId = " + requestidInt);
                }

                Map<String, String> sqlMap = kqFlowActiontBiz.handleSql(proc_set_id, usedetails, requestidInt,kqtype,map);

                //这里兼容下多考勤类型流程
                if (kqtype == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){
                    KQFlowLeaveUtil kqFlowLeaveUtil = new KQFlowLeaveUtil();
                    result = kqFlowLeaveUtil.handleKQLeaveAction(sqlMap, splitBeans, datetimeFormatter, Util.getIntValue(workflowid), requestidInt, rci);
                }else if (kqtype == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){
                    KQFlowEvectionUtil kqFlowEvectionUtil = new KQFlowEvectionUtil();
                    result = kqFlowEvectionUtil.handleKQEvectionAction(sqlMap, splitBeans, datetimeFormatter, Util.getIntValue(workflowid), requestidInt, rci);
                }else if (kqtype == KqSplitFlowTypeEnum.OUT.getFlowtype()){
                    KQFlowOutUtil kqFlowOutUtil = new KQFlowOutUtil();
                    result = kqFlowOutUtil.handleKQOutAction(sqlMap, splitBeans, datetimeFormatter, Util.getIntValue(workflowid), requestidInt, rci);
                }
                if(!result.isEmpty()){
                    String error = Util.null2String(result.get("message"));
                    request.getRequestManager().setMessageid("666" + request.getRequestid() + "999");
                    request.getRequestManager().setMessagecontent(error);
                    return Action.FAILURE_AND_CONTINUE;
                }
            }

            //这里兼容下多考勤类型流程
            if (kqtype == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){
                tableName = "kq_flow_split_temp_leave";
            }else if (kqtype == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){
                tableName = "kq_flow_split_temp_evection";
            }else if (kqtype == KqSplitFlowTypeEnum.OUT.getFlowtype()){
                tableName = "kq_flow_split_temp_out";
            }
            kqLog.info("KqCustomAction splitBeans:"+ JSON.toJSONString(splitBeans));
            String batchSql = "insert into "+tableName+ "("
                    + "requestid,workflowid,dataid,detailid,resourceid,fromdate,fromtime,"
                    + "todate,totime,newleavetype,duration,usedetail,durationrule,tablenamedb,fromdatedb,"
                    + "fromtimedb,todatedb,totimedb,durationdb,status,belongDate,D_Mins,serialid,"
                    + "changeType,subcompanyid,departmentid,jobtitle,companion,iscompanion"+getCustomField(custome_field,"field",null,
                    custome_map)+")"+
                    " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?"+getCustomField(custome_field,"param",null,
                    custome_map)+") ";
            List<List> params = new ArrayList<List>();

            String delSql = "delete from "+tableName+" where requestId=?";
            List<List> delparams = new ArrayList<List>();

            for(SplitBean bean : splitBeans){
                List<Object> beanParams =  new ArrayList<Object>();
                beanParams.add(bean.getRequestId());
                beanParams.add(bean.getWorkflowId());
                beanParams.add(bean.getDataId());
                beanParams.add(bean.getDetailId());
                beanParams.add(bean.getResourceId());
                beanParams.add(bean.getFromDate());
                beanParams.add(bean.getFromTime());
                beanParams.add(bean.getToDate());
                beanParams.add(bean.getToTime());
                beanParams.add(bean.getNewLeaveType());
                beanParams.add(Util.null2s(bean.getDuration(),"0"));
                beanParams.add(bean.getUsedetail());
                beanParams.add(bean.getDurationrule());
                beanParams.add(bean.getTablenamedb());
                beanParams.add(bean.getFromdatedb());
                beanParams.add(bean.getFromtimedb());
                beanParams.add(bean.getTodatedb());
                beanParams.add(bean.getTotimedb());
                beanParams.add(bean.getDurationDB());
                beanParams.add(bean.getStatus());
                beanParams.add(bean.getBelongDate());
                beanParams.add(bean.getD_Mins());
                beanParams.add(bean.getSerialid());
                beanParams.add(bean.getChangeType());
                beanParams.add(bean.getSubcompanyid());
                beanParams.add(bean.getDepartmentid());
                beanParams.add(bean.getJobtitle());
                beanParams.add(bean.getCompanion());
                beanParams.add(bean.getIscompanion());
                if(!custome_field.isEmpty()){
                    getCustomField(custome_field, "value",beanParams,custome_map);
                }

                params.add(beanParams);

                List<Object> delParam =  new ArrayList<Object>();
                delParam.add(bean.getRequestId());
                delparams.add(delParam);
            }
            if(!params.isEmpty()){
                boolean delOk = rs1.executeBatchSql(delSql, delparams);
                if(!delOk){
                    request.getRequestManager().setMessageid("666" + request.getRequestid() + "999");
                    request.getRequestManager().setMessagecontent(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(1232,weaver.general.ThreadVarLanguage.getLang())+"action"+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005361,weaver.general.ThreadVarLanguage.getLang())+""+params);
                    kqLog.info("KqCustomAction删除数据失败:"+requestid);
                    return Action.FAILURE_AND_CONTINUE;
                }

                boolean isOk = rs1.executeBatchSql(batchSql, params);
                if(!isOk){
                    request.getRequestManager().setMessageid("666" + request.getRequestid() + "999");
                    request.getRequestManager().setMessagecontent(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(1232,weaver.general.ThreadVarLanguage.getLang())+"action"+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005361,weaver.general.ThreadVarLanguage.getLang())+""+params);
                    return Action.FAILURE_AND_CONTINUE;
                }
            }else{
                kqLog.info("KqCustomAction没有数据:"+requestid);
            }
        } catch (Exception e) {
            kqLog.info("KqCustomAction:"+e);
            request.getRequestManager().setMessageid("11111" + request.getRequestid() + "22222");
            request.getRequestManager().setMessagecontent("请假流程【KqCustomAction】报错，请联系管理员！");
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }


    /**
     * 考勤流程中间表针对某个流程扩展字段
     * @param custome_field
     * @param key
     * @param beanParams
     * @param custome_map
     * @return
     */
    public String getCustomField(List<String> custome_field, String key, List<Object> beanParams,
                                 Map<String, String> custome_map) {
        String fieldValue = "";
        if(!custome_field.isEmpty()){
            for(int i = 0 ; i < custome_field.size() ; i++){
                String tmp_value = Util.null2String(custome_field.get(i));
                if(tmp_value.length() > 0){
                    if("field".equalsIgnoreCase(key)){
                        fieldValue += ","+tmp_value;
                    }else if("param".equalsIgnoreCase(key)){
                        fieldValue += ",?";
                    }else if("value".equalsIgnoreCase(key)){
                        String value = custome_map.get(tmp_value);
                        beanParams.add(value);
                    }
                }
            }
        }
        return fieldValue;
    }
}
