package nckd.jxccl.swc.utils;


import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import nckd.jxccl.swc.constants.SwcConstant;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class SwcUtils {

    /**
     * 根据入参日期获取所在年度最后一天
     * @param inputDate
     * @return
     */
    public static Date getLastDayOfYear(Date inputDate) {
        LocalDate localDate = inputDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        // 获取该年度最后一天
        LocalDate lastDay = localDate.with(TemporalAdjusters.lastDayOfYear());

        // 转换回Date
        return Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }


    /**
     * 根据薪酬项目编码获取薪酬项目ID
     * @param itemNos
     * @return
     */
    public static List<Long> getSalaryItemIdByNumber (List<String> itemNos) {
        List<Long> itemIds = new ArrayList<Long>();
        QFilter filter = new QFilter("number", QCP.in, itemNos);
        DynamicObject[] items = SwcConstant.SALARYITEM_ENTITY.load("id", filter.toArray());
        for(DynamicObject item : items) {
            itemIds.add(item.getLong("id"));
        }
        return itemIds;
    }

    /**
     * 获取所有薪资核算组ID
     */
    public static List<Long> getAllPayRollGrpIds () {
        List<Long> groupIds = new ArrayList<Long>();
        QFilter filter = new QFilter("iscurrentversion", QCP.equals, "1");
        filter.and("enable", QCP.equals, "1");
        DynamicObjectCollection groupCols = SwcConstant.PAYROLLGRP_HELPER.queryOriginalCollection("id", filter.toArray());
        return groupCols.stream().map(obj -> obj.getLong("id")).collect(Collectors.toList());
    }


    public static StringBuilder getSalaryDetailSql(List<Long> groupIds, Date startDate, Date endDate) {
        String ids = String.join(",",groupIds.stream().map(String::valueOf).toArray(String[]::new));
        String startDateStr = dateToStr(startDate, 1);
        String endDateStr = dateToStr(endDate, 2);

        StringBuilder sb = new StringBuilder();
        sb.append("/*dialect*/ SELECT a.fid groupId,\n" +
                "       a.fname groupName,\n" +
                "       b.forgid orgId,\n" +
                "       d.fid employeeId,\n" +
                "       d.fname empName,\n" +
                "       d.fempnumber empNumber,\n" +
                "       e.fnumber idCardNo,\n" +
                "       count(distinct to_char(b1.fpaydate,'yyyy-MM')) monthCount,\n" +
                "       sum(g.fcalamountvalue) amount\n" +
                "from t_hsas_payrollgrp a\n" +
                "left join t_hsas_calpayrolltask b on a.fid = b.fpayrollgroupid\n" +
                "left join t_hsas_calpayrolltask_a b1 on b1.fid = b.fid\n" +
                "left join t_hsas_calperson c on c.fcaltaskid = b.fid\n" +
                "left join t_hrpi_employee d on d.fid = c.femployeeid\n" +
                "left join t_hrpi_percre e on e.femployeeid = d.fid and e.fcredentialstypeid = '1010'\n" +
                "left join t_hsas_caltable f on f.fcaltaskid = b.fid and f.fcalpersonid = c.fid\n" +
                "left join t_hsas_caltableentry g on g.fid = f.fid\n" +
                "left join t_hsbs_salaryitem h on h.fid = g.fsalaryitemid\n" +
                "where 1 = 1 and b1.ftaskstatus in ('4','7','8','9') ---计算完成 9--已审核 7--审批处理中 8--审批通过 4 \n" +
                "  and a.fiscurrentversion = '1'\n" +
                "  and h.fnumber = 'JT_283'\n");
        sb.append("and b1.fpaydate >= '"+startDateStr+"'\n");
        sb.append("and b1.fpaydate <= '"+endDateStr+"'\n");
        sb.append("and a.fid in ("+ids+") \n");
        sb.append("group by a.fid, b.forgid, a.fname, d.fid, d.fname, d.fempnumber, e.fnumber");

        return sb;
    }

    /**
     *
     * 根据员工ID获取员工薪资明细
     * @param empId
     * @param salaryitem
     * @param startDate
     * @param endDate
     * @return
     */
    public static StringBuilder getSalaryDetailSqlByEmp(Long empId,String salaryitem, Date startDate, Date endDate) {

        String startDateStr = dateToStr(startDate, 1);
        String endDateStr = dateToStr(endDate, 2);

        StringBuilder sb = new StringBuilder();
        sb.append("/*dialect*/ SELECT  c.femployeeid,d.fname empName, \n")
                .append("   d.fempnumber empNumber, \n")
                .append("   count(distinct to_char(b1.fpaydate,'yyyy-MM')) monthCount, \n")
                .append("   sum(g.fcalamountvalue) amount \n")
                .append("from t_hsas_calpayrolltask b \n")
                .append("left join t_hsas_calpayrolltask_a b1 on b1.fid = b.fid \n")
                .append("left join t_hsas_calperson c on c.fcaltaskid = b.fid \n")
                .append("left join t_hrpi_employee d on d.fid = c.femployeeid \n")
                .append("left join t_hrpi_percre e on e.femployeeid = d.fid and e.fcredentialstypeid = '1010'\n")
                .append("left join t_hsas_caltable f on f.fcaltaskid = b.fid and f.fcalpersonid = c.fid \n")
                .append("left join t_hsas_caltableentry g on g.fid = f.fid \n")
                .append("left join t_hsbs_salaryitem h on h.fid = g.fsalaryitemid \n")
                .append("where 1 = 1 and b1.ftaskstatus in ('4','7','8','9')  ---计算完成 9--已审核 7--审批处理中 8--审批通过 4 \n")
                .append("and h.fnumber in (").append(salaryitem).append(") \n")
                .append("and b1.fpaydate >= '").append(startDateStr).append("' \n")
                //.append("and b1.fpaydate >= '2025-01-01 00:00:00' \n")
                .append("and b1.fpaydate <= '").append(endDateStr).append("' \n")
                .append("and c.femployeeid in (").append(empId).append(") \n")
                //.append("and c.femployeeid in (2311775636290546688) \n")
                .append("group by c.femployeeid,d.fname, d.fempnumber");

        return sb;
    }

    public static List<Long> getExcludePayRollGroupIds(Date startDate) {
        List<Long> excludeGroupIds = new ArrayList<Long>();
        QFilter filter = new QFilter("nckd_calyear", QCP.equals, startDate);
        DynamicObject[] cols = SwcConstant.SALANNUALINCOMEBILL_ENTITY.load("nckd_mulpayrollgrp", filter.toArray());
        for(DynamicObject col : cols) {
            excludeGroupIds.addAll(col.getDynamicObjectCollection("nckd_mulpayrollgrp").stream().map(obj -> obj.getLong("fbasedataid.id")).collect(Collectors.toList()));
        }
        return excludeGroupIds;
    }

    public static String dateToStr(Date date, int type) {
        if(type == 1) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(date);
        }
        else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = sdf.format(date);
            return dateStr + " 23:59:59";
        }
    }

}
