package nckd.jxccl.swc.init.plugin.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.BizDataEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.control.Label;
import kd.bos.form.mcontrol.mobtable.MobTable;
import kd.bos.form.mcontrol.mobtable.events.IMobTablePackageDataHandlerListener;
import kd.bos.form.mcontrol.mobtable.events.MobTablePackageDataHandlerEvent;
import kd.bos.form.plugin.AbstractMobFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.swc.constants.SwcConstant;
import nckd.jxccl.base.swc.helper.SWCHelper;


import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 动态表单插件(移动端)
 * 薪酬项目-实发  JT_331 薪酬项目-应发  JT_283 薪酬项目-扣款小计  JT_408
 * @author  turborao
 * @date 2025/11/27
 */
public class EmpSalaryQueryMobFormPlugin extends AbstractMobFormPlugin implements Plugin {

    private static final String KEY_LAB_EMP_NAME = "nckd_employee";
    private static final String KEY_LAB_EMP_DESCRIPTION = "nckd_desc";
    private static final String KEY_LAB_REALAMT = "nckd_realamt";
    private static final String KEY_LAB_GROSSAMT = "nckd_grossamt";
    private static final String KEY_LAB_SUBAMT = "nckd_subamt";
    private static String KEY_CTL_STARTDATE = "startmonth";
    private static String KEY_CTL_ENDDATE = "endmonth";
    private static Long KEY_EMPID = 0L;
    private static Date KEY_STARTDATE = new Date();
    private static Date KEY_ENDDATE = new Date();
    private static String KEY_TYPE = "10";


    @Override
    public void initialize() {
        super.initialize();
        //if(!this.getModel().isDataLoaded()){

        this.registerDataGridListener();
        //}
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        //this.registerDataGridListener();

    }

    /**
     * 通过事件监听，注册数据表格监听事件
     */
    private void registerDataGridListener() {
        MobTable mobTable = getControl("nckd_mobtable");
        mobTable.addMobTablePackageDataHandlerListener(new IMobTablePackageDataHandlerListener() {
            @Override
            public void createMobTablePackageDataHandler(MobTablePackageDataHandlerEvent mobTablePackageDataHandlerEvent) {
                mobTablePackageDataHandlerEvent.setMobTablePackageDataHandler(new EmpSalaryQueryMobDataHandler());//添加自定义的Handle
            }
        });

    }

