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.hrm.util.face.hrmrestful.service.HrmFieldManagerForService;
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.enums.HrmGroupEnum;
import com.engine.organization.enums.LogModuleNameEnum;
import com.engine.organization.enums.OperateTypeEnum;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.jclimport.ImportMapper;
import com.engine.organization.thread.OrganizationSyncEc;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.io.IOException;
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/01
 * @version: 1.0
 */
public class CompanyImport {

    private static ImportMapper getImportMapper() {
        return MapperProxyFactory.getProxy(ImportMapper.class);
    }

    /**
     * 导入模板可选择字段
     *
     * @param user           当前用户
     * @param excludedFields 排除的字段
     */
    public static Map<String, Object> getImportFields(User user, List<String> excludedFields) {
        Map<String, Object> returnMaps = new HashMap<>();
        List<HrmFormFieldPO> importFields = getImportMapper().getImportFields(user.getLanguage(), HrmGroupEnum.COMPANY.getGroupType());
        importFields.removeIf(item -> excludedFields.contains(item.getFieldName()));

        // 查询所有可以勾选的字段
        List<FieldTransferParam> fieldDatas = importFields.stream().map(item -> FieldTransferParam.builder().id(item.getFieldId().toString()).name(item.getLabelName()).build()).collect(Collectors.toList());
        returnMaps.put("data", fieldDatas);
        // 设置必填字段
        List<String> selectedKeys = importFields.stream().filter(item -> null != item.getIsSystem() && 1 == item.getIsSystem() && 1 == item.getIsMand()).map(item -> item.getFieldId().toString()).collect(Collectors.toList());
        returnMaps.put("selectedKeys", selectedKeys);
        return returnMaps;
    }

