package nckd.jxccl.hr.gzbb;

import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.login.utils.DateUtils;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.*;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 调度作业执行程序
 * 定时拉取数据模板下发采集任务
 * allSjcjmbTask01
 * duanyuqi
 * */
public class SjcjmbTask extends AbstractTask {

    private static final Log logger = LogFactory.getLog(SjcjmbTask.class);

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        logger.info("拉取数据采集模板进行下发");
        pushSjcjTask(map);
        logger.info("拉取数据采集模板进行下发结束");
    }

    public void pushSjcjTask(Map<String, Object> map) {
        // 查询所有模板
        List<QFilter> qfilter = new ArrayList<QFilter>();
        qfilter.add(new QFilter("billstatus", "=", "C"));
        if (map.get("org") != null) {
            String orgObject = map.get("org").toString();
            JSONObject orgJson = JSONObject.parseObject(orgObject);
            if (orgJson.get("id") != null) {
                qfilter.add(new QFilter("org.id", "=", orgJson.get("id")));
            }
        }
        QFilter[] filtersQuery = (QFilter[]) qfilter.toArray(new QFilter[qfilter.size()]);
        DynamicObjectCollection sjcjmbObjectCollection = QueryServiceHelper.query("nckd_sjcjmb", "id,billno,nckd_billname", filtersQuery);
        for (DynamicObject sjcjmbObject : sjcjmbObjectCollection) {
            Long mbId = sjcjmbObject.getLong("id");
            pushSjcjTaskSave(mbId);
        }
    }

    /**复制模板并保存采集任务，然后下发*/
    public void pushSjcjTaskSave(Long mbId) {
        DynamicObject sjcjmbObject = BusinessDataServiceHelper.loadSingle(mbId, "nckd_sjcjmb");
        Date nowDate = new Date();// 所属年月
        String yearMonth = DateUtils.formatDate(nowDate, "yyyy-MM");
        String billname = sjcjmbObject.getString("nckd_billname");// 任务名称

        // 处理填报开始时间
        String newBeginDateStr = "";
        Date newBeginDate = null;
        if (sjcjmbObject.getDate("nckd_tbkssj") != null) {
            String beginDayStr = DateUtils.formatDate(sjcjmbObject.getDate("nckd_tbkssj"), "dd");
            newBeginDateStr = yearMonth + "-" + beginDayStr;
            newBeginDate = DateUtils.parseDate(newBeginDateStr);
        }

        // 处理填报截止时间
        // 1. 将 Date 转换为 LocalDate
        LocalDate localDate = nowDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 2. 计算次月最后一天
        YearMonth nextMonth = YearMonth.from(localDate).plusMonths(1);
        LocalDate lastDay = nextMonth.atEndOfMonth();
        // 3. 将 LocalDate 转换回 Date
        Date resultDate = Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant());

        String nckd_remark = sjcjmbObject.getString("nckd_remark");// 描述

        DynamicObject sjcjrwObject = BusinessDataServiceHelper.newDynamicObject("nckd_sjcjrw");
        // 获取编号
        String sjcjrwBillNo = CodeRuleServiceHelper.getNumber("nckd_sjcjrw", sjcjrwObject, null);
        sjcjrwObject.set("billno", sjcjrwBillNo);// 单据编号
        sjcjrwObject.set("billstatus", "C");// 暂存
        sjcjrwObject.set("org", sjcjmbObject.get("org.id"));// 人事管理组织
        sjcjrwObject.set("nckd_billname", billname);//单据名称
        sjcjrwObject.set("nckd_ssny", nowDate);// 所属年月
        sjcjrwObject.set("nckd_tbkssj", newBeginDate);// 填报开始时间
        sjcjrwObject.set("nckd_tbjzsj", resultDate);// 填报截止时间
        sjcjrwObject.set("nckd_remark", nckd_remark);// 描述
        sjcjrwObject.set("nckd_sjzt", "2");// 数据状态
        sjcjrwObject.set("nckd_sfjtxf", "1");// 是否初始下发

        DynamicObjectCollection sjcjDynamicObjects = (DynamicObjectCollection) sjcjrwObject.get("nckd_sjcjrw_entry");

        //获取单据体对象
        DynamicObjectCollection sjcjmbDynamicObjects = (DynamicObjectCollection) sjcjmbObject.get("nckd_sjcjrw_entry");
        for (DynamicObject sjcjmbDynamicObject : sjcjmbDynamicObjects) {
            //创建一条单据体数据
            DynamicObject dynamicObjectNew = sjcjDynamicObjects.addNew();
            dynamicObjectNew.set("nckd_tbxzzz", sjcjmbDynamicObject.get("nckd_tbxzzz.id"));
            dynamicObjectNew.set("nckd_dxbbmc", sjcjmbDynamicObject.get("nckd_dxbbmc"));

            // 处理通知填报人员
            DynamicObjectCollection nckd_tztbry = sjcjmbDynamicObject.getDynamicObjectCollection("nckd_tztbry");// 通知人员
            DynamicObjectCollection userColl = dynamicObjectNew.getDynamicObjectCollection("nckd_tztbry");
            for (DynamicObject user : nckd_tztbry) {
                DynamicObject userObject = user.getDynamicObject("fbasedataId");
                DynamicObject newUser = new DynamicObject(userColl.getDynamicObjectType());
                newUser.set("fbasedataId", userObject);
                userColl.add(newUser);
            }
            dynamicObjectNew.set("nckd_tztbry", userColl);// 通知人员
            dynamicObjectNew.set("nckd_sfscrw", sjcjmbDynamicObject.get("nckd_sfscrw"));// 是否生成下级单位填报任务
        }

        Object[] result = SaveServiceHelper.save(new DynamicObject[]{sjcjrwObject});
        DynamicObject dynamicObject = (DynamicObject) result[0];
        Long sjcjTaskId = dynamicObject.getLong("id");

        // 获取附件面板的附件数据
        List<Map<String, Object>> attachmentDatas = AttachmentServiceHelper.getAttachments("nckd_sjcjmb", mbId, "attachmentpanel");
        if (attachmentDatas.size() > 0) {
            AttachFileUtils.copyFileFromAToB("nckd_sjcjmb", mbId, "attachmentpanel", "nckd_sjcjrw", sjcjTaskId, "attachmentpanel");
        }

        // 获取任务配置分录下发采集任务
        DynamicObject nowTaskObject = BusinessDataServiceHelper.loadSingle(sjcjTaskId, "nckd_sjcjrw");
        DynamicObjectCollection dynamicObjectCollection = nowTaskObject.getDynamicObjectCollection("nckd_sjcjrw_entry");
        for (DynamicObject dynamicObjectEntry: dynamicObjectCollection) {
            String nckd_sfscrw = dynamicObjectEntry.getString("nckd_sfscrw");// 是否生成下级单位填报任务1是0否
            DynamicObjectCollection nckd_tztbry = dynamicObjectEntry.getDynamicObjectCollection("nckd_tztbry");// 通知人员
            List<Long> receivers = nckd_tztbry.stream().map(tztbryObject -> tztbryObject.getLong("fbasedataid.id")).collect(Collectors.toList());
            if ("1".equals(nckd_sfscrw)) { // 需要生成任务
                PushSjcjDataUtils.savePushBillData(nowTaskObject, dynamicObjectEntry);
            }
            PushSjcjDataUtils.savePushBillMsg(nowTaskObject, receivers);
        }
    }



}
