package com.engine.organization.util.saveimport;

import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.engine.organization.entity.fieldset.param.FieldTransferParam;
import com.engine.organization.entity.jclimport.po.HrmFormFieldPO;
import com.engine.organization.entity.jclimport.po.JclImportHistoryDetailPO;
import com.engine.organization.entity.personnelcard.po.CusTreeFormPO;
import com.engine.organization.exception.OrganizationRunTimeException;
import com.engine.organization.mapper.jclimport.JclImportHistoryDetailMapper;
import com.engine.organization.mapper.personnelcard.PersonnelCardMapper;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.saveimport.hrmimport.HrmImportAdaptExcelE9;
import com.engine.organization.util.saveimport.hrmimport.HrmImportProcessE9;
import weaver.file.FileUploadToPath;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.definedfield.HrmFieldManager;
import weaver.join.hrm.in.HrmResourceVo;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author:dxfeng
 * @createTime: 2022/12/07
 * @version: 1.0
 */
public class ResourceImport {

    private static PersonnelCardMapper getPersonnelCardMapper() {
        return MapperProxyFactory.getProxy(PersonnelCardMapper.class);
    }

    /**
     * 导入模板可选择字段
     *
     * @param user           当前用户
     * @param excludedFields 排除的字段
     */
    public static Map<String, Object> getImportFields(User user, List<String> excludedFields) {

        try {
            List<HrmFormFieldPO> importFields = new ArrayList<>();
            List<CusTreeFormPO> cusTreeForms = getPersonnelCardMapper().getCusTreeForms(0);
            importFields.add(HrmFormFieldPO.builder().fieldName("subcompanyid1").labelName("分部").build());
            for (CusTreeFormPO cusTreeForm : cusTreeForms) {
                HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", cusTreeForm.getId());
                hfm.getCustomFields();
                while (hfm.next()) {
                    String fieldName = hfm.getFieldname();
                    String fieldLabel = SystemEnv.getHtmlLabelNames(hfm.getLable(), user.getLanguage());
                    importFields.add(HrmFormFieldPO.builder().fieldName(fieldName).labelName(fieldLabel).build());
                }
            }

            Map<String, Object> returnMaps = new HashMap<>();
            importFields.removeIf(item -> excludedFields.contains(item.getFieldName()));

            // 查询所有可以勾选的字段
            List<FieldTransferParam> fieldDatas = importFields.stream().map(item -> FieldTransferParam.builder().id(item.getFieldName()).name(item.getLabelName()).build()).collect(Collectors.toList());
            returnMaps.put("data", fieldDatas);


            // 设置必填字段
            List<String> selectedKeys = new ArrayList<>();
            selectedKeys.add("subcompanyid1");
            selectedKeys.add("departmentid");
            selectedKeys.add("lastname");
            selectedKeys.add("jobtitle");
            selectedKeys.add("jobactivity");
            selectedKeys.add("jobGroupId");
            selectedKeys.add("locationid");
            returnMaps.put("selectedKeys", selectedKeys);
            return returnMaps;
        } catch (Exception e) {
            new BaseBean().writeLog(e);
            throw new OrganizationRunTimeException("人员导入字段生成异常");
        }
    }

    /**
     * 获取导入模板及导入提示信息
     *
     * @param user         当前用户
     * @param templatePath 导入模板路径
     */
    public static List<Map<String, Object>> importForm(User user, String templatePath) {

        // 返回导入数据
        List<Map<String, Object>> lsGroup = new ArrayList<>();
        Map<String, Object> groupItem = new HashMap<>();
        List<Object> itemList = new ArrayList<>();

        groupItem.put("title", SystemEnv.getHtmlLabelName(1361, user.getLanguage()));
        groupItem.put("defaultshow", true);

        SearchConditionItem searchConditionItem;
        ConditionFactory conditionFactory = new ConditionFactory(user);

        //重复验证字段
        List<SearchConditionOption> statusOptions = new ArrayList<>();
        statusOptions.add(new SearchConditionOption("lastname", SystemEnv.getHtmlLabelName(413, user.getLanguage())));
        statusOptions.add(new SearchConditionOption("workcode", SystemEnv.getHtmlLabelName(714, user.getLanguage()), true));
        statusOptions.add(new SearchConditionOption("loginid", SystemEnv.getHtmlLabelName(412, user.getLanguage())));
        searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, 24638, "keyField", statusOptions);
        searchConditionItem.setValue("lastname");
        itemList.add(searchConditionItem);

