package com.api.customization.kq.util;

import com.alibaba.fastjson.JSON;
import com.engine.kq.biz.KQGroupBiz;
import com.engine.kq.biz.KQGroupComInfo;
import com.engine.kq.biz.KqShiftScheduleRoleBiz;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KqMembersValidateUtil {

    /**
     * 获取当前考勤组的人员开始生效日期
     * @param groupId
     * @param user
     * @return
     */
    public Map<String, String> getValidateFromData(String groupId, User user){
        List<Map<String, String>> result = new ArrayList<>();
        Map<String, List<Map<String, String>>> resultByResourceId = new HashMap<>();
        Map<String, String> validateFromMaps = new HashMap<>();
        Map<String, Integer> userIdLevelMap = new HashMap<>();
        try {
            RecordSet rs = new RecordSet();
            KQGroupComInfo kQGroupComInfo = new KQGroupComInfo();
            String status = "9";

            List<String> managerRoleUserIdList = new KqShiftScheduleRoleBiz().getUfKqShiftScheduleRoleValue((user==null ? "" : ""+user.getUID()), groupId);
            String viewscope = "0";//0：总部 1：分部 2：部门 3：人员 4：我的下属
            int pageIndex = 0;//Util.getIntValue(Util.null2String(params.get("pageIndex")), 1);
            int pageSize = 0;//Util.getIntValue(Util.null2String(params.get("pageSize")), 20);

            String sqlWhere = " ";
            if (status.length() > 0) {
                if (!status.equals("8") && !status.equals("9")) {
                    sqlWhere += " and t.status = " + status + "";
                } else if (status.equals("8")) {
                    sqlWhere += " and (t.status = 0 or t.status = 1 or t.status = 2 or t.status = 3) ";
                }
            }

            if (!Util.null2String(kQGroupComInfo.getExcludecount(groupId)).equals("1")) {
                //剔除无需排班人员
                String excludeid = Util.null2String(kQGroupComInfo.getExcludeid(groupId));
                if (excludeid.length() > 0) {
                    sqlWhere += " and t.resourceid not in (" + excludeid + ")";
                }
            }


            String backFields = " t.resourceid, t.validatefrom, t.validateto,t.groupid, t.status, t.dsporder,t.lastname,t.subcompanyid1, t.departmentid, t.loginid,t.type ";
            String sqlFrom = " from (SELECT distinct t.resourceid, t.validatefrom, t.validateto,t.groupid, t.status, t.dsporder,t.lastname,t.subcompanyid1, t.departmentid, t.loginid,t.type FROM (  \n" +
                    " SELECT a.id AS resourceid, b.validatefrom, b.validateto,b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid,b.type 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.validatefrom, b.validateto,b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid,b.type FROM HrmResource a, kq_groupmember b  \n" +
                    " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 and (b.isdelete is null or  b.isdelete <> '1')  \n" +
                    " UNION ALL  \n" +
                    " SELECT a.id AS resourceid, b.validatefrom, b.validateto,b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid,b.type FROM HrmResource a, kq_groupmember b  \n" +
                    " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 and (b.isdelete is null or  b.isdelete <> '1')  \n" +
                    " UNION ALL  \n" +
                    " SELECT a.id AS resourceid, b.validatefrom, b.validateto,b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid,b.type FROM HrmResource a, kq_groupmember b  \n" +
                    " WHERE  (a.jobtitle = b.typevalue AND b.type=5 and (b.isdelete is null or  b.isdelete <> '1') 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" +
                    " UNION ALL " +
                    " SELECT a.id AS resourceid, b.validatefrom, b.validateto,b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid,b.type 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 ) t where t.groupid = " + groupId;
//            if (!managerRoleUserIdList.isEmpty()) {
//                String allUserIds = StringUtils.join(managerRoleUserIdList, ',');
//                sqlFrom += " and " + Util.getSubINClause(allUserIds, "t.resourceid", "in");
//            }
            String groupBy = " ";

            String sql = backFields + sqlFrom + sqlWhere + groupBy;
            sql = " select " + sql;
            rs.executeQuery(sql);
            new BaseBean().writeLog("==zjValidateFromDatasql=="+sql);
            while (rs.next()) {
                String resourceId = Util.null2String(rs.getString("resourceid"));
                String validatefrom = Util.null2String(rs.getString("validatefrom"));
                validatefrom = "".equals(validatefrom) ? KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE : validatefrom;
                String validateto = Util.null2String(rs.getString("validateto"));
                validateto = "".equals(validateto) ? KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE : validateto;
                String key = resourceId+"|validatefrom";
                int type = Util.getIntValue(rs.getString("type"));
                int oldType = userIdLevelMap.getOrDefault(key, 0);
                boolean needAdd = false;
                if (oldType == 0) {  // 如果userIdLevelMap里面没有，就添加进去
                    needAdd = true;
                } else {
                    //1: 人力资源
                    //2：分部
                    //3：部门
                    //5：岗位
                    //6：所有人
                    //优先级： 人力资源>部门>分部>岗位>所有人
                    switch (type) {
                        case 1:
                            if(oldType == 1) {
                                needAdd = true;
                            }
                            break;
                        case 2:
                            if(oldType == 2 || oldType == 5 || oldType == 6) {
                                needAdd = true;
                            }
                            break;
                        case 3:
                            if(oldType == 3 || oldType == 2 || oldType == 5 || oldType == 6) {
                                needAdd = true;
                            }
                            break;
                        case 5:
                            if(oldType == 5 || oldType == 6) {
                                needAdd = true;
                            }
                            break;
                        default:
                            break;
                    }
                }
                if(needAdd) {
                    userIdLevelMap.put(key, type);
                    validateFromMaps.put(key, validatefrom);
                }
            }

        }catch (Exception e) {
            new BaseBean().writeLog(e);
        }
        return validateFromMaps;
    }

    /**
     * 判断当前日期是否可以修改排班
     * @param date
     * @param resourceId
     * @param isEdit
     * @param user
     * @param validateFromData
     * @return
     */
    public boolean isHave(String date,String resourceId,String isEdit,User user,Map<String, String> validateFromData){
        boolean isNonEdit = false;
        String today = DateUtil.getCurrentDate();
        String validatefrom = Util.null2String(validateFromData.get(resourceId + "|validatefrom"));//人员开始生效日期
        //如果生效日期是当月还是可以修改
        new BaseBean().writeLog("==zjvalidateFromData=="+JSON.toJSONString(validateFromData));
        new BaseBean().writeLog("==validatefrom=="+JSON.toJSONString(validatefrom));
        if (!"".equals(validatefrom) && validatefrom.length()>=7
                && (today.substring(0,7).compareTo(validatefrom.substring(0,7)) == 0)){
            return isNonEdit;
        }
        if (date.substring(0,7).compareTo(today.substring(0,7)) <= 0 && "1".equals(isEdit) && user.getUID()!=1){
            isNonEdit = true;
        }
        return isNonEdit;
    }

    public boolean isHave(String fromdate,String toDate,String resourceId,String isEdit,User user,Map<String, String> validateFromData){
        boolean isNonEdit = false;
        String today = DateUtil.getCurrentDate();
        String todayMonth = DateUtil.getCurrentDate().substring(0,7);
        String validatefrom = Util.null2String(validateFromData.get(resourceId + "|validatefrom"));//人员开始生效日期
        String fromMonth = fromdate.substring(0,7);//开始月份
        String toMonth = toDate.substring(0,7);//结束月份
        //如果生效日期是当月,且修改开始日期和结束日期都是当月，那还是可以改的
        if (!"".equals(validatefrom)&&todayMonth.compareTo(validatefrom.substring(0,7))==0
                && fromMonth.compareTo(todayMonth)==0
        && toMonth.compareTo(todayMonth)==0){
            return isNonEdit;
        }
        boolean isNextMonth= isNextMonth(fromMonth, toMonth,todayMonth);
        if (!isNextMonth && "1".equals(isEdit) && user.getUID()!=1){
            isNonEdit = true;
        }
        return isNonEdit;
    }

    /**
     * 判断当前日期是否可以修改排班(批量删除用的)
     * @param month
     * @param resourceId
     * @param isEdit
     * @param user
     * @param validateFromData
     * @return
     */
    public boolean isHaveDel(String month,String resourceId,String isEdit,User user,Map<String, String> validateFromData){
        boolean isNonEdit = false;
        String today = DateUtil.getCurrentDate();
        String todayMonth = DateUtil.getCurrentDate().substring(0,7);

        String validatefrom = Util.null2String(validateFromData.get(resourceId + "|validatefrom"));//人员开始生效日期
        //如果生效日期是当月还是可以修改
        if (!"".equals(validatefrom) && validatefrom.length()>=7
                && (todayMonth.compareTo(validatefrom.substring(0,7)) == 0)){
            return isNonEdit;
        }
        if (month.compareTo(todayMonth) <= 0 && "1".equals(isEdit) && user.getUID()!=1){
            isNonEdit = true;
        }
        return isNonEdit;
    }



    public  boolean isNextMonth(String fromMonth, String toMonth,String todayMonth) {
        boolean isNextMonth = false;
        if (fromMonth.compareTo(todayMonth) >0 && toMonth.compareTo(todayMonth)>0){
            isNextMonth = true;
        }
        return isNextMonth;
    }
}
