package com.scpyun.platform.jilinsscgsdp.service.impl;

import cn.hutool.core.util.IdUtil;
import com.google.common.collect.Maps;
import com.scpyun.base.bean.Page;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.core.exception.CustomException;
import com.scpyun.base.core.utils.StringUtils;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.bean.entity.KeyPersonRatingHistory;
import com.scpyun.platform.jilinsscgsdp.enums.ScoreCategoryEnum;
import com.scpyun.platform.jilinsscgsdp.utils.DataScopeUtil;
import com.scpyun.platform.jilinsscgsdp.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

import static jdk.nashorn.internal.runtime.JSType.toInteger;

/**
 * @Author liu
 * @Date 2025/9/25 16:50
 * @PackageName:com.scpyun.platform.jilinsscgsdp.service.impl
 * @ClassName: KeyPersonRating
 * @Description: TODO
 * @Version 1.0
 */
@Api("重度人员评分")
@Service("keyPersonRating")
public class KeyPersonRatingServiceImpl {
    @Autowired
    CommonService commonService;

    private final String SUCCESS = "success";

    private String namespace = "com.scpyun.platform.standard.jilinsscgsdp.keyPersonRating.";
    private String ratingHistoryNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.keyPersonRatingHistory.";
    private String ratingDictDayNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.keyPersonRatingDictDay.";
    private String ratingLevelNamespace = "com.scpyun.platform.standard.jilinsscgsdp.keyPersonRatingLevel.";
    @ApiOperation(value = "查询重点人员类别", desc = "查询重点人员类别")
    public Page<Map<String, Object>> selectRatingDictTypeList(Page<Map<String, Object>> page) {
        return commonService.findPage(namespace + "selectRatingDictTypeList", page);
    }

    @ApiOperation(value = "查询重点人员类别评分项", desc = "查询重点人员类别评分项")
    public List<Map<String, Object>> selectRatingDictList(Map<String, Object> map) {
        return commonService.findList(namespace + "selectRatingDictList", map);
    }

    @ApiOperation(value = "查询人员详情")
    public Map<String, Object> getKeyPersonUser(Map<String, Object> map) {
        Map<String, Object> newMap = new HashMap<>();
        //由于表不同
        if (map.get("ratingDictType").equals("6")) {
            //重点未成年人表
            newMap = commonService.getObject(namespace + "getPersonMinor", map);
        } else {
            //其他事另外的表
            newMap = commonService.getObject(namespace + "getKeyPersonUser", map);
        }
        return newMap;
    }