    /**
     * 获取导入模板及导入提示信息
     *
     * @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("add", SystemEnv.getHtmlLabelName(611, user.getLanguage()), true));
        statusOptions.add(new SearchConditionOption("update", SystemEnv.getHtmlLabelName(17744, user.getLanguage())));
        searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, 24863, "importType", statusOptions);
        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(34275);
        lsPromptLabel.add(125452);
        lsPromptLabel.add(125466);
        lsPromptLabel.add(522356);
        lsPromptLabel.add(522357);
        lsPromptLabel.add(530411);

        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) {
        Long importHistoryId = OrgImportUtil.saveImportLog("company", operateType, user);
        JclImportHistoryDetailPO historyDetailPO;

        ImageFileManager manager = new ImageFileManager();
        manager.getImageFileInfoById(Util.getIntValue(excelFile));
        XSSFWorkbook workbook;
        try {
            workbook = new XSSFWorkbook(manager.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 当前sheet
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        int lastRow = sheetAt.getLastRowNum();
        List<HrmFormFieldPO> extendInfoPOS = new ArrayList<>();
        OrganizationAssert.isTrue(lastRow > 0, "导入数据为空");
        short lastCellNum = sheetAt.getRow(0).getLastCellNum();


        // 遍历每一行数据
        nextRow:
        for (int i = 0; i <= lastRow; i++) {
            historyDetailPO = new JclImportHistoryDetailPO();
            historyDetailPO.setPid(importHistoryId);
            XSSFRow row = sheetAt.getRow(i);
            if (null == row) {
                continue;
            }
            // 组装待处理数据
            Map<String, Object> map = new HashMap<>();
            Integer parentCompanyId = null;
            String companyName = "";

            historyDetailPO.setRowNums(String.valueOf(i + 1));
            for (int cellIndex = 0; cellIndex < lastCellNum; cellIndex++) {
                XSSFCell cell = row.getCell((short) cellIndex);
                String cellValue = OrgImportUtil.getCellValue(cell).trim();
                if (i == 0) {
                    List<HrmFormFieldPO> infoPOList = getImportMapper().getImportFieldInfo(user.getLanguage(), HrmGroupEnum.COMPANY.getGroupType(), cellValue);
                    boolean isBreak = OrgImportUtil.isBreak(historyDetailPO, cellValue, infoPOList);
                    if (isBreak) {
                        break nextRow;
                    }
                    // 首行 初始化字段信息
                    extendInfoPOS.add(infoPOList.get(0));
                } else {
                    HrmFormFieldPO infoPO = extendInfoPOS.get(cellIndex);
                    // 数据校验
                    if (infoPO.getIsMand() == 1 && StringUtils.isBlank(cellValue) && !"subcompanycode".equalsIgnoreCase(infoPO.getFieldName())) {
                        historyDetailPO.setOperateDetail(infoPO.getLabelName() + "为必填项");
                        historyDetailPO.setStatus("0");
                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }

                    Object reallyValue;
                    try {
                        if ("subcompanyname".equalsIgnoreCase(infoPO.getFieldName())) {
                            reallyValue = cellValue;
                        } else {
                            reallyValue = HrmFieldManagerForService.getReallyFieldvalue(infoPO.getJsonObject(cellValue), true);
                        }
                    } catch (Exception e) {
                        historyDetailPO.setOperateDetail(cellValue + "转换失败");
                        historyDetailPO.setStatus("0");
                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }
                    if (StringUtils.isNotBlank(cellValue) && StringUtils.isBlank(Util.null2String(reallyValue))) {
                        historyDetailPO.setOperateDetail(infoPO.getLabelName() + "数据转换失败,未找到对应数据");
                        historyDetailPO.setStatus("0");
                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                        continue nextRow;
                    }
                    map.put(infoPO.getFieldName(), reallyValue);
                    if ("subcompanyname".equalsIgnoreCase(infoPO.getFieldName())) {
                        historyDetailPO.setRelatedName(cellValue);
                        String[] split = cellValue.split(">");
                        if (split.length > 0) {
                            if (split.length > 8) {
                                historyDetailPO.setOperateDetail("分部层级不能大于10");
                                historyDetailPO.setStatus("0");
                                OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                continue nextRow;
                            }
                            for (int index = 0; index < split.length - 1; index++) {
                                parentCompanyId = MapperProxyFactory.getProxy(CompMapper.class).getIdByNameAndPid(split[index], parentCompanyId == null ? 0 : parentCompanyId);
                                if (null == parentCompanyId) {
                                    historyDetailPO.setOperateDetail(split[index] + "分部未找到对应数据");
                                    historyDetailPO.setStatus("0");
                                    OrgImportUtil.saveImportDetailLog(historyDetailPO);
                                    continue nextRow;
                                }
                            }
                        }
                        map.put("supsubcomid", Util.null2String(parentCompanyId));

                        companyName = split[split.length - 1];
                        map.put("subcompanyname", companyName);
                        map.put("subcompanydesc", companyName);
                    }

                }
            }
            // 校验、数据交互
            if (i == 0) {
                continue;
            }

            if ("add".equals(operateType)) {
                Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.COMPANY, OperateTypeEnum.ADD, map, false).sync();
                if (OrgImportUtil.isThrowError(syncMap)) {
                    // 刷新组织架构图
                    //TODO new CompanyTriggerRunnable(infoParams.getId()).run();
                    historyDetailPO.setOperateDetail("添加成功");
                    historyDetailPO.setStatus("1");
                } else {
                    historyDetailPO.setOperateDetail(Util.null2String(syncMap.get("message")));
                    historyDetailPO.setStatus("0");
                }
                OrgImportUtil.saveImportDetailLog(historyDetailPO);
            } else if ("update".equals(operateType)) {
                String compNo = (String) map.get("subcompanycode");
                // 查询对应ID
                if (StringUtils.isNotBlank(compNo)) {
                    Integer companyId = MapperProxyFactory.getProxy(CompMapper.class).getIdBySubCompanyCode(compNo);
                    if (companyId == null) {
                        historyDetailPO.setOperateDetail("未找到对应数据");
                        historyDetailPO.setStatus("0");
                        OrgImportUtil.saveImportDetailLog(historyDetailPO);
                        continue;
                    }
                    map.put("id", Util.null2String(companyId));
                    Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.COMPANY, OperateTypeEnum.UPDATE, map, false).sync();
                    if (OrgImportUtil.isThrowError(syncMap)) {
                        // 刷新组织架构图
                        //TODO new CompanyTriggerRunnable(companyId).run();
                        historyDetailPO.setOperateDetail("更新成功");
                        historyDetailPO.setStatus("1");
                    } else {
                        historyDetailPO.setOperateDetail(Util.null2String(syncMap.get("message")));
                        historyDetailPO.setStatus("0");
                    }
                    OrgImportUtil.saveImportDetailLog(historyDetailPO);
                } else {
                    historyDetailPO.setOperateDetail("编号为空,更新失败");
                    historyDetailPO.setStatus("0");
                    OrgImportUtil.saveImportDetailLog(historyDetailPO);
                }
            }
        }
        return importHistoryId;
    }

}
