package com.kingdee.eas.custom.projectbonus.web.service;

import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.custom.projectbonus.*;
import com.kingdee.eas.custom.projectbonus.bizEnum.BusDepProjectStateEnum;
import com.kingdee.eas.custom.projectbonus.bizEnum.CycleStateEnum;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.ats.AtsUtil;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseColumnInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseRowInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.ImportException;
import com.kingdee.util.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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


/**
 * @Description 分配人员明细列表导入模板_已提交(专员)
 * @Date 2024/5/7 21:28
 * @Created by Heyuan
 */
public class PersonnelDetailSubmitedImportService extends ProjectBonusImportService {
    private final static SelectorItemCollection updateSic = new SelectorItemCollection();

    static {
        updateSic.add("performanceGradeQ1");//Q1绩效等级
        updateSic.add("performanceGradeQ2");//Q2绩效等级
        updateSic.add("performanceCoeffQ1");//Q1绩效系数
        updateSic.add("performanceCoeffQ2");//Q2绩效系数
        updateSic.add("initialProportion");//个人初始比例
    }

    /**
     * 模板下载时携带数据
     *
     * @param columnInfoMap
     * @param wb
     * @param sheet
     */
    @Override
    public void completeGenerateExcel(Map<String, BaseColumnInfo> columnInfoMap,
                                      XSSFWorkbook wb,
                                      XSSFSheet sheet) {
        Context ctx = this.getContext();
        String bonusCycleId = this.getCustomParam("bonusCycleId");
        String busDepIds = this.getCustomParam("busDepIds");
        if (StringUtils.isEmpty(bonusCycleId)) {
            throw new RuntimeException("生成分配人员明细带数据导入模板报错,奖金周期id不能为空!");
        }
        int beginRow = 4;//数据生成开始行数
        //隐藏第一列
        //sheet.setColumnHidden(0, true);
        try {
            IBonusCycleBusDepProject iBonusCycleBusDepProject = BonusCycleBusDepProjectFactory.getLocalInstance(ctx);
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("AssPersonnelDetail.*");
            sic.add("AssPersonnelDetail.person.name");
            sic.add("AssPersonnelDetail.person.number");
            sic.add("*");
            sic.add("parent.*");
            sic.add("busDep.name");
            sic.add("busDep.number");
            sic.add("project.name");
            sic.add("project.number");
            sic.add("secondcenter.number");
            sic.add("secondcenter.name");
            FilterInfo filterInfo = new FilterInfo();
            FilterItemCollection filterItems = filterInfo.getFilterItems();
            filterItems.add(new FilterItemInfo("parent", bonusCycleId));
            filterItems.add(new FilterItemInfo("state", 2));//状态等于提交
            if (!StringUtils.isEmpty(busDepIds)) {
                Set<String> busDepIdSet = AtsUtil.toSet(busDepIds);
                filterItems.add(new FilterItemInfo("busDep.id", busDepIdSet, CompareType.INCLUDE));
            }
            SorterItemCollection sortItems = new SorterItemCollection();
            sortItems.add(new SorterItemInfo("busdep.id"));
            sortItems.add(new SorterItemInfo("type"));
            sortItems.add(new SorterItemInfo("project.id"));
            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, sortItems);
            BonusCycleBusDepProjectCollection depProjectCols = iBonusCycleBusDepProject.getBonusCycleBusDepProjectCollection(entityViewInfo);
            if (depProjectCols.size() > 0) {
                BonusCycleBusDepProjectInfo depProjectInfo = depProjectCols.get(0);
                BonusCycleInfo bonusCycleInfo = depProjectInfo.getParent();
                CycleStateEnum state = bonusCycleInfo.getState();
                if (CycleStateEnum.LOCK.equals(state)) {
                    throw new RuntimeException("周期已锁定，不允许执行导入操作！");
                }
            } else {
                throw new RuntimeException("当前周期内没有已提交的明细数据可维护，无需下载模板导入！");
            }
            Map<Integer, String> columnIndexMap = this.getColumnIndexFn(columnInfoMap);
            int fillColumnCount = columnInfoMap.size();
            for (int i = 0; i < depProjectCols.size(); i++) {
                //事业部项目
                BonusCycleBusDepProjectInfo depProjectInfo = depProjectCols.get(i);
                //周期
                BonusCycleInfo bonusCycleInfo = depProjectInfo.getParent();
                //分配人员明细
                BonusCycleBusDepProjectAssPersonnelDetailCollection personnelDetailCols = depProjectInfo.getAssPersonnelDetail();
                for (int j = 0; j < personnelDetailCols.size(); j++) {
                    Row row = sheet.createRow(beginRow++);
                    BonusCycleBusDepProjectAssPersonnelDetailInfo info = personnelDetailCols.get(j);
                    PersonInfo person = info.getPerson();
                    for (int k = 0; k < fillColumnCount; ++k) {
                        Cell createCell = row.createCell(k);
                        String columnName = columnIndexMap.get(k);
                        String value = null;
                        CoreBaseInfo coreBase = null;
                        if (columnName.startsWith("BonusCycle.")) {
                            columnName = columnName.substring(columnName.indexOf(".") + 1);
                            coreBase = bonusCycleInfo;
                        } else if (columnName.startsWith("BonusCycleBusDepProject.")) {
                            columnName = columnName.substring(columnName.indexOf(".") + 1);
                            coreBase = depProjectInfo;
                        } else if (columnName.startsWith("Person.")) {
                            columnName = columnName.substring(columnName.indexOf(".") + 1);
                            coreBase = person;
                        } else {
                            coreBase = info;
                        }
                        Object obj = coreBase.get(columnName);
                        if (obj != null) {
                            if (obj instanceof CoreBaseInfo) {
                                CoreBaseInfo coreBaseInfo = (CoreBaseInfo) coreBase.get(columnName);
                                value = coreBaseInfo.get("number") + "##" + coreBaseInfo.get("name");
                            } else if (obj instanceof BigDecimal) {
                                BigDecimal bigDecimal = (BigDecimal) obj;
                                if (this.moneyFields.contains(columnName)) {
                                    value = bigDecimal.setScale(6, RoundingMode.HALF_UP).toPlainString();
                                } else {
                                    value = bigDecimal.setScale(2, RoundingMode.HALF_UP).toPlainString();
                                }
                            } else {
                                value = obj.toString();
                            }
                        }
                        createCell.setCellValue(value);
                    }
                }
            }
        } catch (Exception e) {
            if (e.getMessage().contains("fetched too much rows")) {
                throw new ImportException("查询的数据量超出限制！请联系系统管理员修改配置，或者减少下载的数据量。");
            } else {
                e.printStackTrace();
                throw new ImportException(e.getMessage());
            }
        }
    }

    /**
     * 校验对象
     *
     * @param coreBaseInfo
     * @throws ImportException
     */
    protected void verifyRowBiz(CoreBaseInfo coreBaseInfo) throws ImportException {
        BonusCycleBusDepProjectAssPersonnelDetailInfo info = (BonusCycleBusDepProjectAssPersonnelDetailInfo) coreBaseInfo;
        String id = info.getId().toString();
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("parent.parent.state");//周期锁定状态
        sic.add("parent.state");//
        try {
            IBonusCycleBusDepProjectAssPersonnelDetail iBonusCycleBusDepProjectAssPersonnelDetail =
                    BonusCycleBusDepProjectAssPersonnelDetailFactory.getLocalInstance(this.getContext());
            BonusCycleBusDepProjectAssPersonnelDetailInfo oldInfo = iBonusCycleBusDepProjectAssPersonnelDetail.getBonusCycleBusDepProjectAssPersonnelDetailInfo(new ObjectUuidPK(id), sic);
            CycleStateEnum state = oldInfo.getParent().getParent().getState();
            if (CycleStateEnum.LOCK.equals(state)) {
                throw new RuntimeException("周期已锁定，不允许执行导入操作！");
            }
            BusDepProjectStateEnum busDepProjectState = oldInfo.getParent().getState();
            if (!BusDepProjectStateEnum.SUBMITED.equals(busDepProjectState)) {
                throw new RuntimeException("事业部项目非已提交状态，不允许执行导入操作！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ImportException(e.getMessage());
        }
    }

    /**
     * 获取主键条件字符串
     *
     * @param row
     * @return
     */
    @Override
    protected String getPKSelectString(BaseRowInfo row) {
        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);
    }

    /**
     * 提交数据
     *
     * @param coreBaseInfo
     * @throws ImportException
     */
    @Override
    protected void submitData(CoreBaseInfo coreBaseInfo) throws ImportException {
        try {
            IBonusCycleBusDepProjectAssPersonnelDetail iBonusCycleBusDepProjectAssPersonnelDetail =
                    BonusCycleBusDepProjectAssPersonnelDetailFactory.getLocalInstance(this.getContext());
            iBonusCycleBusDepProjectAssPersonnelDetail.updatePartial(coreBaseInfo, updateSic);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ImportException(e.getMessage());
        }
    }

    /**
     * 将列对象数据转化成Map集合
     *
     * @param columnInfoMap
     * @return
     */
    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(var4++, key);
        }
        return columnIndexMap;
    }
}
