package nckd.jxccl.sit.hcsi.business.importtaskguide.utils;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.EntityType;
import kd.bos.orm.query.QFilter;
import kd.bos.util.StringUtils;
import kd.hr.hbp.business.bgtask.HRBackgroundTaskHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.common.cache.IHRAppCache;
import kd.hr.hbp.common.cache.HRAppCache;
import nckd.jxccl.sit.hcsi.formplugin.web.tp.enums.SinsurPresetItemEnum;

import java.util.*;

public class ImportTaskUtils {

    private static final String SINSURTPL_ENTITY = "nckd_sinsurtpl";
    private static final String INSURANCEITEM_ENTITY = "sitbs_insuranceitem";


    public static DynamicObject getSinsurTplData(Long sinsurTplId, String fields, QFilter qFilter) {
        HRBaseServiceHelper helper = new HRBaseServiceHelper(SINSURTPL_ENTITY);
        QFilter filter = new QFilter("id", "=", sinsurTplId);
        if (qFilter != null) {
            filter.and(qFilter);
        }
        return helper.queryOne(fields, new QFilter[]{filter});
    }

    private static DynamicObjectCollection getSinsurTplDataList(Long sinsurTplId) {
        HRBaseServiceHelper helper = new HRBaseServiceHelper(SINSURTPL_ENTITY);
        String fields = "nckd_sinsurtplentry.nckd_itemtype,nckd_sinsurtplentry.nckd_itemid,nckd_sinsurtplentry.nckd_matchcolumn,nckd_sinsurtplentry.nckd_comment";
        QFilter qFilter = new QFilter("id", "=", sinsurTplId);
        return helper.queryOriginalCollection(fields, new QFilter[]{qFilter}, "nckd_sinsurtplentry.seq asc");
    }

    public static List<Map<String, String>> getColumnHeadList(Long sinsurTplId, Long importTaskId) {
        List<Map<String, String>> columnHeadList = new ArrayList(10);
        if (sinsurTplId != null && sinsurTplId != 0L && importTaskId != null && importTaskId != 0L) {
            String cacheKey = importTaskId + "_" + sinsurTplId;
            IHRAppCache appCache = HRAppCache.get(cacheKey);
            String json = (String)appCache.get("columnHeadList", String.class);
            if (StringUtils.isNotEmpty(json)) {
                columnHeadList = (List) SerializationUtils.fromJsonString(json, List.class);
                return columnHeadList;
            }
        }
        DynamicObjectCollection list = getSinsurTplDataList(sinsurTplId);
        if (list.size() == 0) {
            return columnHeadList;
        } else {
            List<String> itemList = new ArrayList(10);
            Map<String, Map<String, String>> itemMap = new HashMap(list.size());
            Set<Long> fixSet = new HashSet(16);
            Set<Long> iiItemSet = new HashSet(16);
            Map<String, Integer> indexMap = new HashMap(16);
            String keyStr = "";
            Map<String, String> commentMap = new HashMap(list.size());
            String comment = null;
            Iterator columnIndex;
            DynamicObject obj;
            for(columnIndex = list.iterator(); columnIndex.hasNext(); commentMap.put(keyStr, comment)) {
                obj = (DynamicObject)columnIndex.next();
                String itemType = obj.getString("nckd_sinsurtplentry.nckd_itemtype");
                Long itemId = obj.getLong("nckd_sinsurtplentry.nckd_itemid");
                comment = obj.getString("nckd_sinsurtplentry.nckd_comment");
                if ("0".equals(itemType)) {
                    keyStr = "fix" + itemId;
                    itemList.add(keyStr);
                    indexMap.put(keyStr, getExcelRowIndexByTitle(obj.getString("nckd_sinsurtplentry.nckd_matchcolumn")));
                    fixSet.add(itemId);
                }
                else if ("1".equals(itemType)) {
                    keyStr = "ii" + itemId;
                    itemList.add(keyStr);
                    indexMap.put(keyStr, getExcelRowIndexByTitle(obj.getString("nckd_sinsurtplentry.nckd_matchcolumn")));
                    iiItemSet.add(itemId);
                }
            }
            addFixValue(commentMap, fixSet, "fix", itemMap, "0");
            addItemValue(commentMap, iiItemSet, "ii", itemMap, INSURANCEITEM_ENTITY, "1");
            if (itemMap.size() == 0) {
                return columnHeadList;
            } else {
                columnIndex = null;
                obj = null;
                Iterator it = itemList.iterator();
                while(it.hasNext()) {
                    String key = (String)it.next();
                    Map<String, String> tempMap = (Map)itemMap.get(key);
                    if (tempMap != null) {
                        Integer index = (Integer)indexMap.get(key);
                        tempMap.put("columnIndex", String.valueOf(index));
                        columnHeadList.add(tempMap);
                    }
                }
                if (sinsurTplId != null && sinsurTplId != 0L && importTaskId != null && importTaskId != 0L) {
                    String cacheKey = importTaskId + "_" + sinsurTplId;
                    IHRAppCache appCache = HRAppCache.get(cacheKey);
                    appCache.put("columnHeadList", SerializationUtils.toJsonString(columnHeadList));
                }
                return columnHeadList;
            }
        }
    }

