package nckd.jxccl.opmc.pm.plugin.operate.salary;

import com.alibaba.fastjson.JSON;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.servicehelper.DispatchServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.opmc.pm.common.SalAdjTrackerConstant;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
* 调薪情况-确认推送调薪/不需要调薪
* 实体标识：nckd_saladjtracker
* @author W.Y.C
* @date 2025/11/26 9:34
* @version 1.0
*/
public class PushAdjustOpPlugin extends AbstractOperationServicePlugIn implements Plugin {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        e.getFieldKeys().addAll(this.billEntityType.getAllFields().keySet());
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e){
        e.addValidator(new AbstractValidator() {
            @Override
            public void validate() {
                String operateKey = this.getOperateKey();
                //pushadjust：确认推送调薪
                //nopushadjust：不需要调薪
                for (ExtendedDataEntity rowDataEntity : getDataEntities()) {
                    DynamicObject data = rowDataEntity.getDataEntity();
                    DynamicObject person = data.getDynamicObject(SalAdjTrackerConstant.NCKD_PERFMANAGER).getDynamicObject(FormConstant.NCKD_PERSON);
                    String wageStatus = data.getString(SalAdjTrackerConstant.NCKD_WAGESTATUS);
                    if(SalAdjTrackerConstant.PUSHADJUST_OP.equalsIgnoreCase(operateKey)){
                        if(!"1".equalsIgnoreCase(wageStatus)){
                            this.addFatalErrorMessage(rowDataEntity,"只有【待处理】状态的调薪才可以推送");
                        }
                    }else if(SalAdjTrackerConstant.NOPUSHADJUST_OP.equalsIgnoreCase(operateKey)){
                        if(!"1".equalsIgnoreCase(wageStatus)){
                            this.addErrorMessage(rowDataEntity,StrFormatter.format("【{}】的调薪处理状态已是【{}】状态，本次操作忽略此条处理；", person.getString(FormConstant.NAME_KEY),
                                    "2".equalsIgnoreCase(wageStatus) ? "已处理":"已忽略"));
                        }
                    }
                }
            }
        });
    }

    List<DynamicObject> pushAdjusts = new ArrayList<>();
    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        Long salaryItemId = EntityHelper.getIdByNumber(FormConstant.HSBS_STANDARDITEM, FormConstant.POS_STANDARD_ITEM_NUMBER);
        Long billTypeId = EntityHelper.getIdByNumber(FormConstant.BOS_BILLTYPE, FormConstant.HCDM_APPLYBILL_BT_ADJ);
        Long countryId = EntityHelper.getIdByNumber(FormConstant.BD_COUNTRY, "001");
        Long salaryAdjuStrSnId = EntityHelper.getIdByNumber(FormConstant.HSBS_SALARYADJUSTRSN, "kaohe");
        Long currencyId = EntityHelper.getIdByNumber(FormConstant.BD_CURRENCY, "CNY");
        Long adjApproveScmId = EntityHelper.getLatestIdByNumber(FormConstant.HCDM_ADJAPPROVESCM, "dingtiaoxin");
        Long exRateTableId = EntityHelper.getIdByNumber(FormConstant.BD_EXRATETABLE, "ERT-01");
        Long calFrequencyId = EntityHelper.getIdByNumber(FormConstant.HSBS_CALFREQUENCY, "000_m_001");
        String operateKey = e.getOperationKey();

        List<DynamicObject> updateAdjusts = new ArrayList<>();

        for (DynamicObject dataEntity : e.getDataEntities()) {
            if(SalAdjTrackerConstant.PUSHADJUST_OP.equalsIgnoreCase(operateKey)){
                //推送调薪
                pushAdjusts.add(dataEntity);
            }else if(SalAdjTrackerConstant.NOPUSHADJUST_OP.equalsIgnoreCase(operateKey)){
                dataEntity.set(SalAdjTrackerConstant.NCKD_WAGESTATUS, "3");
                updateAdjusts.add(dataEntity);
            }
        }
        if(!updateAdjusts.isEmpty()){
            SaveServiceHelper.update(updateAdjusts.toArray(new DynamicObject[0]));
        }
        //开始推送定调薪
        if(!pushAdjusts.isEmpty()) {
            Map<String, Object> papams = new HashMap<>();
            List<Map<String, Object>> applyBillData = new ArrayList<>();
            for (DynamicObject pushAdjust : pushAdjusts) {
                Map<String, Object> applyBill = new HashMap<>();
                /**
                 * 必填字段
                 * "billname", "billtype", "org", "billcountry", "salaryadjrsn", "salaryadjscm", "billcurrency", "effectivedate", "exchangeratedate", "exctable"
                 */
                DynamicObject person = pushAdjust.getDynamicObject(SalAdjTrackerConstant.NCKD_PERFMANAGER).getDynamicObject(FormConstant.NCKD_PERSON);
                applyBill.put("billname", StrFormatter.format("【{}】的岗位工资动态调整（人员考评）",person.getString(FormConstant.NAME_KEY)));

                DynamicObject adjFileInfo = pushAdjust.getDynamicObject(SalAdjTrackerConstant.NCKD_ADJFILEINFO);
                if(adjFileInfo != null) {
                    Long orgId = adjFileInfo.getLong(String.join(".", FormConstant.ORG_KEY, FormConstant.ID_KEY)) > 0 ? adjFileInfo.getLong(String.join(".", FormConstant.ORG_KEY, FormConstant.ID_KEY)) : RequestContext.get().getOrgId();

                    String uniquecode = UUID.randomUUID().toString().replace("-", "");
                    applyBill.put("_uniquecode", uniquecode);
                    applyBill.put("org", orgId);
                    //定调薪明细字段显示方案   调薪明细字段
                    applyBill.put("billtype", billTypeId);
                    //国家
                    applyBill.put("billcountry", countryId);
                    //定调薪类型
                    applyBill.put("salaryadjrsn", salaryAdjuStrSnId);
                    //默认币种
                    applyBill.put("billcurrency", currencyId);
                    //定调薪方案
                    applyBill.put("salaryadjscm", adjApproveScmId);
                    //汇率日期
                    applyBill.put("exchangeratedate", new Date());
                    //汇率表
                    applyBill.put("exctable", exRateTableId);
                    //默认生效日期
                    applyBill.put("effectivedate", new Date());
                    //草稿状态
                    applyBill.put("isdraft", "1");
                    //审核状态
                    applyBill.put("auditstatus", "A");
                    //申请单数据来源   //1:手工新增  2:接口写入
                    applyBill.put("datasource", "2");
                    applyBill.put("description", pushAdjust.getString(SalAdjTrackerConstant.NCKD_WAGEEXPLAIN));
                    List<Map<String, Object>> applyBillEntryData = new ArrayList<>();
                    Map<String, Object> applyBillEntry = new HashMap<>();
                    Long employeeId = pushAdjust.getDynamicObject(SalAdjTrackerConstant.NCKD_PERFMANAGER).getDynamicObject(FormConstant.NCKD_PERSON).getLong(FormConstant.ID_KEY);
                    Long positionId = pushAdjust.getDynamicObject(SalAdjTrackerConstant.NCKD_POSITION).getLong(FormConstant.ID_KEY);
                    applyBillEntry.put("adjfile", adjFileInfo.getLong(FormConstant.ID_KEY));
                    applyBillEntry.put("employee", employeeId);
                    applyBillEntry.put("standarditem", salaryItemId);    //定调薪项目   岗位工资标准
                    applyBillEntry.put("frequency", calFrequencyId);       //频度  月
                    applyBillEntry.put("amount", pushAdjust.getBigDecimal(SalAdjTrackerConstant.NCKD_MONEY));
//            applyBillEntry.put("nckd_postgrade", salaryfile.getLong("position.nckd_postgrade.id"));  //岗级
                    applyBillEntry.put("position", positionId);

                    applyBillEntry.put("salarygrade", pushAdjust.getLong(String.join(".", SalAdjTrackerConstant.NCKD_SALARYGRADE, FormConstant.ID_KEY)));
                    applyBillEntry.put("salaryrank", pushAdjust.getLong(String.join(".", SalAdjTrackerConstant.NCKD_SALARYRANK, FormConstant.ID_KEY)));
                    applyBillEntry.put("reason", pushAdjust.getString(SalAdjTrackerConstant.NCKD_WAGEEXPLAIN));
                    applyBillEntryData.add(applyBillEntry);
                    applyBill.put("applybillent", applyBillEntryData);
                    applyBillData.add(applyBill);
                }
            }
            if(!applyBillData.isEmpty()) {
                papams.put("data", applyBillData);
                papams.put("isUseMatchAmount", Boolean.TRUE);
                Map<String, Object> result = DispatchServiceHelper.invokeService("nckd.jxccl.swc.hcdm.servicehelper", "hcdm", "ISwcService", "saveDraftApplyBill", papams);
                if (!ConvertUtil.toBoolean(result.get("success")) || result.get("data") == null || ConvertUtil.toList(result.get("data")).isEmpty()) {
                    throw new ValidationException("推送定调薪失败，原因：" + JSON.toJSONString(result));
                }
            }
        }
    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        if(this.getOperationResult() != null && this.getOperationResult().isSuccess()) {
            if(!pushAdjusts.isEmpty()) {
                for (DynamicObject pushAdjust : pushAdjusts) {
                    pushAdjust.set(SalAdjTrackerConstant.NCKD_WAGESTATUS, "2");
                }
                SaveServiceHelper.update(pushAdjusts.toArray(new DynamicObject[0]));
            }
        }


    }
}