    @ApiOperation(value = "添加修改评分项", desc = "添加修改评分项")
    public String saveRatingDict(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("evaluate_type"))) {
            throw new CustomException("评估类别不可为空");
        }
        if (StringUtils.isEmpty(map.get("scoring_project"))) {
            throw new CustomException("赋分项目不可为空");
        }
        if (StringUtils.isEmpty(map.get("rating_description"))) {
            throw new CustomException("分值描述不可为空");
        }
        if (StringUtils.isEmpty(map.get("id"))) {
            if (commonService.insert(namespace + "insertRatingDict", map) != 1) {
                throw new CustomException("添加失败");
            }
        } else {
            if (commonService.update(namespace + "updateRatingDict", map) != 1) {
                throw new CustomException("修改失败");
            }
        }
        return SUCCESS;
    }

    @ApiOperation(value = "删除评分项", desc = "删除评分项")
    public String deleteRatingDict(Map<String, Object> map) {
        if (commonService.insert(namespace + "deleteRatingDict", map) < 1) {
            throw new CustomException("删除失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "查询打分列表", desc = "查询打分列表")
    public List<Map<String, Object>> selectRatingDetailsList(Map<String, Object> map) {
        Map<String, Object> details = commonService.getObject(namespace + "selectRatingDetailsList", map);
        if (details == null) {
            return commonService.findList(namespace + "selectRatingDictList", map);
        } else {
            return commonService.findList(namespace + "selectRatingDetailsByPersonIdList", map);
        }
    }

    @ApiOperation(value = "添加分数", desc = "添加分数")
    public String saveRatingDetails(Map<String, Object> map) {
        String historyId = IdUtil.simpleUUID();
        String summaryId = IdUtil.simpleUUID();

        if (map.get("historyId") == null) {
            //首次评分
            //添加历史表是多次历史记录表，以及评分记录表
            Map<String, Object> ratingHistoryMap = new HashMap<>();
            ratingHistoryMap.put("id", historyId);
            ratingHistoryMap.put("key_person_id",map.get("id"));
            ratingHistoryMap.put("rating_dict_type",map.get("ratingDictType"));

            Map<String, Object> ratingDictDayMap = new HashMap<>();
            ratingDictDayMap.put("rating_dict_type",map.get("ratingDictType"));
            List<Map<String, Object>> dayResultMapList = commonService.findList(ratingDictDayNameSpace + "selectRatingDictDayList", ratingDictDayMap);
            if (dayResultMapList != null && dayResultMapList.size() > 0) {
                Map<String, Object> dayResultMap = dayResultMapList.get(0);
                Integer startDay = Integer.valueOf(dayResultMap.get("rating_start_day").toString());
                Integer overDay = Integer.valueOf(dayResultMap.get("rating_over_day").toString());
                Integer endDay = Integer.valueOf(dayResultMap.get("rating_end_day").toString());
                // 1. 计算 LocalDate（例如 startDay=0 的日期）
                // 第一次首次评论的开始日期 应该是当前日期，定时任务才根据开始的日期计算
                LocalDate startLocalDate = LocalDate.now().plusDays(0);
                Date utilStartDate = Date.from(startLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

                LocalDate overLocalDate = LocalDate.now().plusDays(endDay - overDay);
                Date utilOverDate = Date.from(overLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

                LocalDate endLocalDate = LocalDate.now().plusDays(endDay);
                Date utilEndDate = Date.from(endLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

                ratingHistoryMap.put("plan_start_data", utilStartDate);
                ratingHistoryMap.put("overdue_date", utilOverDate);
                ratingHistoryMap.put("plan_end_data", utilEndDate);

                ratingHistoryMap.put("is_history", "1");
                ratingHistoryMap.put("do_status", "1");
                ratingHistoryMap.put("is_overdue", "0");
                ratingHistoryMap.put("_user", map.get("_user"));
                if (commonService.insert(ratingHistoryNameSpace + "insertPersonRatingHistory", ratingHistoryMap) != 1) {
                    throw new CustomException("添加失败");
                }
            } else {
                throw new CustomException("请配置循环评分日期");
            }
        } else {
            historyId = map.get("historyId").toString();

            //可能存在超期评分，未超期评分，状态为1，超期评分后，状态为3；根据当前时间和计划结束时间进行对比
            String do_status = "1";
            Map<String, Object> _map = new HashMap<>();
            _map.put("id", historyId);
            Map<String, Object> historyObj = commonService.getObject(namespace + "selectRatingHistoryById", _map);
            do_status = historyObj.get("do_status").toString();
            Date endData = (Date)historyObj.get("plan_end_data");
            if("2".equals(historyObj.get("do_status")) && new Date().compareTo(endData) > 0) {
                do_status = "3";
            }

            //需要更新，jl_key_person_rating_summary表数据
            Map<String, Object> updateSummaryMap = new HashMap<>();
            updateSummaryMap.put("rating_dict_type", map.get("ratingDictType"));
            updateSummaryMap.put("rating_history_id", historyId);
            updateSummaryMap.put("key_person_id", map.get("id"));
            updateSummaryMap.put("_user", map.get("_user"));
            commonService.update(namespace + "updateIsNew", updateSummaryMap);

            Map<String, Object> updateHistoryMap = new HashMap<>();
            updateHistoryMap.put("rating_dict_type", map.get("ratingDictType"));
            updateHistoryMap.put("key_person_id", map.get("id"));
            updateHistoryMap.put("_user", map.get("_user"));
            updateHistoryMap.put("id", historyId);
            updateHistoryMap.put("do_status", do_status);
            commonService.update(namespace + "updateHistory", updateHistoryMap);

        }

        List<Map<String, Object>> ratingDetailsList = (List<Map<String, Object>>) map.get("ratingDetailsList");
        BigDecimal ratingAll = new BigDecimal(0);

        for (Map<String, Object> sub : ratingDetailsList) {
            String detailId = IdUtil.simpleUUID();
            if (StringUtils.isEmpty(sub.get("is_whether"))) {
                throw new CustomException("选择项不可为空");
            }
            sub.put("_user", map.get("_user"));
            sub.put("id", detailId);
            sub.put("key_person_id", map.get("id"));
            if ("2".equals(StringUtils.toStr(sub.get("is_whether")))) {
                sub.put("details", 0);
            }
            sub.put("rating_description", sub.get("rating_description"));
            sub.put("rating_dict_type", map.get("ratingDictType"));
            sub.put("rating_history_id", historyId);
            sub.put("key_person_rating_summary_id",summaryId);
            sub.put("sort",sub.get("sort"));
            sub.put("remarks",sub.get("remarks"));
            if (commonService.insert(namespace + "insertRatingDetails", sub) != 1) {
                throw new CustomException("添加失败");
            }
            BigDecimal rating = new BigDecimal(StringUtils.toLong(sub.get("details")));
            ratingAll = ratingAll.add(rating);
        }

        Map<String, Object> summaryMap = new HashMap<>();
        summaryMap.put("id", summaryId);
        summaryMap.put("rating_dict_type", map.get("ratingDictType"));
        summaryMap.put("rating_history_id", historyId);
        summaryMap.put("key_person_id", map.get("id"));
        summaryMap.put("rating", ratingAll);
        String rat = ratingAll.toString();
        //老数据是写死的
//        summaryMap.put("rating_type", ScoreCategoryEnum.ScoreCategory.fromScore(StringUtils.toInteger(rat)));
        //现在改成从接口获取
        Map<String, Object> levelMap = new HashMap<>();
        levelMap.put("rating_dict_type", map.get("ratingDictType"));
        List<Map<String, Object>> resuleMap = commonService.findList(ratingLevelNamespace + "selectRatingLevelList", levelMap);
        for (Map<String, Object> resule : resuleMap) {
            Integer ratInt = StringUtils.toInteger(rat);
            Integer startInt = StringUtils.toInteger(resule.get("rating_start_score"));
            Integer endInt = StringUtils.toInteger(resule.get("rating_end_score"));
            // 判断ratInt是否在 [startInt, endInt) 范围内
            if (ratInt >= startInt && ratInt < endInt) {
                // 找到匹配的范围，赋值rating_type
                summaryMap.put("rating_type", resule.get("rating_level_value"));
                // 如果只需匹配第一个符合条件的范围，可直接退出循环
                break;
            }
        }

        summaryMap.put("is_history", 1);//最新数据
        summaryMap.put("_user", map.get("_user"));

        summaryMap.put("rating_users", map.get("ratingUsers"));

        summaryMap.put("rating_custom_time", map.get("ratingTime").toString().replace("T", " ").substring(0,19));
        summaryMap.put("rating_img", map.get("ratingImg").toString());
//        try {
//            summaryMap.put("rating_custom_time", DateUtil.parseTime(map.get("ratingTime").toString().replace("T", " ").substring(0,19)));
//        } catch (ParseException e) {
//            summaryMap.put("rating_custom_time", DateUtil.getCurrentTime());
//        }

        if (commonService.insert(namespace + "insertPersonRatingSummary", summaryMap) != 1) {
            throw new CustomException("添加失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "查询评分详情", desc = "查询评分详情")
    public Page<Map<String, Object>> selectRatingSummaryByPersonIdList(Page<Map<String, Object>> page) {
        Page<Map<String, Object>> summaryList = commonService.findPage(namespace + "selectRatingSummaryByPersonIdList", page);
        return summaryList;
    }

    @ApiOperation(value = "查询历史详情", desc = "查询历史详情")
    public List<Map<String, Object>> selectSummaryRatingDetailsList(Map<String, Object> map) {
        return commonService.findList(namespace + "selectSummaryRatingDetailsList", map);
    }

    @ApiOperation(value = "查询重点未成年人", desc = "查询重点未成年人")
    public Page<Map<String, Object>> findKeyPersonMinorList(Page<Map<String, Object>> page) {
        return commonService.findPage(namespace + "findKeyPersonMinorList", page);
    }

    @ApiOperation(value = "新增重点未成年人", desc = "新增")
    public String insertKeyPersonMinor(Map<String, Object> map) {
        if (commonService.insert(namespace + "insertKeyPersonMinor", map) != 1) {
            throw new CustomException("删除失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "修改重点未成年人", desc = "修改重点未成年人")
    public String updateKeyPersonMinor(Map<String, Object> map) {
        if (commonService.update(namespace + "updateKeyPersonMinor", map) != 1) {
            throw new CustomException("删除失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "删除重点未成年人", desc = "删除重点未成年人")
    public String deleteKeyPersonMinor(Map<String, Object> map) {
        if (commonService.delete(namespace + "deleteKeyPersonMinor", map) != 1) {
            throw new CustomException("删除失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "获取评分按钮权限", desc = "返回页面按钮权限映射")
    public Map getVisitButtonPower(Map<String, Object> map) {
        Object _user = map == null ? null : map.get("_user");
        if (_user == null) {
            return new java.util.HashMap<>();
        }
        return DataScopeUtil.getButtonPower(_user);
    }
}
