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.biz.KQGroupBiz;
import com.engine.kq.biz.KQGroupComInfo;
import com.engine.kq.biz.KQGroupMemberComInfo;
import com.engine.kq.service.KQShiftScheduleService;
import com.engine.kq.service.impl.KQShiftScheduleServiceImpl;
import org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shil
 * @date 2024/8/1
 *  流程生成排班
 */
public class Htpblc2SchedulingEditActionbak 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 cjr = "" ;
            String pbyf = "" ;
            String cjrbm = "" ;
            String pbmd = "";
            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"));
                cjr = Util.null2String(rs.getString("cjr"));
                pbyf = Util.null2String(rs.getString("pbyf"));
                cjrbm = Util.null2String(rs.getString("cjrbm"));
                pbmd = Util.null2String(rs.getString("pbmd"));
            }

            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 lcid = requestList.get(0).get("requestid");
                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{

                int daysInMonth = 0;
                if(StringUtils.isNotBlank(pbyf) && pbyf.length() == 7){
                    LocalDate date = LocalDate.parse(pbyf + "-01"); // 获取当前日期
                    daysInMonth = date.lengthOfMonth(); // 获取本月有多少天
                }
                bb.writeLog("----mainid------"+mainid);
                if(StringUtils.isNotBlank(mainid))
                {
                    String cjrGroupid = getUserActiveGroupId(cjr);
                    bb.writeLog("cjrGroupid:"+cjrGroupid);

                    Map<String,String> scheduleMap = queryScheduleDataMap(billtable,mainid,pbyf);

                    JSONObject datasJSON = new JSONObject();
                    JSONArray datasArray = new JSONArray();

                    sql = " select * from "+billtable+"_dt1 where mainid="+mainid;
                    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"));



                        if(StringUtils.isNotBlank(resourceid)){
                            List<Map<String,String>> userGroupList = getUserKqGroupData(resourceid);
                            JSONArray kqdata = new JSONArray();
                            for(int k=1;k<=daysInMonth;k++){
                                String serialid = Util.null2String(dt1Map.get("bc"+k));
                                if(StringUtils.isNotBlank(serialid)){
                                    String kqdate = "";
                                    if(k<10){
                                        kqdate = pbyf+"-0"+k;
                                    }else{
                                        kqdate = pbyf+"-"+k;
                                    }

                                    String groupid = "";
                                    for(int n=0;n<userGroupList.size();n++){
                                        Map<String,String> userGrupMap = userGroupList.get(n);
                                        String validatefrom = userGrupMap.get("validatefrom");
                                        String validateto = userGrupMap.get("validateto");
                                        if(kqdate.compareTo(validatefrom)>=0 && kqdate.compareTo(validateto) < 0){
                                            groupid = userGrupMap.get("groupid");
                                        }
                                    }

                                    if(StringUtils.isNotBlank(groupid)){
                                        if(cjrGroupid.equals(groupid)){
                                            JSONObject bcJSON = new JSONObject();
                                            String id = "";
                                            if(scheduleMap.containsKey(resourceid+"_"+serialid+"_"+groupid+"_"+kqdate)){
                                                id = scheduleMap.get(resourceid+"_"+serialid+"_"+groupid+"_"+kqdate);
                                            }
                                            bb.writeLog(resourceid+":id:"+id);
                                            bcJSON.put("id",id);
                                            bcJSON.put("serialid",serialid);
                                            bcJSON.put("date",kqdate);
                                            kqdata.add(bcJSON);
                                        }
                                    }
                                }
                            }

//                            List<Map<String,String>> userGroupList = getUserKqGroupData(resourceid);
//                            Set<String> groupSet = new HashSet<String>();
//                            for(int k=1;k<=daysInMonth;k++){
//                                String kqdate = "";
//                                if(k<10){
//                                    kqdate = pbyf+"-0"+k;
//                                }else{
//                                    kqdate = pbyf+"-"+k;
//                                }
//                                for(int n=0;n<userGroupList.size();n++){
//                                    Map<String,String> userGrupMap = userGroupList.get(n);
//                                    String validatefrom = userGrupMap.get("validatefrom");
//                                    String validateto = userGrupMap.get("validateto");
//                                    if(kqdate.compareTo(validatefrom)>=0 && kqdate.compareTo(validateto) < 0){
//                                        String groupid = userGrupMap.get("groupid");
//                                        groupSet.add(groupid);
//                                    }
//                                }
//                            }

//                            for(String activeGroup : groupSet){
//                                JSONObject datasJSON = new JSONObject();
//                                JSONArray datasArray = new JSONArray();
//
//                                JSONArray kqdata = new JSONArray();
//                                for(int k=1;k<=daysInMonth;k++){
//                                    String serialid = Util.null2String(dt1Map.get("bc"+k));
//                                    if(StringUtils.isNotBlank(serialid)){
//                                        String kqdate = "";
//                                        if(k<10){
//                                            kqdate = pbyf+"-0"+k;
//                                        }else{
//                                            kqdate = pbyf+"-"+k;
//                                        }
//
//                                        String groupid = "";
//                                        // resourceid, groupid,status,validatefrom,validateto
//
//
//                                        for(int n=0;n<userGroupList.size();n++){
//                                            Map<String,String> userGrupMap = userGroupList.get(n);
//                                            String validatefrom = userGrupMap.get("validatefrom");
//                                            String validateto = userGrupMap.get("validateto");
//                                            if(kqdate.compareTo(validatefrom)>=0 && kqdate.compareTo(validateto) < 0){
//                                                groupid = userGrupMap.get("groupid");
//                                            }
//                                        }
//
//                                        if(StringUtils.isNotBlank(groupid)){
//                                            JSONObject bcJSON = new JSONObject();
//                                            String id = "";
//                                            if(scheduleMap.containsKey(resourceid+"_"+serialid+"_"+groupid+"_"+kqdate)){
//                                                id = scheduleMap.get(resourceid+"_"+serialid+"_"+groupid+"_"+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);
                        }
                    }

                    datasJSON.put("datas",datasArray);
                    datasJSON.put("groupId", cjrGroupid);

                    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")){
                        String status = Util.null2String(apidatas.get("status"));
                        if(!"1".equals(status)){
                            String message = Util.null2String(apidatas.get("message"));
                            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;
                    }
                }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;
    }

    /**
     *
     * @param billtable
     * @param mainid
     * @return
     */
    public List<Map<String,String>> queryScheduleData(String billtable,String mainid,String pbyf){

        List<Map<String,String>> scheduleList  = new ArrayList<Map<String,String>>();
        try {
            String userids = "" ;
            String sql = " select yg from "+billtable+"_dt1 where mainid="+mainid;
            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"));
                userids += StringUtils.isBlank(userids) ? resourceid : ","+resourceid ;
            }
            if(StringUtils.isNotBlank(userids)){
                sql = " select id,kqdate,resourceid,serialid,groupid from kq_shiftschedule where left(kqdate,7) = '"+pbyf+"' and resourceid in("+userids+") and (isdelete is null or isdelete = 0)";
                scheduleList = CommonUtil.queryListBySql(sql);
            }

        }catch (Exception e){

        }
        return scheduleList;
    }


    public Map<String,String> queryScheduleDataMap(String billtable,String mainid,String pbyf){
        Map<String,String> dataMap = new HashMap<String,String>();
        List<Map<String,String>> scheduleList  = new ArrayList<Map<String,String>>();
        BaseBean bb = new BaseBean();
        try {
            String userids = "" ;
            String sql = " select yg from "+billtable+"_dt1 where mainid="+mainid;
            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"));
                if(StringUtils.isNotBlank(resourceid)){
                    userids += StringUtils.isBlank(userids) ? resourceid : ","+resourceid ;
                }
            }

            if(StringUtils.isNotBlank(userids)){
                sql = " select id,kqdate,resourceid,serialid,groupid from kq_shiftschedule where left(kqdate,7) = '"+pbyf+"' and resourceid in("+userids+") and isdelete = 0 ";
                bb.writeLog("sql:"+sql);
                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 String getUserActiveGroupId(String userid){
        BaseBean bb = new BaseBean();

        KQGroupMemberComInfo kqGroupMemberComInfo = null;
        KQGroupComInfo kqGroupComInfo = null ;
        String activeGroupId = "";
        try{
            kqGroupMemberComInfo = new KQGroupMemberComInfo();
            kqGroupComInfo = new KQGroupComInfo();

            Map<String, List<String>> groupMemberMap = getUserGroup();

            String activeGroup = "";
            if(groupMemberMap.containsKey(userid)){
                List<String> groupIds = groupMemberMap.get(userid);
                bb.writeLog("groupIds:"+groupIds.size());

                for(String i : groupIds){
                    String isDelete = kqGroupComInfo.getIsdelete(i);
                    if(!"1".equals(isDelete)) {
                        String currentGroupId = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userid, DateUtil.getCurrentDate()));
                        if (i.equals(currentGroupId)) {
                            activeGroupId =  i;
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog(e);
        }
        return activeGroupId;
    }


    /***
     *
     * @return
     */
    public Map<String, List<String>> getUserGroup(){
        BaseBean bb = new BaseBean();
        Map<String, List<String>> groupMemberMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        String viewScope = "3";
        try {
            KQGroupBiz kqGroupBiz = new KQGroupBiz();
            Map<String, Object> groupParams = new HashMap<String, Object>();
            if("3".equals(viewScope)){
                groupParams.put("isNoAccount", "1");
            }
            rs.executeQuery(kqGroupBiz.getGroupMemberSql(groupParams));
            while (rs.next()) {
                String id = rs.getString("resourceid");
                String gid = rs.getString("groupid");
                if (!groupMemberMap.containsKey(id))
                    groupMemberMap.put(id, new ArrayList<>());
                groupMemberMap.get(id).add(gid);
            }
        } catch (Exception e) {
        }
        return groupMemberMap;
    }


    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;
    }

}
