package nckd.jxccl.wtc.wtabm.web.common.util;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.IFormView;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.hr.hbp.common.util.HRDateTimeUtils;
import kd.hr.hbp.common.util.HRStringUtils;
import kd.sdk.hr.haos.business.helper.HAOSServiceHelper;
import org.apache.commons.lang3.ObjectUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Tyx
 * 2025-09-28
 * 考勤模块工具类
 */
public class WtcUtils {

    private static final Log log = LogFactory.getLog(WtcUtils.class);

    /**
     * 获取人员date所在年份的休假信息
     * // @param dyn 休假单数据包
     * @param employeeId 员工Id
     * @param date 休假开始日期
     * @param vaTypeNumber 休假类型编码
     */
    public static DynamicObjectCollection getHistoryVaApplyInfos (Long employeeId, Date date, String vaTypeNumber) {

        // 获取date所在年份的第一天和最后一天
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate startDate = LocalDate.of(localDate.getYear(), 1, 1);
        LocalDate endDate = LocalDate.of(localDate.getYear(), 12, 31);

        // 日期过滤
        QFilter dateFilter = new QFilter("enddate", QCP.large_equals, startDate);
        dateFilter.and("enddate", QCP.less_equals, endDate);

        // 人员
        QFilter personFilter = new QFilter("attfilebasef7.employee.id", QCP.equals, employeeId);

        // 单据版本过滤（存在变更，取最新的且时长不为0的），这里直接取审批通过的
        QFilter statusFilter = new QFilter("billstatus", QCP.in, new String[]{"A","B","C"});

        // 休假类型过滤
        QFilter typeFilter = new QFilter("entryentity.entryvacationtype.number", QCP.equals, vaTypeNumber);

        // 查询字段
        String selectFields = "startdate,enddate,applytime,billstatus,entryentity.entryvacationtype.name";

        // 查询数据
        DynamicObjectCollection billCols = QueryServiceHelper.query("wtabm_vaapply", selectFields, new QFilter[]{dateFilter, personFilter, statusFilter, typeFilter});
        return billCols;
    }

    /**
     * 获取参数
     * @param number
     * @param entityName
     * @return
     */
    public static Map<String, String> getWtcParams(String number, String entityName) {
        String selectField = "nckd_entryentity.nckd_key, nckd_entryentity.nckd_value";
        QFilter qFilter = new QFilter("number", "=", number);
        DynamicObject commonParam = BusinessDataServiceHelper.loadSingle(entityName, selectField, qFilter.toArray());
        if (ObjectUtils.isEmpty(commonParam)) {
            return null;
        } else {
            DynamicObjectCollection entryentity = commonParam.getDynamicObjectCollection("nckd_entryentity");
            if (entryentity != null && entryentity.size() != 0) {
                Map<String, String> mapentity = (Map)entryentity.stream().collect(Collectors.toMap((k) -> {
                    return k.getString("nckd_key");
                }, (v) -> {
                    return v.getString("nckd_value");
                }, (existing, replacement) -> {
                    return existing;
                }));
                return mapentity;
            } else {
                return null;
            }
        }
    }


    /**
     * 获取下级组织
     * @param adminOrgDyn
     * @return
     */
    public static Set getSubOrgFilters (DynamicObject adminOrgDyn, String field) {
        List<Long> adminOrgList = new ArrayList<Long>();
        adminOrgList.add(adminOrgDyn.getLong("id"));
        List<Map<String, Object>> subOrgs = HAOSServiceHelper.querySubOrgToList(adminOrgList, new Date(), null);
        Set subOrgIdset = subOrgs.stream().map(i -> i.get("orgId")).collect(Collectors.toSet());
        return subOrgIdset;
    }

    public static boolean checkQwndate(String beginDateKer, String endDateKer, IFormView view, String changeKey) {
        if (!HRStringUtils.isEmpty(beginDateKer) && !HRStringUtils.isEmpty(endDateKer) && view != null) {
            IDataModel model = view.getModel();
            Date beginDate = model.getDataEntity().getDate(beginDateKer);
            Date endDate = model.getDataEntity().getDate(endDateKer);
            if (beginDate != null && endDate != null) {
                int addMonth = 1;

                Date date = HRDateTimeUtils.addMonth(beginDate, addMonth);
                if (!endDate.before(date)) {
                    model.setValue(changeKey, (Object)null);
                    view.showTipNotification(ResManager.loadKDString("查询日期跨度不能超过{0}个月。", "AttrecordConstants_02", "wtc-wtte-common", new Object[]{addMonth}));
                    return false;
                } else {
                    return true;
                }
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    /**
     * 日期转yyyy-MM-dd
     * @param date
     * @return
     */
    public static String dateToStr(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }


}
