package weaver.interfaces.zw.workflow.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.kq.service.KQShiftScheduleService;
import com.engine.kq.service.impl.KQShiftScheduleServiceImpl;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.interfaces.zw.utils.CommonUtil;
import weaver.soa.workflow.request.RequestInfo;

import java.time.LocalDate;
import java.util.*;

/**
 * @author shil
 * @date 2024/8/1
 *  流程生成排班
 */
public class Htpblc2SchedulingEditAction implements Action {

    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean bb = new BaseBean();
        String requestid = requestInfo.getRequestid();
        String workflowid = requestInfo.getWorkflowid();
        String billtable = requestInfo.getRequestManager().getBillTableName();

        int creator = requestInfo.getRequestManager().getCreater();
        bb.writeLog("creator:"+creator);
        User creatorUser = new User(creator);
        bb.writeLog("creatorUser:"+creatorUser.getLastname());

        RecordSet rs = new RecordSet();
        bb.writeLog("----Htpblc2SchedulingEditAction------");
        DepartmentComInfo departmentComInfo = null;
        ResourceComInfo resourceComInfo = null;
        try {
            departmentComInfo = new DepartmentComInfo();
            resourceComInfo = new ResourceComInfo();
            String mainid = "" ;
            String pbyf = "" ;
            String cjrbm = "" ;
            String sql = " select id,cjr,pbyf,cjrbm,pbmd from "+billtable+" where requestid="+requestid;
            rs.execute(sql);
            if(rs.next()){
                mainid = Util.null2String(rs.getString("id"));
                pbyf = Util.null2String(rs.getString("pbyf"));
                cjrbm = Util.null2String(rs.getString("cjrbm"));
            }

            List<Map<String,String>> requestList = queryRequestList(billtable,cjrbm,pbyf,workflowid,requestid);
            if(!requestList.isEmpty() && requestList.size() >0){
                String requestname = requestList.get(0).get("requestname");
                String cjrbmmc = departmentComInfo.getDepartmentname(cjrbm);
                String currentnodetype = requestList.get(0).get("currentnodetype");
                String requesttypename = "";
                if ("1".equals(currentnodetype) || "2".equals(currentnodetype)) {
                    requesttypename = "正在审批";
                } else if ("3".equals(currentnodetype)) {
                    requesttypename = "已归档";
                }
                requestInfo.getRequestManager().setMessageid("1000");
                requestInfo.getRequestManager().setMessagecontent(cjrbmmc+"已存在"+pbyf+"的排班申请"+requesttypename+"流程:<"+requestname+">,无法提交当前流程");
                return Action.FAILURE_AND_CONTINUE;
            }else{

                String message = "";
                int daysInMonth = 0;
                if(StringUtils.isNotBlank(pbyf) && pbyf.length() == 7){
                    LocalDate date = LocalDate.parse(pbyf + "-01"); // 获取当前日期
                    daysInMonth = date.lengthOfMonth(); // 获取本月有多少天
                }
                bb.writeLog("----mainid------"+mainid);
                bb.writeLog("----daysInMonth------"+daysInMonth);
                if(StringUtils.isNotBlank(mainid))
                {
                    int errcount = 0;
                    Map<String,String> groupNameMap = queryGroupData();

                    sql = " select * from "+billtable+"_dt1 where mainid="+mainid;
                    bb.writeLog("----sql------"+sql);
                    List<Map<String,String>> dt1List = CommonUtil.queryListBySql(sql);
                    for(int i=0;i<dt1List.size();i++)
                    {
                        Map<String,String> dt1Map = dt1List.get(i);
                        String resourceid = Util.null2String(dt1Map.get("yg"));

                        Map<String,Set<String>> userGroupsMap = getUsergroupByDate(dt1Map, pbyf,daysInMonth);
                        for (Map.Entry<String, Set<String>> entry : userGroupsMap.entrySet()) {
                            String userActiveGroupId = entry.getKey();
                            Set<String> dateSet = entry.getValue();

                            bb.writeLog("----userActiveGroupId------"+userActiveGroupId);
                            bb.writeLog("----dateSet------"+dateSet.size());
                            dateSet.forEach(element ->bb.writeLog("date:"+element));

                            String status = getUserScheduleData(dt1Map,pbyf,userActiveGroupId,dateSet,creatorUser,daysInMonth);
                            if(!"".equals(status)){
                                message += resourceComInfo.getLastname(resourceid)+"在考勤组:<"+groupNameMap.get(userActiveGroupId)+">的排班异常;";
                                errcount++;
                            }
                        }
                    }

                    if(errcount > 0){
                        requestInfo.getRequestManager().setMessageid("1000");
                        requestInfo.getRequestManager().setMessagecontent(message);
                        return Action.FAILURE_AND_CONTINUE;
                    }
                }else{
                    requestInfo.getRequestManager().setMessageid("1000");
                    requestInfo.getRequestManager().setMessagecontent("获取流程数据异常");
                    return Action.FAILURE_AND_CONTINUE;
                }
            }
        }catch (Exception e){
            requestInfo.getRequestManager().setMessageid("1000");
            requestInfo.getRequestManager().setMessagecontent("流程提交接口异常");
            return Action.FAILURE_AND_CONTINUE;
        }

