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

import kd.bos.base.BaseShowParameter;
import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;

import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.datamodel.events.BizDataEventArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.ShowType;
import kd.bos.form.events.*;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.BillList;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.swc.init.business.SynPendingSalaryAdjDataServiceImpl;
import java.util.*;


/**
 * 员工待定调薪清单
 * 人事那边做完调动后，判断调动后岗位的【薪酬标准方案】为“江铜集团岗位绩效工资制”的，更新定调薪人员名单列表
 * 单据包含入职单，调动单，自动更新员工待定调薪清单
 * @author turborao
 * @date 2025/11/19 11:35
 */
public class PendingSalaryAdjListPlugin extends AbstractListPlugin implements Plugin {

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

    }

    @Override
    public void billListHyperLinkClick(HyperLinkClickArgs args) {
        String fieldName = args.getHyperLinkClickEvent().getFieldName();
        if ("nckd_employeefield_empnumber".equals(fieldName)) {
            HyperLinkClickEvent linkClick = args.getHyperLinkClickEvent();
            BillList billList = (BillList)linkClick.getSource();
            ListSelectedRow selectedRow = billList.getCurrentSelectedRowInfo();
            if (selectedRow != null) {
                long id = Long.parseLong(String.valueOf(selectedRow.getPrimaryKeyValue()));
                DynamicObject dyn = QueryServiceHelper.queryOne(FormConstant.NCKD_PENDINGSALARYADJ,"id,nckd_employeefield.boid,nckd_employeefield.name", new QFilter[]{new QFilter("id", "=", id)});
                BaseShowParameter showParameter = new BaseShowParameter();
                showParameter.setFormId("hsbs_employee");
                showParameter.setPkId(dyn.get("nckd_employeefield.boid"));
                showParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                showParameter.setStatus(OperationStatus.VIEW);
                showParameter.setCaption("计薪人员 - "+dyn.getString("nckd_employeefield.name"));
                this.getView().showForm(showParameter);
                args.setCancel(true);
            }
        }
    }

    @Override
    public void createNewData(BizDataEventArgs e) {
        super.createNewData(e);

        //加载入职单与调动单的数据 进来时不用加载数据
        //getAdjustBillData();
    }


    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        //super.beforeDoOperation(args);

        FormOperate formOperate = (FormOperate)args.getSource();
        String key = formOperate.getOperateKey();
        switch (key) {
            case "syndata":
                //加载入职单与调动单的数据
                getAdjustBillData();
                break;

        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        FormOperate formOperate = (FormOperate)args.getSource();
        String key = formOperate.getOperateKey();
        switch (key) {
            case "apply_adj":
                OperationResult ore =  args.getOperationResult();
                if(ore.isSuccess()) {
                    Map<String, String> params = ore.getCustomData();
                    if (params != null && params.containsKey("applyID")) {
                        Long billid = Long.parseLong(params.get("applyID"));
                        BillShowParameter billShowParameter = new BillShowParameter();
                        billShowParameter.setFormId("hcdm_applybill");
                        billShowParameter.setPkId(billid);//单据内码
                        billShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                        billShowParameter.setStatus(OperationStatus.EDIT);
                        this.getView().showForm(billShowParameter);
                    }
                    this.getView().invokeOperation("refresh");
                }
                break;
            case "queryapplybill":
                ListSelectedRowCollection selectedRows = formOperate.getListSelectedData();
                Object[] pks = selectedRows.getPrimaryKeyValues();
                List<Object> pkList = Arrays.asList(pks);
                // 查询数据
                QFilter idQFilter = new QFilter("id", QCP.in, pkList);
                DynamicObject[] billDyns = BusinessDataServiceHelper.load(FormConstant.NCKD_PENDINGSALARYADJ, "nckd_applybillid", new QFilter[] { idQFilter });
                for(DynamicObject billDyn : billDyns){
                    Long billid = billDyn.getLong("nckd_applybillid");
                    if (billid > 0) {
                        BillShowParameter billShowParameter = new BillShowParameter();
                        billShowParameter.setFormId("hcdm_applybill");
                        billShowParameter.setPkId(billid);//单据内码
                        billShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                        billShowParameter.setStatus(OperationStatus.EDIT);
                        this.getView().showForm(billShowParameter);
                    }else{
                        this.getView().showTipNotification("没有定调薪申请单");
                    }
                    break;
                }
                break;
            case "flag_ignore":
                setBillStatus("F",key);
                break;
            case "cleanflag":
                setBillStatus("A",key);
                break;
        }
    }

    /**
     * 设置单据状态
     * @param billStatus
     * A	待处理
     * D	处理中
     * C	已处理
     * F	已忽略
     */
    public void setBillStatus(String billStatus,String operateKey) {
        StringBuffer errorInfo = new StringBuffer();
        ListSelectedRowCollection selectedRows = this.getSelectedRows();
        MainEntityType entityType= EntityMetadataCache.getDataEntityType(FormConstant.NCKD_PENDINGSALARYADJ);
        DynamicObject[] billDyns = BusinessDataServiceHelper.load(selectedRows.getPrimaryKeyValues(), entityType);
        for (DynamicObject billDyn : billDyns){
            String currbillstatus = billDyn.getString("billstatus");
            String billno = billDyn.getString("billno");
            if(operateKey.equals("flag_ignore") && !currbillstatus.equals("A")){
                errorInfo.append(billno + ",单据状态不是待处理，请重新选择单据！");
                continue;
            }
            if(operateKey.equals("cleanflag") && !currbillstatus.equals("F")){
                errorInfo.append(billno + ",单据状态不是已忽略，请重新选择单据！");
                continue;
            }
            billDyn.set("billstatus", billStatus);
        }

        if (errorInfo.length() > 0) {
            this.getView().showErrorNotification(errorInfo.toString());
        }else{
            Object[] update = SaveServiceHelper.save(billDyns);
            this.getView().showSuccessNotification(update.length + "条，操作成功", 3000);
        }
        this.getView().updateView();
        //this.getView().invokeOperation("refresh");

    }

    /**
     * 获取入职单与调动单的数据
     */
    public void getAdjustBillData() {
        SynPendingSalaryAdjDataServiceImpl service = new SynPendingSalaryAdjDataServiceImpl();
        String msg  = service.SynPendingSalaryAdjDataForPersonTransfer();
        this.getView().showTipNotification(msg,4000); // 成功类型
    }
}