    @Override
    public void createNewData(BizDataEventArgs e) {
        super.createNewData(e);
        // 设置最大日期为上个月
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date lastMonthDate = calendar.getTime();
        KEY_STARTDATE = lastMonthDate;

    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        this.getModel().setValue(KEY_CTL_STARTDATE, KEY_STARTDATE);

        this.getModel().setValue(KEY_CTL_ENDDATE, KEY_ENDDATE);

        Long userId = UserServiceHelper.getCurrentUserId();
        this.getModel().setValue("nckd_user", userId);

        DynamicObject personUserDyn = SWCHelper.queryOne(FormConstant.HRPI_PERSONUSERREL, "employee.id","user",userId);

        if(personUserDyn == null){
            /**
             * 没有员工信息时，返回常量，用于测试
             */
            KEY_EMPID = 2313784485549715456L;
           // this.getView().showMessage("未找到员工！");
           // return;
        }else {
            KEY_EMPID = personUserDyn.getLong("employee.id");
        }

        showData();
    }

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

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String fieldKey = e.getProperty().getName();
        if (fieldKey.equals(KEY_CTL_STARTDATE) || fieldKey.equals(KEY_CTL_ENDDATE)){
            // TODO 在此添加业务逻辑
            KEY_STARTDATE = (Date)this.getModel().getValue(KEY_CTL_STARTDATE);
            KEY_ENDDATE = (Date)this.getModel().getValue(KEY_CTL_ENDDATE);
            showData();
            //this.registerDataGridListener();
            this.getView().updateView("nckd_mobtable");
        }
        if (fieldKey.equals("nckd_type")){
            // TODO 在此添加业务逻辑

            KEY_TYPE = (String)this.getModel().getValue("nckd_type");
            showData();
            //this.registerDataGridListener();
            this.getView().updateView("nckd_mobtable");

        }
    }

    /**
     * 显示薪酬数据
     * caltask.paydate       预计支付日期  发放口径
     * caltask.payrolldate   薪资所属年月  统计口径
     */
    public void showData() {
        // 获取单据头日期范围，开始时间、结束时间
        Date startdate = KEY_STARTDATE;
        Date enddate = KEY_ENDDATE;
        String type = KEY_TYPE;

        if(KEY_EMPID == 0L) {
            this.getView().showMessage("未找到员工！");
            return;
        }
        String selectFields1 = "id,company.name,adminorg.name,employee.id,employee.name";
        QFilter filter1 = new QFilter("isprimary", QCP.equals, "1");
        QFilter filter2 = new QFilter("iscurrentdata", QCP.equals, "1");
        QFilter filter3 = new QFilter("employee.id", QFilter.equals, KEY_EMPID);
        DynamicObject employeeDyn = QueryServiceHelper.queryOne(FormConstant.HRPI_EMPPOSORGREL,selectFields1, new QFilter[]{filter1, filter2, filter3});

        if(employeeDyn == null){
            this.getView().showMessage("未找到员工！");
            return;
        }

        Map<Long, DynamicObject>  calPersonIdMap = SWCHelper.queryCalPersonList(KEY_EMPID);
        if(calPersonIdMap == null && calPersonIdMap.size() <= 0) {
            this.getView().showMessage("未找到员工！");
            return;
        }

        //将Map转换为List
        List<Long> calPersonIds = calPersonIdMap.keySet().stream().collect(Collectors.toList());

        // 获取核算列表信息
        QFilter filter = new QFilter("calpersonid", QCP.in, calPersonIds);
        if(type.equals("10")){
            filter.and("caltask.paydate", QCP.large_equals, startdate);
            filter.and("caltask.paydate", QCP.less_equals, enddate);
        }else{
            filter.and("caltask.payrolldate", QCP.large_equals, startdate);
            filter.and("caltask.payrolldate", QCP.less_equals, enddate);
        }

        DynamicObjectCollection calTableDyns = SWCHelper.querySalaryList(calPersonIds, startdate, enddate, type) ;

        Label label = this.getView().getControl(KEY_LAB_EMP_NAME);
        label.setText(employeeDyn.getString("employee.name"));

        Label labelDesc = this.getView().getControl(KEY_LAB_EMP_DESCRIPTION);
        String companyName = employeeDyn.getString("company.name");
        String adminorgName = employeeDyn.getString("adminorg.name");
        String desc = "";
        if(companyName != null){
            desc = "公司：" + companyName;
        }
        if(adminorgName != null){
            desc = desc + " 部门：" + adminorgName;
        }
        labelDesc.setText( desc);

        Map<String, BigDecimal> calItemAmtMap = getCalItemAmt(calTableDyns);
        Map<String, String> itemNameMap = getItemName(calTableDyns);

        if(calItemAmtMap != null && calItemAmtMap.size() > 0 && itemNameMap != null && calItemAmtMap.size() > 0){
            DecimalFormat df = new DecimalFormat("#,##0.00");
            Label label1 = this.getView().getControl(KEY_LAB_REALAMT);
            if(calItemAmtMap.get(FormConstant.SALARYITEM_REAL) == null){
                label1.setText("0.00");
            }else {
                label1.setText(df.format(calItemAmtMap.get(FormConstant.SALARYITEM_REAL)));    //实发合计
            }

            Label label2 = this.getView().getControl(KEY_LAB_GROSSAMT);
            if(calItemAmtMap.get(FormConstant.SALARYITEM_GROSS) == null){
                label2.setText("0.00");
            }else {
                label2.setText(df.format(calItemAmtMap.get(FormConstant.SALARYITEM_GROSS)));
            }
            Label label3 = this.getView().getControl(KEY_LAB_SUBAMT);
            if(calItemAmtMap.get(FormConstant.SALARYITEM_SUB) == null){
                label3.setText("0.00");
            }else {
                label3.setText(df.format(calItemAmtMap.get(FormConstant.SALARYITEM_SUB)));
            }

            MobTable mobTable = getControl("nckd_mobtable");
            mobTable.setCustomParam("calItemAmt", calItemAmtMap);
            mobTable.setCustomParam("itemName", itemNameMap);

        }else{
            Label label1 = this.getView().getControl(KEY_LAB_REALAMT);
            label1.setText("0.00");
            Label label2 = this.getView().getControl(KEY_LAB_GROSSAMT);
            label2.setText("0.00");
            Label label3 = this.getView().getControl(KEY_LAB_SUBAMT);
            label3.setText("0.00");
        }

    }

    /**
     * 按 salaryitem.number 分组汇总金额
     * @param calTableDyns
     * @return
     */
    public Map<String, BigDecimal> getCalItemAmt(DynamicObjectCollection calTableDyns) {
        // 按 salaryitem.number 分组汇总金额
        Map<String, BigDecimal> groupedAmounts = new LinkedHashMap<>();

        for (DynamicObject item : calTableDyns) {
            String salaryItemNumber = item.getString("hsas_caltableentry.salaryitem.number");
            BigDecimal amount = item.getBigDecimal("hsas_caltableentry.calamountvalue");
            if (amount == null) {
                amount = BigDecimal.ZERO;
            }else{
                amount = amount.setScale(2, BigDecimal.ROUND_HALF_UP);
            }

            if (salaryItemNumber != null) {
                groupedAmounts.put(salaryItemNumber, groupedAmounts.getOrDefault(salaryItemNumber, BigDecimal.ZERO) .add(amount != null ? amount : BigDecimal.ZERO));
            }
        }

        return groupedAmounts;
    }
    /**
     * 按 salaryitem.number 获取名称
     * @param calTableDyns
     * @return
     */
    public Map<String, String> getItemName(DynamicObjectCollection calTableDyns) {
        Map<String, String> itemNameMap = new LinkedHashMap <>();
        for (DynamicObject item : calTableDyns) {
            String salaryItemNumber = item.getString("hsas_caltableentry.salaryitem.number");
            String salaryItemName = item.getString("hsas_caltableentry.salaryitem.name");

            if (salaryItemNumber != null) {
                itemNameMap.put(salaryItemNumber, salaryItemName);
            }
        }

        return itemNameMap;
    }

}

