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.SelectorItemCollection;
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.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.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Description 事业部项目带数据导入
 * @Date 2024/4/29 18:04
 * @Created by Heyuan
 */
public class BonusCycleBusDepProjectImportService extends ProjectBonusImportService {
    /**
     * 模板下载时携带数据
     *
     * @param columnInfoMap
     * @param wb
     * @param sheet
     */
    @Override
    public void completeGenerateExcel(Map<String, BaseColumnInfo> columnInfoMap,
                                      XSSFWorkbook wb,
                                      XSSFSheet sheet) {
        Context ctx = this.getContext();
        String parentId = this.getCustomParam("parentId");
        if (StringUtils.isEmpty(parentId)) {
            throw new RuntimeException("生成事业部项目带数据导入模板报错,parentId参数不能为空!");
        }
        int beginRow = 4;//数据生成开始行数
        try {
            //奖金周期
            IBonusCycle iBonusCycle = BonusCycleFactory.getLocalInstance(ctx);
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("cycleName");
            sic.add("state");
            sic.add("BusDepProject.*");
            sic.add("BusDepProject.busDep.name");//事业部
            sic.add("BusDepProject.busDep.number");
            sic.add("BusDepProject.project.name");//项目
            sic.add("BusDepProject.project.number");
            sic.add("BusDepProject.principal.name");//事业部负责人
            sic.add("BusDepProject.principal.number");
            sic.add("BusDepProject.projectPrincipal.name");//项目负责人
            sic.add("BusDepProject.projectPrincipal.number");
            BonusCycleInfo bonusCycleInfo = iBonusCycle.getBonusCycleInfo(new ObjectUuidPK(parentId), sic);
            CycleStateEnum state = bonusCycleInfo.getState();
            if (CycleStateEnum.LOCK.equals(state)) {
                throw new RuntimeException("周期已锁定，不允许执行导入操作！");
            }
            String cycleName = bonusCycleInfo.getCycleName();//周期名称
            BonusCycleBusDepProjectCollection busDepProjectCols = bonusCycleInfo.getBusDepProject();//事业部项目集合
            Map<Integer, String> columnIndexMap = this.getColumnIndexFn(columnInfoMap);
            int fillColumnCount = columnInfoMap.size();
            //隐藏第一列
            //sheet.setColumnHidden(0, true);
            for (int i = 0; i < busDepProjectCols.size(); i++) {
                Row row = sheet.createRow(i + beginRow);
                BonusCycleBusDepProjectInfo info = busDepProjectCols.get(i);
                for (int j = 0; j < fillColumnCount; ++j) {
                    String value = null;
                    Cell createCell = row.createCell(j);
                    String columnName = columnIndexMap.get(j);
                    int index = columnName.indexOf(".");
                    if (index == -1) {
                        Object obj = info.get(columnName);
                        if (obj != null) {
                            if (obj instanceof CoreBaseInfo) {
                                CoreBaseInfo coreBaseInfo = (CoreBaseInfo) info.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();
                            }
                        }
                    } else {
                        value = cycleName;
                    }
                    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
     */
    @Override
    protected void submitData(CoreBaseInfo coreBaseInfo) throws ImportException {
        try {
            IBonusCycleBusDepProject iBonusCycleBusDepProject = BonusCycleBusDepProjectFactory.getLocalInstance(this.getContext());
            BonusCycleBusDepProjectInfo info = (BonusCycleBusDepProjectInfo) coreBaseInfo;
            BusDepProjectStateEnum state = info.getState();
            //根据事业部状态获取更新列
            SelectorItemCollection updateSic = getUpdateSic(state);
            iBonusCycleBusDepProject.updatePartial(info, 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;
    }

    /**
     * 校验对象
     *
     * @param coreBaseInfo
     * @throws ImportException
     */
    protected void verifyRowBiz(CoreBaseInfo coreBaseInfo) throws ImportException {
        BonusCycleBusDepProjectInfo info = (BonusCycleBusDepProjectInfo) coreBaseInfo;
        String id = info.getId().toString();
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("parent.state");//周期锁定状态
        try {
            IBonusCycleBusDepProject iBonusCycleBusDepProject = BonusCycleBusDepProjectFactory.getLocalInstance(this.getContext());
            BonusCycleBusDepProjectInfo oldInfo = iBonusCycleBusDepProject.getBonusCycleBusDepProjectInfo(new ObjectUuidPK(id), sic);
            CycleStateEnum state = oldInfo.getParent().getState();
            if (CycleStateEnum.LOCK.equals(state)) {
                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 state
     * @return
     */
    protected SelectorItemCollection getUpdateSic(BusDepProjectStateEnum state) {
        SelectorItemCollection updateSic = new SelectorItemCollection();
        updateSic.add("notPrincipalPropor");//非负责人初始比例
        updateSic.add("principalPropor");//负责人初始比例
        updateSic.add("totalBonusHalf");//上半年总奖金额（100%口径）
        updateSic.add("totalBonusReal");//上半年实发奖金额（①+②+③+④+⑤）
        updateSic.add("directManProjBonus");//①直管项目奖金
        updateSic.add("contraManProjBonus");//②委托项目奖金
        updateSic.add("condManProjectBonus");//③共管项目奖金
        updateSic.add("condManProjectBonus");//③共管项目奖金
        updateSic.add("straManProjectBonus");//④战略型项目奖金
        updateSic.add("bonusAdjustment");//⑤奖金调整
        updateSic.add("bonusAdjustmentDesc");//奖金调整说明
        updateSic.add("initialAllocationRatio1");//事业部平台初始分配比例
        updateSic.add("initialAllocationRatio2");//∑项目初始分配比例
        updateSic.add("initialAllocationRatio3");//直管项目负责人初始分配比例
        updateSic.add("projectPrincipal");//项目负责人
        if (BusDepProjectStateEnum.INITIALIZATION.equals(state)
                || BusDepProjectStateEnum.DISABLE.equals(state)) {
            //当状态等于初始化 或 禁用, 才能修改 负责人
            updateSic.add("principal");//负责人
        }
        if (!BusDepProjectStateEnum.SUBMITCALCULATED.equals(state) && !BusDepProjectStateEnum.RECHECK.equals(state)) {
            //当状态不等于已计算和已复核
            updateSic.add("bonusAmount");//奖金分包金额
        }
        return updateSic;
    }
}
