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

import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.custom.performancenew.*;
import com.kingdee.eas.custom.performancenew.app.periodTypeEnum;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.json.GridDataEntity;
import com.kingdee.shr.base.syssetting.web.handler.ListHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author qingwu
 * @date 2024/4/24
 * @apiNote 评分人查看累计得分
 */
public class AccumulativeScoreShow extends ListHandler {

    private  Context ctx = SHRContext.getInstance().getContext();

    @Override
    protected FilterInfo getDefaultFilter(HttpServletRequest request, HttpServletResponse response) throws SHRWebException {
        //当前登录员工id
        String currentPersonId = ContextUtil.getCurrentUserInfo(ctx).getPerson().getId().toString();
        FilterInfo customFilter = null;
        String custom_params = request.getParameter("custom_params");
        if (!StringUtils.isEmpty(custom_params)) {
            customFilter = new FilterInfo();
            Map customParams = JSONUtils.convertJsonToObject(custom_params);
            String examineGradePersonId = (String) customParams.get("billId");
            customFilter.getFilterItems().add(new FilterItemInfo("parent.id", examineGradePersonId));
            customFilter.getFilterItems().add(new FilterItemInfo("scorer.id", currentPersonId));
        }
        return customFilter;
    }

    /**
     * 查看累计得分
     *
     * @param request
     * @param response
     * @param gridDataEntity
     * @throws SHRWebException
     */
    @Override
    protected void afterGetListData(HttpServletRequest request, HttpServletResponse response, GridDataEntity gridDataEntity) throws SHRWebException {
        String custom_params = request.getParameter("custom_params");
        Map customParams = JSONUtils.convertJsonToObject(custom_params);
        String billId = (String) customParams.get("billId");
        List rowData = gridDataEntity.getRows();
        Map<String, Object> userData = (Map) request.getAttribute("_userData_");

        Set set = new HashSet<>();
        //去重操作
        for (int i = rowData.size() - 1; i >= 0; i--) {
            Map Map = (Map) rowData.get(i);
            String adminId = Map.get("adminOrg.number").toString();
            if (set.contains(adminId)) {
                rowData.remove(Map);
            } else {
                set.add(adminId);
            }
        }
        if (userData != null) {
            int rows = (Integer) userData.get("rows");
            int page = (Integer) userData.get("page");
            gridDataEntity.setRecords(rowData.size());
            gridDataEntity.setTotal(rowData.size() % rows == 0 ? rowData.size() : rowData.size() + 1);
        }
        try {
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            for (int i = 0; i < rowData.size(); i++) {
                Map<String, Object> dataMap = (Map<String, Object>) rowData.get(i);
                FilterInfo filterInfo = new FilterInfo();
                filterInfo.getFilterItems().add(new FilterItemInfo("id", dataMap.get("id").toString(), CompareType.EQUALS));
                SelectorItemCollection sic = new SelectorItemCollection();
                sic.add("*");
                sic.add("parent.*");
                EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
                ExamineGradePersonEntryCollection examineGradePersonEntryCollection = iExamineGradePersonEntry.getExamineGradePersonEntryCollection(entityViewInfo);
                //ExamineGradePersonEntryInfo examineGradePersonEntryInfo = iExamineGradePersonEntry.getExamineGradePersonEntryInfo(new ObjectUuidPK(dataMap.get("id").toString()));
                if (examineGradePersonEntryCollection.size() > 0) {
                    ExamineGradePersonEntryInfo examineGradePersonEntryInfo = examineGradePersonEntryCollection.get(0);
                    ExamineGradePersonInfo parent = examineGradePersonEntryInfo.getParent();
                    if (parent.getPeriodType().equals(periodTypeEnum.year)) {
                        String afterScoreNumMap = examineGradePersonEntryInfo.getAfterScoreNumMap();
                        Map gradeAMap = null;
                        if (StringUtils.isEmpty(afterScoreNumMap)) {
                            gradeAMap = new HashMap();
                        } else {
                            gradeAMap = mapStringToMap(afterScoreNumMap);

                        }

                        if (gradeAMap != null) {
                            dataMap.put("A", (int) Double.parseDouble(gradeAMap.get("A") == null ? "0" : gradeAMap.get("A").toString()));
                            dataMap.put("B+", (int) Double.parseDouble(gradeAMap.get("B+") == null ? "0" : gradeAMap.get("B+").toString()));
                            dataMap.put("B-", (int) Double.parseDouble(gradeAMap.get("B-") == null ? "0" : gradeAMap.get("B-").toString()));
                            dataMap.put("C", (int) Double.parseDouble(gradeAMap.get("C") == null ? "0" : gradeAMap.get("C").toString()));
                            dataMap.put("D", (int) Double.parseDouble(gradeAMap.get("D") == null ? "0" : gradeAMap.get("D").toString()));
                            dataMap.put("B", (int) Double.parseDouble(gradeAMap.get("B") == null ? "0" : gradeAMap.get("B").toString()));
                        }

                    } else {
                        //判断当前是第几个季度，获取该年度的前面的所有季度
                        //if (parent.getQuarter() != 1) {
                        int a = 0;
                        int bPlus = 0;
                        int b = 0;
                        int bMinus = 0;
                        int c = 0;
                        int d = 0;
                        for (int j = parent.getQuarter(); j > 0; j--) {
                            SelectorItemCollection sicQuarter = new SelectorItemCollection();
                            sicQuarter.add("*");
                            sicQuarter.add("parent.*");
                            sicQuarter.add("adminOrg.*");
                            FilterInfo filterInfoQuarter = new FilterInfo();
                            FilterItemCollection filterItems = filterInfoQuarter.getFilterItems();
                            filterItems.add(new FilterItemInfo("parent.periodType", parent.getPeriodType(), CompareType.EQUALS));
                            filterItems.add(new FilterItemInfo("parent.year", parent.getYear()));
                            filterItems.add(new FilterItemInfo("adminOrg.id", examineGradePersonEntryInfo.getAdminOrg().getId()));
                            filterItems.add(new FilterItemInfo("parent.quarter", j));

                            EntityViewInfo entityViewInfoNew = EntityViewInfo.getInstance(filterInfoQuarter, sicQuarter, null);

                            ExamineGradePersonEntryCollection examineGradePersonEntryCollectionNew = iExamineGradePersonEntry.getExamineGradePersonEntryCollection(entityViewInfoNew);

                            if (examineGradePersonEntryCollectionNew.size() > 0) {

                                ExamineGradePersonEntryInfo examineGradePersonEntryInfoNew = examineGradePersonEntryCollectionNew.get(0);
                                ExamineGradePersonInfo parentNew = examineGradePersonEntryInfoNew.getParent();
                                String afterScoreNumMap = examineGradePersonEntryInfoNew.getAfterScoreNumMap();
                                if (!StringUtils.isEmpty(afterScoreNumMap)) {
                                    JSONObject jsonObject = mapStringToJsonObject(afterScoreNumMap);
                                    a += jsonObject.getInteger("A") == null ? 0 : jsonObject.getInteger("A");
                                    bPlus += jsonObject.getInteger("B+") == null ? 0 : jsonObject.getInteger("B+");
                                    b += jsonObject.getInteger("B") == null ? 0 : jsonObject.getInteger("B");
                                    bMinus += jsonObject.getInteger("B-") == null ? 0 : jsonObject.getInteger("B-");
                                    c += jsonObject.getInteger("C") == null ? 0 : jsonObject.getInteger("C");
                                    d += jsonObject.getInteger("D") == null ? 0 : jsonObject.getInteger("D");
                                }
                            }
                        }
                        dataMap.put("A", a);
                        dataMap.put("B+", bPlus);
                        dataMap.put("B-", bMinus);
                        dataMap.put("C", c);
                        dataMap.put("D", d);
                        dataMap.put("B", b);
                    }
                    //}

                }
            }
        } catch (BOSException e) {
            throw new RuntimeException(e);
        }
        super.afterGetListData(request, response, gridDataEntity);
    }


    /**
     * 将Map字符串转换为Map
     *
     * @param str Map字符串
     * @return Map
     */
    public static Map<String, String> mapStringToMap(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map<String, String> map = new HashMap<String, String>();
        for (String string : strs) {
            String key = string.split("=")[0];
            String value = string.split("=")[1];
            // 去掉头部空格
            String key1 = key.trim();
            String value1 = value.trim();
            map.put(key1, value1);
        }
        return map;
    }

    /**
     * 将Map字符串转换为mapStringToJsonObject
     *
     * @param str Map字符串
     * @return Map
     */
    public static JSONObject mapStringToJsonObject(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        JSONObject jsonObject = new JSONObject();
        for (String string : strs) {
            String key = string.split("=")[0];
            String value = string.split("=")[1];
            // 去掉头部空格
            String key1 = key.trim();
            String value1 = value.trim();
            jsonObject.put(key1, value1);
        }
        return jsonObject;
    }
}