    /**
     * 处理预置项目
     * @param commentMap
     * @param itemSet
     * @param itemKey
     * @param itemMap
     * @param itemType
     */
    private static void addFixValue(Map<String, String> commentMap, Set<Long> itemSet, String itemKey, Map<String, Map<String, String>> itemMap, String itemType) {
        if (itemSet.size() != 0) {
            Map<Long, SinsurPresetItemEnum> map = SinsurPresetItemEnum.getSinsurPresetItemEnumMap();
            SinsurPresetItemEnum itemEnum = null;
            Map<String, String> tempMap = null;
            Iterator it = itemSet.iterator();
            while(it.hasNext()) {
                Long itemId = (Long)it.next();
                itemEnum = (SinsurPresetItemEnum)map.get(itemId);
                tempMap = new HashMap(16);
                tempMap.put("name", itemEnum.getItemName());
                tempMap.put("datatypeid", String.valueOf(itemEnum.getDataTypeId()));
                tempMap.put("id", String.valueOf(itemId));
                tempMap.put("key", getFixColumnKeyByItemId(itemId.toString()));
                tempMap.put("itemType", itemType);
                tempMap.put("comment", commentMap.get(itemKey + itemId));
                itemMap.put(itemKey + itemId, tempMap);
            }
        }
    }

    private static String getFixColumnKeyByItemId(String itemId) {
        String columnKey = null;
        switch (itemId) {
            case "1":
                columnKey = "nckd_idcard";
                break;
            case "2":
                columnKey = "nckd_empname";
                break;
        }

        return columnKey;
    }

    private static void addItemValue(Map<String, String> commentMap, Set<Long> itemSet, String itemKey, Map<String, Map<String, String>> itemMap, String entityId, String itemType) {
        if (itemSet.size() != 0) {
            HRBaseServiceHelper helper = new HRBaseServiceHelper(entityId);
            String fields = "id,datatype.id,name";
            DynamicObjectCollection result = helper.queryOriginalCollection(fields, new QFilter[]{new QFilter("id", "in", itemSet)});
            Map<String, String> tempMap = null;
            Iterator var11 = result.iterator();

            while(var11.hasNext()) {
                DynamicObject obj = (DynamicObject)var11.next();
                tempMap = new HashMap(16);
                String keyStr = itemKey + obj.getLong("id");
                tempMap.put("name", obj.getString("name"));
                tempMap.put("datatypeid", String.valueOf(obj.getLong("datatype.id")));
                tempMap.put("id", String.valueOf(obj.getLong("id")));
                tempMap.put("key", keyStr);
                tempMap.put("itemType", itemType);
                tempMap.put("comment", commentMap.get(keyStr));
                itemMap.put(keyStr, tempMap);
            }

        }
    }


    public static int getExcelRowIndexByTitle(String columnTitle) {
        int length = columnTitle.length();
        int num = 0;
        for(int i = 0; i < length; ++i) {
            num = num * 26 + columnTitle.charAt(i) - 65 + 1;
        }
        return num - 1;
    }

    /**
     * 处理预置字段
     *
     * @param commonColumnIndexMap
     * @param temporary
     * @param rowMap
     * @param periodNumber
     */
    public static void setTemporaryValueForCommon(Map<Integer, List<Map<String, String>>> commonColumnIndexMap, DynamicObject temporary, Map<Integer, Object> rowMap, String periodNumber) {
        for (Map.Entry<Integer, List<Map<String, String>>> entry : commonColumnIndexMap.entrySet()) {
            Object itemValue = rowMap.get(entry.getKey());
            if (itemValue == null) {
                continue;
            }
            for (Map<String, String> itemMap : entry.getValue()) {
                temporary.set(itemMap.get("key").toString(), itemValue);
            }
        }

        temporary.set("nckd_periodname", periodNumber);

    }

    public static DynamicObjectCollection getItemEntryList(Map<Integer, Object> rowMap, Map<Integer, List<Map<String, String>>> columnIndexMap, EntityType entryType) {
        DynamicObjectCollection itemEntryList = new DynamicObjectCollection();
        int sequence = 0;
        for (Map.Entry<Integer, List<Map<String, String>>> entry : columnIndexMap.entrySet()) {
            Object itemValue = rowMap.get(entry.getKey());
            if (itemValue == null) {
                continue;
            }
            for (Map<String, String> itemMap : entry.getValue()) {
                try {
                    DynamicObject item = (DynamicObject) entryType.createInstance();

                    item.set("nckd_itemvalue", itemValue);
                    item.set("nckd_itemtype", itemMap.get("itemType"));
                    item.set("nckd_itemname", itemMap.get("name"));
                    item.set("seq", sequence);

                    String id = itemMap.get("id");
                    if (id != null) {
                        item.set("nckd_itemid", Long.valueOf(id));
                    }

                    String datatypeId = itemMap.get("datatypeid");
                    if (datatypeId != null) {
                        item.set("nckd_datatype", Long.valueOf(datatypeId));
                    }
                    sequence++;
                    itemEntryList.add(item);
                } catch (Exception e) {
                    // 记录错误日志，但继续处理其他条目
                    System.err.println("Error processing item: " + e.getMessage());
                }
            }
        }
        return itemEntryList;
    }

