package nckd.jxccl.hr.tsc.plugin.form;

import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.BizDataEventArgs;
import kd.bos.form.OpenStyle;
import kd.bos.form.ShowType;
import kd.bos.form.control.Label;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.swc.helper.SWCHelper;
import nckd.jxccl.base.tsc.helper.TSCHelper;

import java.util.*;

/**
 * 应聘申请表单插件 【nckd_applicationbill】
 * @author Tyx
 * 时间 2026/1/14 11:18
 */
public class ApplicationBillFormPlugin extends AbstractFormPlugin implements Plugin {

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners(new String[]{"nckd_fullname", "vectorap"});
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        // 携带简历字段
        dealResumeCvInfo();
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        // 处理员工相关信息
        getEmployeeInfo();
        // 携带源页面字段
        dealAdvertInfo();

    }

    /**
     * 获取员工相关信息
     * 1.所在部门/所在单位
     * 2.政治面貌--废弃 直接查询属性关联出来
     */
    public void getEmployeeInfo() {
        IDataModel model = this.getModel();
        DynamicObject dyn = model.getDataEntity();
        // 当前用户ID
        Long userId = UserServiceHelper.getCurrentUserId();
        DynamicObject personUserDyn = SWCHelper.queryOne(FormConstant.HRPI_PERSONUSERREL, "employee.id","user",userId);
        Long employeeId = 0L;
        if(personUserDyn == null){
            employeeId = 0L;
            return;
        }
        else {
            employeeId = personUserDyn.getLong("employee.id");
        }

        model.setValue("nckd_employee", employeeId);
        List<Long> employeeIds = new java.util.ArrayList<>();
        employeeIds.add(employeeId);
        DynamicObject[] empDyns = SWCHelper.queryEmpPosOrgRelDyns(employeeIds);

        if(empDyns != null && empDyns.length > 0){
            Long companyId = empDyns[0].getLong("company.id");
            model.setValue("nckd_company", companyId);
            Long adminorgId = empDyns[0].getLong("adminorg.id");
            model.setValue("nckd_adminorg", adminorgId);
        }
    }


    /**
     * 处理从我要应聘-最新职位跳转过来携带的参数
     */
    public void dealAdvertInfo() {
        IDataModel model = this.getModel();
        Map map = this.getView().getFormShowParameter().getCustomParams();
        map.keySet().forEach(key -> {
            if (key.equals("positionId")) {
                model.setValue("nckd_position", map.get(key));
            }
            else if(key.equals("advertId")) {
                model.setValue("nckd_advert", map.get(key));
            }
        });
    }

    public void dealResumeCvInfo() {
        IDataModel model = this.getModel();
        // 当前用户ID
        Long userId = UserServiceHelper.getCurrentUserId();
        TSCHelper tscHelper = new TSCHelper();
        //DynamicObject personUserDyn = SWCHelper.queryOne(FormConstant.HRPI_PERSONUSERREL, "employee.id","user",userId);
        Long employeeId = 0L;
//        if(personUserDyn == null){
//            employeeId = 0L;
//            return;
//        }
//        else {
//            employeeId = personUserDyn.getLong("employee.id");
//        }
        employeeId = model.getDataEntity().getLong("nckd_employee.id");
        DynamicObject[] empCVDyArr = tscHelper.getEmpCVDyByEmpId(employeeId);
        if (empCVDyArr.length == 0) {
            //this.getView().showTipNotification("empcv is null");
        } else {
            DynamicObject empCVDy = empCVDyArr[0];
            Date updateDate = empCVDy.getDate("modifytime");
            updateDate = updateDate == null ? empCVDy.getDate("createtime") : updateDate;
            String name = ResManager.loadKDString("{0}的简历", "EmpCVListPlugin_0", "tsc-tsirm-formplugin", new Object[]{empCVDy.getString("name")});
            Label fullName = (Label)this.getControl("nckd_fullname");
            fullName.setText(name);
            this.getModel().setValue("nckd_rsmupdatetime", updateDate);
            this.getView().getPageCache().put("cachekey_cvid", String.valueOf(empCVDy.getLong("id")));
            this.getView().updateView("nckd_rsmupdatetime");
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate formOperate = (FormOperate)args.getSource();
        String operateKey = formOperate.getOperateKey();
        String cvId = this.getView().getPageCache().get("cachekey_cvid");
        if ("donothing_viewresume".equals(operateKey)) {
            this.openCVDetailPage(Long.parseLong(cvId));
        }
    }

    /**
     * 打开简历详情页面
     * @param cvId
     */
    private void openCVDetailPage(long cvId) {
        BillShowParameter showParameter = new BillShowParameter();
        showParameter.setFormId("tsirm_employeecv");
        showParameter.setPkId(cvId);
        showParameter.setStatus(OperationStatus.VIEW);
        OpenStyle openStyle = showParameter.getOpenStyle();
        Optional.ofNullable(openStyle).ifPresent((style) -> {
            style.setShowType(ShowType.NonModal);
        });
        this.getView().showForm(showParameter);
    }

}