package com.kingdee.eas.custom.performancenew.service;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.sql.ParserException;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.expandassess.app.AssessRatingEnum;
import com.kingdee.eas.custom.performancenew.*;
import com.kingdee.eas.custom.performancenew.app.scoreEnum;
import com.kingdee.eas.custom.performancenew.handler.service.ExamineScorePersonService;
import com.kingdee.eas.custom.performancenew.handler.service.impl.ExamineScorePersonServiceImpl;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.ats.AtsUtil;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.shr.base.syssetting.app.io.fileImport.*;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.ml.util.SHRServerResource;
import com.kingdee.shr.shrimport.SHRFileTemplateInfo;
import com.kingdee.util.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author qingwu
 * @date 2024/4/19
 * @apiNote 周期季度（评分人导入）人员考核等级评分
 */
public class ExamineGradeImportPFRService extends BaseImportService {
    ExamineScorePersonService examineScorePersonService = new ExamineScorePersonServiceImpl();
    private static final SelectorItemCollection SIC = new SelectorItemCollection();
    private static final SelectorItemCollection UPDATESIC = new SelectorItemCollection();

    static {
        SIC.add("adminOrg.name");
        SIC.add("adminOrg.number");
        SIC.add("auditor.name");
        SIC.add("upLastScore");
        SIC.add("upLastLevel");
        SIC.add("scoreleader");
        SIC.add("remark");

        UPDATESIC.add("upLastScore");
        UPDATESIC.add("upLastLevel");
        UPDATESIC.add("scoreleader");
        UPDATESIC.add("remark");
    }

    /**
     * 启用 批量导入
     * com.kingdee.shr.base.syssetting.app.io.fileImport.ImportTaskExecutor#run() 135
     *
     * @param templateInfo
     * @return
     */
    @Override
    public boolean isBatch(SHRFileTemplateInfo templateInfo) {
        return true;
    }