        //导入类型
        List<SearchConditionOption> statusOptions1 = new ArrayList<>();
        statusOptions1.add(new SearchConditionOption("add", SystemEnv.getHtmlLabelName(611, user.getLanguage()), true));
        statusOptions1.add(new SearchConditionOption("update", SystemEnv.getHtmlLabelName(17744, user.getLanguage())));
        searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, 24863, "importType", statusOptions1);
        searchConditionItem.setValue("add");
        itemList.add(searchConditionItem);

        //模板文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.INPUT, 28576, "templet");
        searchConditionItem.setValue(templatePath);
        itemList.add(searchConditionItem);

        //Excel文件
        searchConditionItem = conditionFactory.createCondition(ConditionType.RESOURCEIMG, 16630, "excelfile");
        itemList.add(searchConditionItem);

        groupItem.put("items", itemList);
        lsGroup.add(groupItem);


        itemList = new ArrayList<>();
        groupItem = new HashMap<>();
        groupItem.put("title", SystemEnv.getHtmlLabelName(33803, Util.getIntValue(user.getLanguage())));
        groupItem.put("defaultshow", true);
        List<Integer> lsPromptLabel = new ArrayList<>(); //提示信息
        lsPromptLabel.add(128520);
        lsPromptLabel.add(125868);
        lsPromptLabel.add(128365);
        //lsPromptLabel.add(81697);
        //lsPromptLabel.add(81698);
        lsPromptLabel.add(81699);
        lsPromptLabel.add(516263);
        //lsPromptLabel.add(81701);
        //lsPromptLabel.add(388880);
        lsPromptLabel.add(81702);
        lsPromptLabel.add(81703);
        lsPromptLabel.add(125869);

        for (int i = 0; i < lsPromptLabel.size(); i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("index", (i + 1));
            String value = Util.toScreen(SystemEnv.getHtmlLabelName(lsPromptLabel.get(i), user.getLanguage()), user.getLanguage());
            if (i == 0) {
                value += SystemEnv.getHtmlLabelName(28576, user.getLanguage());
                item.put("link", templatePath);
            }
            item.put("value", value);
            itemList.add(item);
        }
        groupItem.put("items", itemList);
        lsGroup.add(groupItem);
        return lsGroup;
    }

    /**
     * @param operateType 导入类型
     * @param excelFile   上传的文件
     * @param user        当前用户
     */
    public static Long saveImport(String operateType, String excelFile, User user, HttpServletRequest request) {
        Long importHistoryId = OrgImportUtil.saveImportLog("resource", operateType, user);
        HrmImportAdaptExcelE9 importAdapt = new HrmImportAdaptExcelE9();
        FileUploadToPath fu = new FileUploadToPath(request);

        List<String> errorInfo = importAdapt.creatImportMap(fu);

        //如果读取数据和验证模板没有发生错误
        if (errorInfo.isEmpty()) {
            Map<String, HrmResourceVo> hrMap = importAdapt.getHrmImportMap();
            HrmImportProcessE9 importProcess = new HrmImportProcessE9();
            importProcess.init(request, importHistoryId);
            importProcess.processMap(hrMap);
        } else {
            for (String s : errorInfo) {
                MapperProxyFactory.getProxy(JclImportHistoryDetailMapper.class).insertHistoryDetail(JclImportHistoryDetailPO.builder().pid(importHistoryId).operateDetail(Util.null2String(s)).status("0").build());
            }
        }
        return importHistoryId;
    }

}