        return Action.SUCCESS;
    }


    public Map<String,Set<String>> getUsergroupByDate(Map<String,String> dt1Map,String pbyf,int daysInMonth){
        BaseBean bb = new BaseBean();

        Map<String,Set<String>> userGroupsMap = new HashMap<String,Set<String>>();

        String resourceid = Util.null2String(dt1Map.get("yg"));
        if(StringUtils.isNotBlank(resourceid)){
            List<Map<String,String>> userGroupList = getUserKqGroupData(resourceid);
            for(int k=1;k<=daysInMonth;k++){
                String kqdate = "";
                if(k<10){
                    kqdate = pbyf+"-0"+k;
                }else{
                    kqdate = pbyf+"-"+k;
                }
                String userActiveGroupId = "";
                for(int p = 0;p<userGroupList.size();p++){
                    Map<String,String> userGroupMap = userGroupList.get(p);

                    String validatefrom = userGroupMap.get("validatefrom");
                    String validateto = userGroupMap.get("validateto");
                    bb.writeLog("resourceid:"+resourceid+" validatefrom:"+validatefrom);
                    bb.writeLog("resourceid:"+resourceid+" validateto:"+validateto);

                    if(kqdate.compareTo(validatefrom) >= 0 && kqdate.compareTo(validateto) <=0){
                        userActiveGroupId = userGroupMap.get("groupid");
                    }
                }
                if(userGroupsMap.containsKey(userActiveGroupId)){
                    Set<String> dataSet = userGroupsMap.get(userActiveGroupId);
                    dataSet.add(kqdate);
                    userGroupsMap.put(userActiveGroupId,dataSet);
                }else{
                    Set<String> dataSet = new HashSet<String>();
                    dataSet.add(kqdate);
                    userGroupsMap.put(userActiveGroupId,dataSet);
                }
            }
        }

        return userGroupsMap;
    }


    public String getUserScheduleData(Map<String,String> dt1Map,String pbyf,String userActiveGroupId,Set<String> dateSet,User creatorUser,int daysInMonth){
        BaseBean bb = new BaseBean();
        String resourceid = Util.null2String(dt1Map.get("yg"));

        String status = "";
        Map<String,String> scheduleMap = queryScheduleDataByActiveGroupId(resourceid,pbyf,userActiveGroupId);


        JSONArray datasArray = new JSONArray();

        JSONArray kqdata = new JSONArray();
        for(int k=1;k<=daysInMonth;k++){
            String kqdate = "";
            if(k<10){
                kqdate = pbyf+"-0"+k;
            }else{
                kqdate = pbyf+"-"+k;
            }

            if(StringUtils.isNotBlank(userActiveGroupId)){
                if(dateSet.contains(kqdate)){
                    String serialid = Util.null2String(dt1Map.get("bc"+k));
                    if(StringUtils.isNotBlank(serialid)){
                        JSONObject bcJSON = new JSONObject();
                        String id = "";
                        if(scheduleMap.containsKey(resourceid+"_"+serialid+"_"+userActiveGroupId+"_"+kqdate)){
                            id = scheduleMap.get(resourceid+"_"+serialid+"_"+userActiveGroupId+"_"+kqdate);
                        }
                        bb.writeLog(resourceid+":id:"+id);
                        bcJSON.put("id",id);
                        bcJSON.put("serialid",serialid);
                        bcJSON.put("date",kqdate);
                        kqdata.add(bcJSON);
                    }
                }
            }
        }

        JSONObject dataJSON = new JSONObject();
        dataJSON.put("resourceid",resourceid);
        dataJSON.put("kqdata",kqdata);
        datasArray.add(dataJSON);

        JSONObject datasJSON = new JSONObject();
        datasJSON.put("datas",datasArray);
        datasJSON.put("groupId", userActiveGroupId);
        bb.writeLog("data:"+datasJSON.toJSONString());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("data",datasJSON.toJSONString());
        Map<String, Object> apidatas = getService(creatorUser).save(params, creatorUser);
        bb.writeLog("apidatas:"+ JSONObject.toJSONString(apidatas));
        if(apidatas.containsKey("status")){
            status = Util.null2String(apidatas.get("status"));
        }
        return status;
    }


    public Map<String,String> queryScheduleDataByActiveGroupId(String userid,String pbyf,String activeGroupid){
        Map<String,String> dataMap = new HashMap<String,String>();
        BaseBean bb = new BaseBean();
        try {
            String sql = " select id,kqdate,resourceid,serialid,groupid from kq_shiftschedule where left(kqdate,7) = '"+pbyf+"' and resourceid in("+userid+") and isdelete =0 and groupid="+activeGroupid;
            bb.writeLog("sql:"+sql);
            List<Map<String,String>> scheduleList = CommonUtil.queryListBySql(sql);
            for(int i=0;i<scheduleList.size();i++){
                Map<String,String> scheduleMap = scheduleList.get(i);
                String kqdate = scheduleMap.get("kqdate");
                String resourceid = scheduleMap.get("resourceid");
                String serialid = scheduleMap.get("serialid");
                String groupid = scheduleMap.get("groupid");
                String id = scheduleMap.get("id");

                bb.writeLog("kqdate:"+kqdate);
                bb.writeLog("resourceid:"+resourceid);
                bb.writeLog("serialid:"+serialid);
                bb.writeLog("groupid:"+groupid);
                bb.writeLog("id:"+id);
                dataMap.put(resourceid+"_"+serialid+"_"+groupid+"_"+kqdate,id);
            }
        }catch (Exception e){

        }
        return dataMap;
    }


    /***
     *
     * @param billtable
     * @param cjrbm
     * @param pbyf
     * @param workflowid
     * @param requestid
     * @return
     */
    public List<Map<String,String>> queryRequestList(String billtable,String cjrbm,String pbyf,String workflowid,String requestid){

        List<Map<String,String>> requestList  = new ArrayList<Map<String,String>>();
        try{
            String sql =" select t.id,r.requestid,r.requestname,r.currentnodetype " +
                        " from "+billtable+" t " +
                        " inner join workflow_requestbase r on r.requestid = t.requestid " +
                        " where t.pbyf ='"+pbyf+"' " +
                        " and t.cjrbm ='"+cjrbm+"' " +
                        " and r.currentnodetype in(1,2,3) " +
                        " and r.workflowid = "+workflowid +
                        " and t.requestid <> "+requestid;
            requestList = CommonUtil.queryListBySql(sql);
        }catch (Exception e){

        }
        return requestList;
    }


    private KQShiftScheduleService getService(User user) {
        return (KQShiftScheduleService) ServiceUtil.getService(KQShiftScheduleServiceImpl.class, user);
    }



    public List<Map<String,String>> getUserKqGroupData(String userid){

        List<Map<String,String>> userGroupList = new ArrayList<Map<String,String>>();

        try{
            if(StringUtils.isNotBlank(userid)){
                String sql =" select distinct resourceid, groupid,status,validatefrom,validateto FROM ( \n" +
                        "   select a.id AS resourceid, b.groupid, a.status,b.validatefrom,b.validateto FROM HrmResource a, kq_groupmember b \n" +
                        "   where a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') \n" +
                        "   union all \n" +
                        "   select a.id AS resourceid, b.groupid, a.status,b.validatefrom,b.validateto FROM HrmResource a, kq_groupmember b \n" +
                        "   where a.subcompanyid1 = b.typevalue and b.type=2 and a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') \n" +
                        "   union all \n" +
                        "   SELECT a.id AS resourceid, b.groupid, a.status,b.validatefrom,b.validateto FROM HrmResource a, kq_groupmember b \n" +
                        "   WHERE a.departmentid = b.typevalue AND b.type=3 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') \n" +
                        "   UNION ALL \n" +
                        "   SELECT a.id AS resourceid, b.groupid, a.status,b.validatefrom,b.validateto FROM HrmResource a, kq_groupmember b \n" +
                        "   WHERE a.jobtitle = b.typevalue AND b.type=5 \n" +
                        "   AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) \n" +
                        "   and (b.isdelete is null or b.isdelete <> '1') \n" +
                        "   UNION ALL \n" +
                        "   SELECT a.id AS resourceid, b.groupid, a.status,b.validatefrom,b.validateto FROM HrmResource a, kq_groupmember b \n" +
                        "   WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') ) t\n" +
                        "   where resourceid="+userid ;
                userGroupList = queryListBySql(sql);
            }
        }catch (Exception e){

        }
        return userGroupList;
    }


    public List<Map<String,String>> queryListBySql(String sql){
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        try{
            if(StringUtils.isNotBlank(sql)){
                Map<String,String> map = new HashMap<String,String>();
                rs.executeQuery(sql);
                String[] column = rs.getColumnName();
                while (rs.next()){
                    map = new HashMap<String,String>();
                    for(int i=0;i<column.length;i++){
                        String value = rs.getString(column[i]);
                        map.put(column[i],value);
                    }
                    if(!map.isEmpty() && map.size()>0){
                        list.add(map);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("queryListBySql-e:"+e);
        }
        return list;
    }

    public Map<String,String> queryGroupData(){
        Map<String,String> groupNameMap = new HashMap<String,String>();
        RecordSet rs = new RecordSet();
        String sql = " select id,groupname from kq_group ";
        rs.executeQuery(sql);
        while (rs.next()){
            String id = Util.null2String(rs.getString("id"));
            String groupname = Util.null2String(rs.getString("groupname"));
            groupNameMap.put(id,groupname);
        }
        return groupNameMap;
    }

}