    public static Set<Integer> getExportTplRequireColumnSet() {
        Set<Integer> requireFixColumnSet = new HashSet(16);
        requireFixColumnSet.add(0);
        requireFixColumnSet.add(1);
        requireFixColumnSet.add(2);
        requireFixColumnSet.add(3);
        return requireFixColumnSet;
    }

    public static void updateImportTaskStatus(Long importTaskId) {
        HRBaseServiceHelper temporaryHelper = new HRBaseServiceHelper("nckd_sinsurtempdata");
        QFilter filter = new QFilter("nckd_importtask", "=", importTaskId);
        int count = temporaryHelper.count(temporaryHelper.getEntityName(), new QFilter[]{filter});
        if (count == 0) {
            updateImportTaskByDelete(importTaskId, "0", count);
        } else {
            QFilter statusFilter = new QFilter("nckd_datastatus", "=", "5");
            int writedCount = temporaryHelper.count(temporaryHelper.getEntityName(), new QFilter[]{filter, statusFilter});
            if (count == writedCount) {
                updateImportTaskByDelete(importTaskId, "2", count);
            } else {
                updateImportTaskByDelete(importTaskId, (String)null, count);
            }
        }
    }

    private static void updateImportTaskByDelete(Long importTaskId, String taskStatus, int count) {
        HRBaseServiceHelper taskHelper = new HRBaseServiceHelper("nckd_sinsurimptask");
        DynamicObject task = taskHelper.queryOne(importTaskId);
        if (taskStatus != null) {
            task.set("nckd_taskstatus", taskStatus);
        }

        task.set("nckd_count", count);
        task.set("modifytime", new Date());
        task.set("modifier", RequestContext.get().getCurrUserId());
        taskHelper.updateOne(task);
    }


    public static synchronized void updateImportDataProgress(int successCount, int failCount, String cacheKey, String fileUrl) {
        IHRAppCache appCache = HRAppCache.get(String.format(Locale.ROOT, "import_cache_%s", cacheKey));
        Integer existSuccCount = (Integer)appCache.get("successCount", Integer.class);
        Integer existFailCount = (Integer)appCache.get("failCount", Integer.class);
        if (existSuccCount == null) {
            existSuccCount = 0;
        }

        if (existFailCount == null) {
            existFailCount = 0;
        }

        existSuccCount = existSuccCount + successCount;
        existFailCount = existFailCount + failCount;
        appCache.put("successCount", existSuccCount);
        appCache.put("failCount", existFailCount);
        if (fileUrl != null) {
            appCache.put("fileUrl", fileUrl);
        }

        Integer sumCount = existSuccCount + existFailCount;
        IHRAppCache bgAppCache = HRAppCache.get(String.format(Locale.ROOT, "bggroud_taskid_%s", cacheKey));
        String bgTaskId = (String)bgAppCache.get("bgTaskId", String.class);
        if (StringUtils.isNotEmpty(bgTaskId)) {
            Integer totalCount = bgAppCache.get("totalCount", Integer.class) == null ? 0 : (Integer)bgAppCache.get("totalCount", Integer.class);
            if (totalCount == 0) {
                return;
            }

            int progress;
            if (sumCount.equals(totalCount)) {
                progress = 100;
            } else {
                progress = sumCount * 100 / totalCount;
                if (progress == 100) {
                    progress = 99;
                }
            }

            HRBackgroundTaskHelper.getInstance().feedbackProgress(bgTaskId, progress, "", (Map)null);
        }

    }


    public static String join(Set<String> set, String str) {
        if (null != set && set.size() != 0) {
            StringBuilder result = new StringBuilder();
            Iterator var3 = set.iterator();

            while(var3.hasNext()) {
                String temp = (String)var3.next();
                result.append(temp).append(str);
            }

            return result.substring(0, result.length() - 1);
        } else {
            return "";
        }
    }

    public static <T> List<List<T>> split(List<T> resList, int count) {
        List<List<T>> ret = new ArrayList(10);
        if (resList != null && !resList.isEmpty() && count >= 1) {
            int size = resList.size();
            if (size <= count) {
                ret.add(resList);
            } else {
                int pre = size / count;
                int last = size % count;
                List<T> itemList = null;

                int i;
                for(i = 0; i < pre; ++i) {
                    itemList = new ArrayList(count);

                    for(int j = 0; j < count; ++j) {
                        itemList.add(resList.get(i * count + j));
                    }

                    ret.add(itemList);
                }

                if (last > 0) {
                    itemList = new ArrayList(count);

                    for(i = 0; i < last; ++i) {
                        itemList.add(resList.get(pre * count + i));
                    }

                    ret.add(itemList);
                }
            }

            return ret;
        } else {
            return ret;
        }
    }

}
