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

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.eas.basedata.org.AdminOrgUnitFactory;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.IAdminOrgUnit;
import com.kingdee.eas.custom.performancenew.*;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.*;
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/5/9
 * @apiNote 组织绩效得分带数据导入
 */
public class PerformImportService extends BaseImportService {
    private static final SelectorItemCollection UPDATESIC = new SelectorItemCollection();

    static {
        UPDATESIC.add("performanceScoreOrg");
    }

    /**
     * 启用 批量导入
     * 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;
        String parentId = getCustomParam("parentId");
        if (StringUtils.isEmpty(parentId)) {
            throw new RuntimeException("绩效考核周期表ID不可为空！！");
        }
        try {
            //循环拿出数据
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(this.getContext());
            IAdminOrgUnit iAdminOrgUnit = AdminOrgUnitFactory.getLocalInstance(this.getContext());
            IPersonRelationOrg iPersonRelationOrg = PersonRelationOrgFactory.getLocalInstance(this.getContext());

            while (rowIterator.hasNext()) {
                BaseRowInfo row = rowIterator.next();
                BaseResultInfo baseResultInfo = new BaseResultInfo(row);
                //部门编码
                String adminOrgNumber = row.getValueOfString("adminOrgNumber");
                //组织绩效得分
                String performanceScoreOrg = row.getValueOfString("performanceScoreOrg");
                AdminOrgUnitInfo adminOrgUnitInfo = iAdminOrgUnit.getAdminOrgUnitCollection("where number = '" + adminOrgNumber + "'").get(0);
                PersonRelationOrgInfo personRelationOrgInfo = iPersonRelationOrg.getPersonRelationOrgInfo("where name = '" + performanceScoreOrg + "'");
                //通过名称获取组织
                ExamineGradePersonEntryCollection examineGradePersonEntryCollection = iExamineGradePersonEntry.getExamineGradePersonEntryCollection("where parent.id='" + parentId + "' and adminOrg.id = '" + adminOrgUnitInfo.getId() + "'");
                if (examineGradePersonEntryCollection.size() > 0) {
                    for (int i = 0; i < examineGradePersonEntryCollection.size(); i++) {
                        ExamineGradePersonEntryInfo examineGradePersonEntryInfo = examineGradePersonEntryCollection.get(i);
                        examineGradePersonEntryInfo.setPerformanceScoreOrg(personRelationOrgInfo);
                        iExamineGradePersonEntry.updatePartial(examineGradePersonEntryInfo, UPDATESIC);
                    }
                    resultInfoList = new ArrayList();
                    resultInfoList.add(baseResultInfo);
                    for (BaseResultInfo resultInfo : resultInfoList) {
                        resultInfo.setMessage("导入成功!");
                        getMonitor().completeRow(resultInfo);
                    }
                }
            }
        } catch (Exception e) {
            resultInfoList = new ArrayList();
            for (BaseResultInfo resultInfo : resultInfoList) {
                if (resultInfo.isSuccess()) {
                    resultInfo.setSuccess(false);
                    resultInfo.setState(0);
                    resultInfo.setMessage(e.getMessage());
                    resultInfo.setLog(e.getMessage());
                    resultInfo.setE(new ImportException(e.getMessage()));
                }
                getMonitor().completeRow(resultInfo);
            }
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    protected String getPKSelectString(BaseRowInfo row) {
        String pkSelectString = super.getPKSelectString(row);
        String parentId = getCustomParam("parentId");
        if (StringUtils.isEmpty(parentId)) {
            throw new RuntimeException("绩效考核周期表ID不可为空！！");
        }
        return pkSelectString + " and parent.id ='" + parentId + "'";
    }

    @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不可为空！！");
        }

        int beginRow = 4;
        try {
            IExamineGradePerson iExamineGradePerson = ExamineGradePersonFactory.getLocalInstance(ctx);
            ExamineGradePersonInfo examineGradePersonInfo = iExamineGradePerson.getExamineGradePersonCollection("select entrys.adminOrg.* ,entrys.performanceScoreOrg.* where id = '" + parentId + "'").get(0);
            ExamineGradePersonEntryCollection entrys = examineGradePersonInfo.getEntrys();
            Set set = new HashSet<>();
            //去重操作
            for (int i = entrys.size() - 1; i >= 0; i--) {
                ExamineGradePersonEntryInfo examineGradePersonEntryInfo = entrys.get(i);
                String adminId = examineGradePersonEntryInfo.getAdminOrg().getId().toString();
                if (set.contains(adminId)) {
                    entrys.remove(examineGradePersonEntryInfo);
                } else {
                    set.add(adminId);
                }
            }
            Map<Integer, String> columnIndexMap = getColumnIndexFn(columnInfoMap);
            int fillColumnCount = columnInfoMap.size();
            for (int i = 0; i < entrys.size(); i++) {
                XSSFRow xSSFRow = sheet.createRow(i + beginRow);
                ExamineGradePersonEntryInfo examineGradePersonEntryInfo = entrys.get(i);
                String adminOrgNumber = null;
                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");
                            adminOrgNumber = (String) coreBaseInfo.get("number");

                        } else if (obj instanceof BigDecimal) {
                            BigDecimal bigDecimal = (BigDecimal) obj;
                            value = bigDecimal.setScale(2).toPlainString();
                        } else {
                            value = obj.toString();
                        }
                    }
                    if (columnName.equals("adminOrgNumber")) {
                        value = (String) adminOrgNumber;
                    }
                    createCell.setCellValue(value);
                }
            }
        } catch (BOSException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    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;
    }
}
