package nckd.jxccl.hr.gzbb;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.ConfirmTypes;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;

import java.io.IOException;
import java.net.URLDecoder;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.login.utils.DateUtils;
import kd.bos.message.api.MessageChannels;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.workflow.MessageCenterServiceHelper;
import kd.bos.web.actions.utils.FilePathUtil;
import kd.bos.workflow.engine.msg.info.MessageInfo;

/**
 * 央国企人事云》国资报表ext》单据》数据采集
 * 表单插件
 * nckd_sjcjrw
 * duanyuqi
 */
public class SjcjCheckFormPlugin extends AbstractFormPlugin implements BeforeF7SelectListener {
    private static final Log logger = LogFactory.getLog(SjcjCheckFormPlugin.class);

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
    }

    @Override
    public void afterCopyData(EventObject e) {
        this.getModel().setValue("nckd_sjzt", "1");// 暂存
        super.afterCopyData(e);
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        // 获取父页面的数据模型
        IDataModel parentModel = this.getView().getParentView().getModel();
        // 获取父页面传递过来的数据参数
        Map<String,Object> customParams = this.getView().getFormShowParameter().getCustomParams();
        // 判断是否是从数据填报任务列表过来的
        if (customParams.get("sjtbrwEntry") != null) {
            String sjtbrwEntry = customParams.get("sjtbrwEntry").toString();
            if ("nckd_sjtbrw".equals(sjtbrwEntry)) {// 从数据填报任务列表过来的数据
                Object sjtbrwId = customParams.get("sjtbrwId");
                this.initDataModelBySjtbrw(sjtbrwId);
            }
        }
        super.afterCreateNewData(e);
    }

    /**从数据填报任务列表过来的数据需要初始化字段信息*/
    public void initDataModelBySjtbrw(Object sjtbrwId) {
        // 获取到数据填报任务单据
        DynamicObject sjtbObject = BusinessDataServiceHelper.loadSingle(sjtbrwId, "nckd_sjtbrw");
        String nckd_rwmc = sjtbObject.getString("nckd_rwmc");// 任务名称
        Date nckd_tbsjny = sjtbObject.getDate("nckd_tbsjny");// 所属年月
        String nckd_ydcbm = sjtbObject.getString("nckd_ydcbm");// 源单长编码
        String nckd_ydbh = sjtbObject.getString("billno");// 源单编号
        String nckd_ydst = "nckd_sjtbrw";// 源单实体
        Date nckd_tbjzrq = sjtbObject.getDate("nckd_tbjzrq");// 填报截止时间
        String nckd_ydcbm_new = nckd_ydcbm + nckd_ydbh + "!";

        this.getModel().setValue("nckd_billname", nckd_rwmc);// 单据名称
        this.getModel().setValue("nckd_ssny", nckd_tbsjny);// 所属年月
        this.getModel().setValue("nckd_tbjzsj", nckd_tbjzrq);// 填报截止时间
        this.getModel().setValue("nckd_sfjtxf", "0");// 是否集团下发
        this.getModel().setValue("nckd_ydbm", nckd_ydbh);// 源单编码
        this.getModel().setValue("nckd_ydpk", sjtbrwId);// 源单ID
        this.getModel().setValue("nckd_ydcbm", nckd_ydcbm_new);// 源单长编码
        this.getModel().setValue("nckd_ydst", nckd_ydst);
        this.getModel().setValue("nckd_sjzt", "1");// 数据状态
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {

    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        FormOperate formOperate = (FormOperate) args.getSource();
        if ("save".equals(formOperate.getOperateKey())) { // 保存按钮
            Map<String, String> resultMap = this.checkDataEntity();
            String isSuccess = resultMap.get("isSuccess");
            if ("error".equals(isSuccess)) {
                this.getView().showConfirm("保存失败", resultMap.get("message"), MessageBoxOptions.OK, ConfirmTypes.Save,null,new HashMap<>(),null);
                args.setCancel(true);
                return;
            }
        }
        super.beforeDoOperation(args);
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        OperationResult operationResult = args.getOperationResult();
        // 够获取页面配置的校验规则的执行结果
        if (operationResult != null && !operationResult.isSuccess()) {
            return;
        }
        FormOperate formOperate = (FormOperate) args.getSource();
        if ("nckd_fbbtn".equals(formOperate.getOperateKey())) { // 发布按钮
            Map<String, String> resultMap = this.checkDataEntity();
            String isSuccess = resultMap.get("isSuccess");
            if ("error".equals(isSuccess)) {
                this.getView().showConfirm("保存失败", resultMap.get("message"), MessageBoxOptions.OK, ConfirmTypes.Save,null,new HashMap<>(),null);
                return;
            } else {
                this.getView().invokeOperation("save");
                this.getModel().setValue("billstatus", "C");// 已审核
                this.getModel().setValue("nckd_sjzt", "2");// 已下发
                Object[] result = SaveServiceHelper.save(new DynamicObject[]{this.getModel().getDataEntity()});
                DynamicObject dynamicObject = (DynamicObject) result[0];
                this.savePushToNextBill(dynamicObject);
                this.getView().showSuccessNotification("发布成功.");
                this.getView().updateView();
            }
        } else if ("nckd_zfbtn".equals(formOperate.getOperateKey())) { // 作废按钮
            Long pkValue = (Long) this.getModel().getDataEntity().getPkValue();
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(pkValue, "nckd_sjcjrw");
            // 作废数据填报单据
            PushSjcjDataUtils.deleteSjtbBillData(dynamicObject);
            // 作废数据采集单据
            PushSjcjDataUtils.deleteSjcjBillData(dynamicObject);
            //this.getModel().setValue("billstatus", "A");// 暂存
            dynamicObject.set("nckd_sjzt", "3");// 作废
            SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
            this.getView().showSuccessNotification("作废成功!");
            this.getView().updateView();
        }
        super.afterDoOperation(args);
    }

    /**检查任务配置单据体内容*/
    public Map<String, String> checkDataEntity() {
        Map<String, String> resultMap = new LinkedHashMap();
        resultMap.put("isSuccess", "success");
        resultMap.put("msg", "");
        DynamicObjectCollection nckdSjcjrwEntry =  this.getModel().getEntryEntity("nckd_sjcjrw_entry");
        Long[] orgIds = new Long[nckdSjcjrwEntry.size()];
        for (int i = 0; i < nckdSjcjrwEntry.size(); i++) {
            DynamicObject dynamicObject = nckdSjcjrwEntry.get(i);
            orgIds[i] = dynamicObject.getLong("nckd_tbxzzz.id");
        }
        if (orgIds.length > 0) {
            String msg = "";
            boolean isError = false;
            List<QFilter> qfilterHr = new ArrayList<QFilter>();
            qfilterHr.add(new QFilter("iscurrentversion", "=", "1"));// 是否当前版本
            qfilterHr.add(new QFilter("datastatus", "=", "1"));// 数据版本状态
            qfilterHr.add(new QFilter("id", "in", orgIds));
            QFilter[] filtersQueryHr = (QFilter[]) qfilterHr.toArray(new QFilter[qfilterHr.size()]);
            String selectHrFields = "id,number,name,nckd_sscj.id";
            DynamicObjectCollection hrObjectCollection = QueryServiceHelper.query("haos_adminorghr", selectHrFields, filtersQueryHr, "sortcode asc");
            for (DynamicObject dynamicObject : hrObjectCollection) {
                Object nckdSscjId = dynamicObject.get("nckd_sscj.id");
                if (nckdSscjId == null || "0".equals(String.valueOf(nckdSscjId))) {
                    msg = msg +"组织"+dynamicObject.getString("name")+" 未设置所属层级 \r\n";
                    isError = true;
                }
            }
            if (isError) {
                resultMap.put("isSuccess", "error");
                resultMap.put("message", msg);
            }
        }
        return resultMap;
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String fieldKey = e.getProperty().getName();
        if ("nckd_ssny".equals(fieldKey)) {
            // 获取所在月份的最后一天填入截止日期
            Date nckd_ssny = (Date) this.getModel().getValue("nckd_ssny");
            // 1. 将 Date 转换为 LocalDate
            LocalDate localDate = nckd_ssny.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());
            this.getModel().setValue("nckd_tbjzsj", resultDate);
        }
        super.propertyChanged(e);
    }

    /**下推生成数据填报任务*/
    public void savePushToNextBill(DynamicObject dynamicObject) {
        // 获取分录
        DynamicObjectCollection dynamicObjectCollection = dynamicObject.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(dynamicObject, dynamicObjectEntry);
            }
            PushSjcjDataUtils.savePushBillMsg(dynamicObject, receivers);
        }

    }



}
