package nckd.jxccl.opmc.pm.plugin.form.print;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.cache.AppCache;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.datamodel.events.PackageDataEvent;
import kd.bos.entity.report.ReportColumn;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.operate.printop.PrintPreview;
import kd.bos.form.operate.printop.SelectTplPrint;
import kd.bos.list.IListView;
import kd.bos.metadata.dao.MetaCategory;
import kd.bos.metadata.dao.MetadataDao;
import kd.bos.metadata.form.FormMetadata;
import kd.bos.mvc.report.ReportView;
import kd.bos.orm.query.QFilter;
import kd.bos.print.api.utils.ConfigConstUtil;
import kd.bos.print.business.utils.OldPrintTemplateUtil;
import kd.bos.report.ReportList;
import kd.bos.report.plugin.AbstractReportFormPlugin;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.template.orgctrl.service.PrintTemplateServiceFactory;
import kd.bos.template.orgctrl.utils.ParamUtils;
import kd.hr.hbp.common.cache.HRAppCache;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.DateUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* 人员考评套打列表
* 实体标识：perfbatchprintlist
* @author W.Y.C
* @date 2025/12/7 21:20
* @version 1.0
*/
public class PerfBatchPrintListPlugin extends AbstractReportFormPlugin implements Plugin {

    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        // 1. 获取表单显示参数对象
        FormShowParameter showParameter = (FormShowParameter) e.getSource();
        // 2. 设置页面标题
        showParameter.setCaption("套打列表");
        super.preOpenForm(e);
    }
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        Toolbar toolbar = this.getView().getControl(FormConstant.TOOLBARAP);
        toolbar.addItemClickListener(this);
    }

    @Override
    public void beforeQuery(ReportQueryParam queryParam) {
        ReportList reportList = this.getControl("reportlistap");
        reportList.setSelectedAll(true);
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        String operationKey = evt.getOperationKey();
        if("nckd_baritemap".equalsIgnoreCase(itemKey)){
            ReportList reportList = this.getView().getControl(FormConstant.REPORTLISTAP);
            int[] selectedRowIndexes = reportList.getEntryState().getSelectedRows();
            List<Long> personIds =  new ArrayList<>();
            if(selectedRowIndexes != null && selectedRowIndexes.length > 0) {
                for (int selectedRowIndex : selectedRowIndexes) {
                    DynamicObject rowData = reportList.getReportModel().getRowData(selectedRowIndex);
                    personIds.add(rowData.getDynamicObject(FormConstant.NCKD_PERSON).getLong(FormConstant.ID_KEY));
                }
            }else{
                int rowCount = reportList.getReportModel().getRowCount();
                DynamicObjectCollection rowDataColl = reportList.getReportModel().getRowData(1, rowCount, false);
                for (DynamicObject dynamicObject : rowDataColl) {
                    long personId = dynamicObject.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY));
                    personIds.add(personId);
                }
            }
            FormShowParameter showParameter = new FormShowParameter();
            showParameter.setFormId("nckd_batchmoddocstamppopu");
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            showParameter.setCloseCallBack(new CloseCallBack(this, "nckd_batchmoddocstamppopu"));
            showParameter.setCaption("批量修改文件印发及盖章时间");
            showParameter.setCustomParam( "personIds", personIds);
            this.getView().showForm(showParameter);
        }
        if("nckd_employeeprint".equalsIgnoreCase(itemKey)){
            HRAppCache.get("nckd_pm").remove( "printYear");
            ReportList reportList = this.getView().getControl(FormConstant.REPORTLISTAP);
            int[] selectedRowIndexes = reportList.getEntryState().getSelectedRows();
            List<Long> personIds =  new ArrayList<>();
            if(selectedRowIndexes == null ||  selectedRowIndexes.length == 0){
                this.getView().showTipNotification("请选择要打印的员工！");
                return;
            }
            FormShowParameter showParameter = new FormShowParameter();
            showParameter.setFormId("nckd_selectdateprint");
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            showParameter.setCloseCallBack(new CloseCallBack(this, "nckd_selectdateprint"));
            showParameter.setCaption("选择打印年份");
            this.getView().showForm(showParameter);
        }
    }


    private Map<String, String> getTemplates(String formId) {
        String id = MetadataDao.getIdByNumber(formId, MetaCategory.Form);// 368
        FormMetadata fm = (FormMetadata)MetadataDao.readMeta(id, MetaCategory.Form);// 369
        String oriFormId = MetadataDao.getNumberById(fm.getEntityId());// 370
        Map<String, String> templateMap = new LinkedHashMap(16);// 371
        DynamicObject[] dynamicObjects = BusinessDataServiceHelper.load("bos_manageprinttpl", "number, name, enable,type,printtplid", ConfigConstUtil.isNewTenantOfVersion(7) ? new QFilter[]{new QFilter("billformid", "=", oriFormId), new QFilter("type", "!=", "A")} : new QFilter[]{new QFilter("billformid", "=", oriFormId)});// 372 373

        for(DynamicObject obj : dynamicObjects) {// 375
            DynamicObject printtpObj = obj.getDynamicObject("printtplid");// 376
            Object tplId = obj.get("printtplid_id");// 377
            String enable = obj.getString("enable");// 378
            if (!"0".equals(enable)) {// 379
                if (printtpObj != null && "B".equals(printtpObj.get("type"))) {// 383
                    templateMap.put(tplId.toString(), printtpObj.getLocaleString("name").getLocaleValue());// 391
                } else {
                    QFilter qFilter = new QFilter("id", "=", tplId);// 384
                    DynamicObject formMeta = OldPrintTemplateUtil.loadSingleFromCache("id,number,bizappid,basedatafield,modifierid", new QFilter[]{qFilter});// 385
                    if (formMeta != null) {// 386
                        templateMap.put(tplId.toString(), formMeta.getLocaleString("name").getLocaleValue());// 389
                    }
                }
            }
        }

        return templateMap;// 394
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        String actionId = closedCallBackEvent.getActionId();
        if("nckd_batchmoddocstamppopu".equalsIgnoreCase(actionId)){
            Object returnData = closedCallBackEvent.getReturnData();
            if(returnData != null){
                /*Map<String, Date> returnDate = ConvertUtil.toMap(returnData);
                this.getPageCache().put("fileIssueTime", JSON.toJSONString(returnDate));*/
                this.getView().showSuccessNotification( "文件印发及盖章时间修改成功");
                this.getView().invokeOperation(FormConstant.REFRESH_OP);
            }
        }else if("nckd_selectdateprint".equalsIgnoreCase(actionId)){
            Object returnData = closedCallBackEvent.getReturnData();
            if(returnData != null) {
                HRAppCache.get("nckd_pm").remove( "employeePrintIdMap");
                Date date = ConvertUtil.toDate(returnData);
                HRAppCache.get("nckd_pm").put( "printYear", date);
                ReportList reportList = this.getView().getControl(FormConstant.REPORTLISTAP);
                int[] selectedRowIndexes = reportList.getEntryState().getSelectedRows();
                Map<Integer,Long> personIdMap = new HashMap<>();
                for (int selectedRowIndex : selectedRowIndexes) {
                    DynamicObject rowData = reportList.getReportModel().getRowData(selectedRowIndex);
                    personIdMap.put( rowData.getInt("fseq"), rowData.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY)));
                }
                HRAppCache.get("nckd_pm").put( "employeePrintIdMap", personIdMap);
                this.getView().invokeOperation("employeeprint");

            }
        }
    }


   @Override
    public void packageData(PackageDataEvent e) {
        String fileIssueTime = this.getPageCache().get("fileIssueTime");
        if(StringUtils.isNotEmpty(fileIssueTime)){
            JSONObject jsonObject = JSON.parseObject(fileIssueTime);
            String colKey = ((ReportColumn)e.getSource()).getFieldKey();
            if ("nckd_fileissuetime".equalsIgnoreCase(colKey) && jsonObject.containsKey("nckd_fileissuetime")) {
                e.setFormatValue(DateUtil.format(jsonObject.getDate("nckd_fileissuetime"),DateUtil.NORM_DATE_PATTERN));
            } else if ("nckd_stamptime".equalsIgnoreCase(colKey) && jsonObject.containsKey("nckd_stamptime")) {
                e.setFormatValue(DateUtil.format(jsonObject.getDate("nckd_stamptime"),DateUtil.NORM_DATE_PATTERN));
            }

        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        AbstractOperate operate = (AbstractOperate) args.getSource();
        HRAppCache.get("nckd_pm").remove( "selectPrintSeq");
        HRAppCache.get("nckd_pm").remove( "selectPrintPersonIdMap");
        String operateKey = operate.getOperateKey();
        if ("selecttplprint".equals(operateKey)) {
            ReportList reportList = this.getView().getControl(FormConstant.REPORTLISTAP);
            int[] selectedRowIndexes = reportList.getEntryState().getSelectedRows();
            Map<Integer,Long> personIdMap = new HashMap<>();
            List<Integer> seqList = new  ArrayList<>();
            if(selectedRowIndexes != null && selectedRowIndexes.length > 0) {
                for (int selectedRowIndex : selectedRowIndexes) {
                    DynamicObject rowData = reportList.getReportModel().getRowData(selectedRowIndex);
                    seqList.add(rowData.getInt("fseq"));
                    personIdMap.put( rowData.getInt("fseq"), rowData.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY)));
                }
            }else{
                int rowCount = reportList.getReportModel().getRowCount();
                DynamicObjectCollection rowDataColl = reportList.getReportModel().getRowData(1, rowCount, false);
                for (DynamicObject dynamicObject : rowDataColl) {
                    long personId = dynamicObject.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY));
                    seqList.add(dynamicObject.getInt("fseq"));
                    personIdMap.put(dynamicObject.getInt("fseq"), personId);
                }
            }
            HRAppCache.get("nckd_pm").put( "selectPrintSeq", seqList);
            HRAppCache.get("nckd_pm").put( "selectPrintPersonIdMap", personIdMap);
        }else if( "employeeprint".equals(operateKey)){

        }
    }
}