package nckd.jxccl.wtc.wtabm.web.validate;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.entity.validate.ErrorLevel;
import kd.sdk.hr.haos.business.helper.HAOSServiceHelper;
import nckd.jxccl.base.wtc.helper.WTCHelper;
import nckd.jxccl.wtc.wtabm.web.common.constant.WtcConstant;
import nckd.jxccl.wtc.wtabm.web.common.util.WtcUtils;

import java.util.*;
import java.util.stream.Collectors;

public class VaApplyCheckValidator extends AbstractValidator {

    /**
     * 休假申请单校验行政组织范围内是否存在关键岗位同时请假-工作流用
     */
    @Override
    public void validate() {
        // 操作标识 checkbyrole：根据工作流角色判断，checkbypar：根据直接上级判断
        String operateKey = this.getOperateKey();
        for (ExtendedDataEntity dataEntity : dataEntities) {
            DynamicObject bill = dataEntity.getDataEntity();
            // 当前用户ID
            long userId = RequestContext.getOrCreate().getCurrUserId();
            List<Long> allOrgIds = new ArrayList<Long>();
            List<Long> positionIds = new ArrayList<Long>();
            Date startDate = bill.getDate("startdate");
            Date endDate = bill.getDate("enddate");

            getKeyPositionIds(operateKey, allOrgIds, positionIds, userId);

            if(positionIds.size() > 0) {
                // 根据关键岗位 + 日期范围 获取休假单信息
                DynamicObjectCollection applyDyns = WTCHelper.getVaApplyInfo(positionIds, startDate, endDate, bill.getLong("id"));
                if (applyDyns.size() > 0) {
                    List<String> msgList = new ArrayList<String>();
                    StringBuilder sb = new StringBuilder();
                    int i = 1;
                    for (DynamicObject applyBill : applyDyns) {
                        String billNo = applyBill.getString("billno");
                        String empName = applyBill.getString("attfile.employee.name");
                        String orgName = applyBill.getString("attfile.adminorg.name");
                        String posName = applyBill.getString("attfile.position.name");
                        String startDateStr = WtcUtils.dateToStr(applyBill.getDate("startdate"), "yyyy-MM-dd");
                        String endDateStr = WtcUtils.dateToStr(applyBill.getDate("enddate"), "yyyy-MM-dd");
                        String msg = String.format(i + "、【%s】-【%s】-【%s】-【%s】-【%s】-【%s】", billNo, empName, orgName, posName, startDateStr, endDateStr);
                        msgList.add(msg);
                        i++;
                    }
                    String titleMsg = "以下单据存在其他关键岗位人员正在休假：\n ";
                    String errorMsg = titleMsg + String.join("\n ", msgList);
                    this.addWarningMessage(dataEntity, errorMsg);
                }
            }
        }
    }

    /**
     * 获取关键岗位ID
     * @param operateKey
     * @param allOrgIds
     * @param positionIds
     * @param userId
     */
    public void getKeyPositionIds (String operateKey, List<Long> allOrgIds, List<Long> positionIds, Long userId) {
        // 根据工作流角色判断
        if("checkbyrole".equals(operateKey)) {
            // 获取工作流角色中的组织
            DynamicObject role = WTCHelper.getWFRoleByUserId(WtcConstant.WTCROLE_NUMBER, userId);
            if (role != null) {
                List<Long> orgIds = new ArrayList<Long>();
                orgIds.add(role.getLong("roleentry.org.id"));
                // 根据工作流角色中维护的组织获取所有组织ID
                // 如果是包含下级的情况 查询所有的下级组织
                if (role.getBoolean("roleentry.includadminsub")) {
                    List<Map<String, Object>> subOrgMap = HAOSServiceHelper.querySubOrgToList(orgIds, new Date(), null);
                    allOrgIds.addAll(subOrgMap.stream().map(i -> Long.valueOf(i.get("orgId").toString())).collect(Collectors.toList()));
                }
                // 不包含下级
                else {
                    allOrgIds.add(role.getLong("roleentry.org.id"));
                }
            }
            // 获取组织范围内的关键岗位
            positionIds.addAll(WTCHelper.getKeyPositionByOrg(allOrgIds));
        }
        // 根据直接上级判断
        // 2025-12-12 查找当前用户的主职和兼职下的所有关键岗位
        else if ("checkbypar".equals(operateKey)) {
            // 获取当前用户对应的employeeId
            Long employeeId = WTCHelper.queryEmployeeIdByUserId(userId);
            // 获取员工当前的主职/兼职岗位
            DynamicObjectCollection empPosOrgRelDyns = WTCHelper.queryEmpPosOrgRelDyns(Arrays.asList(employeeId));
            List<Long> empPositionIds = empPosOrgRelDyns.stream().map(i -> i.getLong("position.id")).collect(Collectors.toList());
            // 添加下级岗级关键岗位
            positionIds.addAll(WTCHelper.getSubKeyPositions(empPositionIds));
        }
    }
}