    /**
     * 开始执行批量导入
     *
     * @param rowIterator
     * @return
     */
    @Override
    public boolean startBatchImport(Iterator<BaseRowInfo> rowIterator) {
        List<BaseResultInfo> resultInfoList = null;
        List<ExamineGradePersonEntryInfo> entryListData = new ArrayList<>();
        Map<String, BaseResultInfo> map = new HashMap();

        try {
            //循环拿出数据
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(this.getContext());
            while (rowIterator.hasNext()) {
                BaseRowInfo row = rowIterator.next();
                BaseResultInfo baseResultInfo = new BaseResultInfo(row);
                String fid = row.getValueOfString("id");
                String upLastScore = row.getValueOfString("upLastScore");
                String upLastLevel = row.getValueOfString("upLastLevel");
                String scoreleader = row.getValueOfString("scoreLeader");
                String remark = row.getValueOfString("remark");
                ExamineGradePersonEntryInfo entryInfo = iExamineGradePersonEntry.getExamineGradePersonEntryInfo(new ObjectUuidPK(fid), SIC);
                entryInfo.setUpLastLevel(scoreEnum.getEnum(getscoreEnum(upLastLevel)));
                entryInfo.setUpLastScore(new BigDecimal(upLastScore));
                entryInfo.setScoreLeader(scoreEnum.getEnum(getscoreEnum(scoreleader)));
                entryInfo.setRemark(remark);
                entryListData.add(entryInfo);
                map.put(entryInfo.getId().toString(), baseResultInfo);
            }
            //先排序list数据  按照部门和顺序排序
            Collections.sort(entryListData, new Comparator<ExamineGradePersonEntryInfo>() {
                @Override
                public int compare(ExamineGradePersonEntryInfo o1, ExamineGradePersonEntryInfo o2) {
                    // 首先按照名称排序
                    int nameComparison = o1.getAdminOrg().getId().toString().compareTo(o2.getAdminOrg().getId().toString());
                    if (nameComparison != 0) {
                        return nameComparison;
                    }
                    // 如果名称相同，则按照编号排序
                    return o1.getIndex() - o2.getIndex();
                }
            });
            // 使用Map存储每个分类的最大编号
            Map<String, Integer> maxNumberMap = new HashMap<>();
            ExamineGradePersonEntryCollection entryCollection = new ExamineGradePersonEntryCollection();
            //排序后的数据校验顺序是否断层
            for (int i = 0; i < entryListData.size(); i++) {
                ExamineGradePersonEntryInfo entryInfo = entryListData.get(i);
                AdminOrgUnitInfo adminOrg = entryInfo.getAdminOrg();
                String adminId = adminOrg.getId().toString();
                int order = entryInfo.getIndex();
                Integer maxNumber = maxNumberMap.getOrDefault(adminId, 0);
                BaseResultInfo baseResultInfo = map.get(entryInfo.getId().toString());
                // 检查编号是否按顺序且没有断层
                //if (order == maxNumber + 1) {
                maxNumberMap.put(adminId, order);
                resultInfoList = new ArrayList();
                resultInfoList.add(baseResultInfo);
                for (BaseResultInfo resultInfo : resultInfoList) {
                    resultInfo.setMessage("导入成功!");
                    getMonitor().completeRow(resultInfo);
                }
                entryCollection.add(entryInfo);
                iExamineGradePersonEntry.updatePartial(entryInfo, UPDATESIC);
                //} else {
                //    resultInfoList = new ArrayList();
                //    resultInfoList.add(baseResultInfo);
                //    for (BaseResultInfo resultInfo : resultInfoList) {
                //        if (resultInfo.isSuccess()) {
                //            resultInfo.setSuccess(false);
                //            resultInfo.setState(0);
                //            resultInfo.setMessage("部门[" + adminOrg.getName() + "] 中的顺序不符合规则!!");
                //            resultInfo.setLog("部门[" + adminOrg.getName() + "] 中的顺序不符合规则!!");
                //            resultInfo.setE(new ImportException("部门[" + adminOrg.getName() + "] 中的顺序不符合规则!!"));
                //        }
                //        getMonitor().completeRow(resultInfo);
                //    }
                //}
            }
            //导入数据后通重新排序
            examineScorePersonService.maintainIndex(getCustomParam("parentId"));
        } catch (BOSException e) {
            throw new RuntimeException(e);
        } catch (EASBizException e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    public String getscoreEnum(String score) {
        switch (score) {
            case "A":
                return "1";
            case "B+":
                return "2";
            case "B":
                return "3";
            case "B-":
                return "4";
            case "C":
                return "5";
            case "D":
                return "6";
            default:
                return "";
        }
    }

    @Override
    public void completeGenerateExcel(Map<String, BaseColumnInfo> columnInfoMap, XSSFWorkbook wb, XSSFSheet sheet) {
        Context ctx = getContext();
        String parentId = getCustomParam("parentId");
        if (StringUtils.isEmpty(parentId)) {
            throw new RuntimeException("绩效考核周期表ID不可为空！！");
        }
        String adminOrgId = getCustomParam("adminOrgId");

        int beginRow = 4;
        try {

            //当前登录员工id
            String currentPersonId = ContextUtil.getCurrentUserInfo(ctx).getPerson().getId().toString();
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("auditor.name");
            sic.add("adminOrg.name");
            sic.add("adminOrg.id");
            sic.add("upLastScore");
            sic.add("upLastLevel");
            sic.add("scoreleader");
            sic.add("remark");
            //过滤当前周期状态为已启用排序评分人等于登录人的数据
            FilterInfo filterInfo = new FilterInfo();
            FilterItemCollection filterItems = filterInfo.getFilterItems();
            filterItems.add(new FilterItemInfo("parent.id", parentId));
            filterItems.add(new FilterItemInfo("orderStatuc", "2", CompareType.NOTEQUALS));
            filterItems.add(new FilterItemInfo("scorer.id", currentPersonId));
            //判断前端是否带组织查询如何查询拿到过滤条件
            if (!StringUtils.isEmpty(adminOrgId)) {
                filterItems.add(new FilterItemInfo("adminOrg.id", AtsUtil.toSet(adminOrgId), CompareType.INCLUDE));
            }
            SorterItemCollection sorterItemCollection = new SorterItemCollection();
            sorterItemCollection.add(new SorterItemInfo("adminOrg.id"));
            sorterItemCollection.add(new SorterItemInfo("index"));
            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, sorterItemCollection);
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            //绩效考核分录实体
            ExamineGradePersonEntryCollection entryCollection = iExamineGradePersonEntry.getExamineGradePersonEntryCollection(entityViewInfo);
            Map<Integer, String> columnIndexMap = getColumnIndexFn(columnInfoMap);
            int fillColumnCount = columnInfoMap.size();
            for (int i = 0; i < entryCollection.size(); i++) {
                XSSFRow xSSFRow = sheet.createRow(i + beginRow);
                ExamineGradePersonEntryInfo examineGradePersonEntryInfo = entryCollection.get(i);
                for (int j = 0; j < fillColumnCount; j++) {
                    String value = null;
                    Cell createCell = xSSFRow.createCell(j);
                    String columnName = columnIndexMap.get(Integer.valueOf(j));
                    Object obj = examineGradePersonEntryInfo.get(columnName);
                    if (obj != null) {
                        if (obj instanceof CoreBaseInfo) {
                            CoreBaseInfo coreBaseInfo = (CoreBaseInfo) examineGradePersonEntryInfo.get(columnName);
                            //value = coreBaseInfo.get("number") + "##" + coreBaseInfo.get("name");
                            value = (String) coreBaseInfo.get("name");
                        } else if (obj instanceof BigDecimal) {
                            BigDecimal bigDecimal = (BigDecimal) obj;
                            value = bigDecimal.setScale(2).toPlainString();
                        } else {
                            if ("upLastScore".equals(columnName) || "upLastLevel".equals(columnName) || "scoreLeader".equals(columnName)) {
                                value = AssessRatingEnum.getEnum((String) obj).getAlias();
                            } else {
                                value = obj.toString();
                            }
                        }
                    }
                    createCell.setCellValue(value);
                }
            }
        } catch (BOSException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void submitData(CoreBaseInfo coreBaseInfo) throws ImportException {
        SelectorItemCollection updateSic = new SelectorItemCollection();
        updateSic.add("upLastScore");
        updateSic.add("upLastLevel");
        try {
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(getContext());
            iExamineGradePersonEntry.updatePartial(coreBaseInfo, updateSic);
        } catch (EASBizException var4) {
            ImportException importException = new ImportException(var4.getMessage(getContext().getLocale()), (Throwable) var4);
            throw importException;
        } catch (BOSException var5) {
            ImportException importException = new ImportException(SHRServerResource.getString("com.kingdee.shr.base.syssetting.CommonserviceResource", "save_fails_bos", getContext()), (Throwable) var5);
            throw importException;
        } catch (Exception var6) {
            ImportException importException = new ImportException(SHRServerResource.getString("com.kingdee.shr.base.syssetting.CommonserviceResource", "save_submit_fails", getContext()), var6);
            throw importException;
        }
    }

    protected Map<Integer, String> getColumnIndexFn(Map<String, BaseColumnInfo> columnInfoMap) {
        Map<Integer, String> columnIndexMap = new HashMap<>();
        Iterator<String> keys = columnInfoMap.keySet().iterator();
        int var4 = 0;
        while (keys.hasNext()) {
            String key = keys.next();
            columnIndexMap.put(Integer.valueOf(var4++), key);
        }
        return columnIndexMap;
    }

    @Override
    protected String getPKSelectString(BaseRowInfo row) {
        String parentId = getCustomParam("parentId");
        List<BaseColumnInfo> keyColumnList = row.getKeyColumnInfo();
        for (int i = 0; i < keyColumnList.size(); i++) {
            BaseColumnInfo keyColumn = keyColumnList.get(i);
            keyColumn.setCustomField(false);
        }
        return super.getPKSelectString(row) + " and parent.id ='" + parentId + "' and orderstatuc <>'2'";
    }
}
