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

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.eas.basedata.person.IPerson;
import com.kingdee.eas.basedata.person.PersonCollection;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.custom.attendanceexception.*;
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.BaseImportService;
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.log4j.Logger;
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.util.*;

/**
 * @Description 中心负责人关系表导入业务实现类
 * @Date 2025/4/15 18:28
 * @Created by Heyuan
 */
public class CenterLeaderRelationImportService extends BaseImportService {
    private static Logger logger = Logger.getLogger(CenterLeaderRelationImportService.class);

    /**
     * 设置其他字段
     *
     * @param baseInfo
     * @param row
     * @throws ImportException
     */
    @Override
    protected void setOtherFieldInfo(CoreBaseInfo baseInfo, BaseRowInfo row) throws ImportException {
        super.setOtherFieldInfo(baseInfo, row);
        try {
            CenterLeaderRelationInfo relationInfo = (CenterLeaderRelationInfo) baseInfo;
            CenterLeaderRelationEntryCollection entrys = relationInfo.getEntry();
            entrys.clear();
            Map<String, BaseColumnInfo> mapColumnInfo = row.getMapColumnInfo();
            Context ctx = this.getContext();
            IPerson iPerson = null;
            iPerson = PersonFactory.getLocalInstance(ctx);
            for (String key : mapColumnInfo.keySet()) {
                BaseColumnInfo columnInfo = mapColumnInfo.get(key);
                String propName = columnInfo.getPropName();
                String name = columnInfo.getName();
                if (columnInfo.isCustomField() && propName.startsWith("person")) {
                    String value = row.getValueOfString(propName);
                    if (StringUtils.isEmpty(value)) {
                        continue;
                    }
                    String filter = null;
                    if (value.contains("##")) {
                        String[] split = value.split("##");
                        String number = split[0];
                        filter = "where number = '" + number + "'";
                    } else {
                        filter = "where number = '" + value + "' or name = '" + value + "'";
                    }
                    PersonCollection personCollection = iPerson.getPersonCollection(filter);
                    if (personCollection.size() > 0) {
                        PersonInfo personInfo = personCollection.get(0);
                        CenterLeaderRelationEntryInfo entry = new CenterLeaderRelationEntryInfo();
                        entry.setPerson(personInfo);
                        entrys.add(entry);
                    } else {
                        throw new ImportException(name + " " + value + " 未找到，请检查数据是否有误");
                    }
                }
            }
        } catch (BOSException e) {
            logger.error(e.getMessage(), e);
            throw new ImportException(e);
        }
    }

    /**
     * 模板下载时携带数据
     *
     * @param columnInfoMap
     * @param wb
     * @param sheet
     */
    @Override
    public void completeGenerateExcel(Map<String, BaseColumnInfo> columnInfoMap, XSSFWorkbook wb, XSSFSheet sheet) {
        Context ctx = this.getContext();
        int beginRow = 4;//数据生成开始行数
        try {
            ICenterLeaderRelation iCenterLeaderRelation = CenterLeaderRelationFactory.getLocalInstance(ctx);
            SelectorItemCollection sic = getSelectorItemCollection(columnInfoMap);
            SorterItemCollection sortItems = new SorterItemCollection();
            sortItems.add(new SorterItemInfo("department.sortCode"));
            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(null, sic, sortItems);
            //查询中心负责人关系表
            CenterLeaderRelationCollection relationCollection = iCenterLeaderRelation.getCenterLeaderRelationCollection(entityViewInfo);
            //获取字段
            Map<Integer, String> columnIndexMap = this.getColumnIndexFn(columnInfoMap);
            int fillColumnCount = columnInfoMap.size();
            for (int j = 0; j < relationCollection.size(); j++) {
                Row row = sheet.createRow(beginRow++);
                //中心负责人关系表
                CenterLeaderRelationInfo relationInfo = relationCollection.get(j);
                //分录
                CenterLeaderRelationEntryCollection entrys = relationInfo.getEntry();
                for (int k = 0; k < fillColumnCount; ++k) {
                    Object obj = null;
                    Cell createCell = row.createCell(k);
                    String columnName = columnIndexMap.get(k);
                    String value = null;
                    if (columnName.startsWith("person")) {
                        String num = columnName.replace("person", "");
                        if (!StringUtils.isEmpty(num)) {
                            Integer index = Integer.valueOf(num);
                            if (index > entrys.size()) {
                                value = "";
                            } else {
                                CenterLeaderRelationEntryInfo entryInfo = entrys.get(index - 1);
                                obj = entryInfo.getPerson();
                            }
                        } else {
                            continue;
                        }
                    } else {
                        obj = relationInfo.get(columnName);
                    }
                    if (obj != null) {
                        if (obj instanceof CoreBaseInfo) {
                            CoreBaseInfo coreBaseInfo = (CoreBaseInfo) obj;
                            value = coreBaseInfo.get("number") + "##" + coreBaseInfo.get("name");
                        } else if (obj instanceof Boolean) {
                            value = (Boolean) obj ? "是" : "否";
                        } 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());
            }
        }
    }

    /**
     * 将列对象数据转化成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 columnInfoMap
     * @return
     */
    protected SelectorItemCollection getSelectorItemCollection(Map<String, BaseColumnInfo> columnInfoMap) {
        SelectorItemCollection sic = new SelectorItemCollection();
        for (String key : columnInfoMap.keySet()) {
            BaseColumnInfo columnInfo = columnInfoMap.get(key);
            if (!columnInfo.isCustomField() && !columnInfo.isDynamicColumn()) {
                String supplierEntityName = columnInfo.getSupplierEntityName();
                if (DataType.OBJECTVALUE.equals(columnInfo.getPropDataType()) || !StringUtils.isEmpty(supplierEntityName)) {
                    sic.add(key + ".*");
                } else {
                    sic.add(key);
                }
            }
        }
        sic.add("entry.person.number");
        sic.add("entry.person.name");
        return sic;
    }
}
