package nckd.jimin.jyyy.hr.hspm.formplugin.web.reform.file.web.employee;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.property.PKFieldProp;
import kd.bos.form.FormConfig;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IMobileView;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.IListView;
import kd.bos.list.IMobileListView;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.metadata.dao.MetaCategory;
import kd.bos.metadata.dao.MetadataDao;
import kd.bos.metadata.form.FormMetadata;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.orm.util.CollectionUtils;
import kd.bos.report.IReportView;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.common.util.HRStringUtils;
import kd.hr.hspm.formplugin.print.ResumeListPrintPlugin;
import kd.hrmp.hrpi.business.domian.service.impl.PersonServiceImpl;
import kd.sdk.hr.hspm.common.utils.QFilterUtil;

import java.text.MessageFormat;
import java.util.*;

public class ResumePrintPlugin extends AbstractFormPlugin {
    private static final Log LOGGER = LogFactory.getLog(ResumeListPrintPlugin.class);
    private static final String KEY_SELECTTPLPRINT_EXT = "selecttplprintext";
    private static final HRBaseServiceHelper HSPM_ERMANFILE = new HRBaseServiceHelper("hspm_ermanfile");
    private static final int MAX_SELECT_COUNT = 1000;
    private static final long POST_FULLTIME = 1010L;
    private static final String KEY_EMPPOSREL_POSTID = "empposrel.postype.id";


    public ResumePrintPlugin() {
    }

    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        AbstractOperate operate = (AbstractOperate)args.getSource();
        String opKey = operate.getOperateKey();
        if (HRStringUtils.equals("selecttplprintext", opKey)) {
            this.showSelectPrintForm();
        }

    }

    private void showSelectPrintForm() {
        List<Object> pkids = this.getPKIds();
        if (pkids.size() > 1000) {
            this.getView().showMessage(MessageFormat.format(ResManager.loadKDString("打印失败，一次最多可选择的数据条数为：{0}。", "ResumeListPrintPlugin_4", "hr-hspm-formplugin", new Object[0]), 1000));
        } else {
            List<Long> ids = new ArrayList(pkids.size());
            Set<Long> filterEmployeeIds = new HashSet(pkids.size());
            DynamicObject[] dys = HSPM_ERMANFILE.query("employee.id,empposrel.postype,businessstatus", new QFilter[]{new QFilter("id", "in", pkids)});
            if (dys != null && dys.length > 0) {
                DynamicObject[] var5 = dys;
                int var6 = dys.length;

                for(int var7 = 0; var7 < var6; ++var7) {
                    DynamicObject dy = var5[var7];
                    long employeeId = dy.getLong("employee.id");
                    if (employeeId != 0L && "1".equals(dy.getString("businessstatus")) && 1010L == dy.getLong("empposrel.postype.id") && filterEmployeeIds.add(employeeId)) {
                        ids.add(dy.getLong("id"));
                    }
                }
            }

            if (CollectionUtils.isEmpty(ids)) {
                this.getView().showMessage(MessageFormat.format(ResManager.loadKDString("打印失败：没有符合条件的人员档案。请选择生效中的全职任职档案进行打印。", "ResumeListPrintPlugin_5", "hr-hspm-formplugin", new Object[0]), 1000));
            } else {
                String text = MessageFormat.format(ResManager.loadKDString("将打印生效中的全职任职档案（共选择：{0}，将打印{1}）。", "ResumeListPrintPlugin_6", "hr-hspm-formplugin", new Object[0]), pkids.size(), ids.size());
                String formId = "hspm_erfilelistreform";
                String id = MetadataDao.getIdByNumber(formId, MetaCategory.Form);
                FormMetadata fm = (FormMetadata)MetadataDao.readMeta(id, MetaCategory.Form);
                String oriFormId = MetadataDao.getNumberById(fm.getEntityId());
                formId = oriFormId;
                if (this.getView() instanceof IMobileView) {
                    FormConfig fc = this.getView().getFormShowParameter().getFormConfig();
                    formId = fc.getEntityTypeId();
                }

                FormShowParameter param = new FormShowParameter();
                param.getOpenStyle().setShowType(ShowType.Modal);
                param.setFormId("bos_selecttemplate");
                param.setCustomParam("formid", formId);
                param.setCustomParam("pkids", ids);
                param.setCustomParam("type", "printpreview");
                param.setCustomParam("showalltpl", Boolean.TRUE);
                param.setCustomParam("text", text);
                this.getView().showForm(param);
            }
        }
    }

    private List<Object> getPKIds() {
        List<Object> pkids = new ArrayList();
        //查询当前人员 生效中的全职任职的ermanfileId
        //pkids.add(2218386780892185612L);
        Long userId = UserServiceHelper.getCurrentUserId();
        Long personId = 999999L;
        Map<String, Object> map = PersonServiceImpl.getInstance().getPersonModelIdByUserId(userId);
        if(Boolean.valueOf(map.get("success").toString())) {
            personId = Long.valueOf(((Map) map.get("data")).get("person").toString());
        }

        QFilter filter = QFilterUtil.getCurrentQf();
        filter.and("filetype.number", QCP.equals, "1010_S");
        filter.and("person.id", QCP.equals, personId);
        DynamicObject[] ermanFileDyn = HSPM_ERMANFILE.query("id", new QFilter[]{filter}, "startdate desc", 1);
        if(ermanFileDyn.length > 0) {
            pkids.add(ermanFileDyn[0].get("id"));
        }
        return pkids;
    }
}
