package com.hotwj.platform.reportStatistics.provider.driver;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.hotwj.platform.driverManagement.driver.domain.vo.HotDriverVo;
import com.hotwj.platform.driverManagement.driver.service.IHotDriverService;
import com.hotwj.platform.driverManagement.driverAnnualAssessment.domain.bo.HotDriverAnnualAssessmentBo;
import com.hotwj.platform.driverManagement.driverAnnualAssessment.domain.vo.HotDriverAnnualAssessmentVo;
import com.hotwj.platform.driverManagement.driverAnnualAssessment.service.IHotDriverAnnualAssessmentService;
import com.hotwj.platform.reportStatistics.service.IDriverFilePrintService;
import com.hotwj.platform.reportStatistics.service.IReportDataProvider;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.service.OssService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 驾驶员年度考核记录数据提供者
 *
 * @author shihongwei
 */
@Component
@RequiredArgsConstructor
public class AnnualAssessmentRecordProvider implements IReportDataProvider {

    private final IHotDriverService driverService;
    private final IHotDriverAnnualAssessmentService annualAssessmentService;
    private final OssService ossService;

    @Override
    public String getTemplateCode() {
        return "templates/driver/annualAssessmentRecord.html.vm";
    }

    @Override
    public String getReportType() {
        return IDriverFilePrintService.TYPE_ANNUAL_ASSESSMENT_RECORD;
    }

    @Override
    public String getReportTitle() {
        return "驾驶员年度考核记录";
    }

    @Override
    public Map<String, Object> prepareData(Map<String, Object> params) {
        String driverId = MapUtil.getStr(params, "driverId");
        if (StrUtil.isBlank(driverId)) {
            return new HashMap<>();
        }

        HotDriverVo driver = driverService.queryById(driverId);
        if (driver == null) {
            return new HashMap<>();
        }

        Map<String, Object> ctx = new HashMap<>();
        ctx.put("name", driver.getName());
        ctx.put("idCardNo", driver.getIdCardNo());

        HotDriverAnnualAssessmentBo bo = new HotDriverAnnualAssessmentBo();
        bo.setDriverId(driverId);
        bo.setIsDeleted(0L);
        List<HotDriverAnnualAssessmentVo> list = annualAssessmentService.queryList(bo);

        List<Map<String, Object>> categories = new ArrayList<>();
        String result = "";
        String assessTime = "";
        String evaluatorSignatureUrl = "";
        String assessedSignatureUrl = "";
        int totalValue = 0;
        int totalScoreActual = 0;

        if (CollUtil.isNotEmpty(list)) {
            HotDriverAnnualAssessmentVo vo = list.get(0);
            result = vo.getAssessmentResult();
            assessTime = vo.getAssessmentTime() != null ? DateUtil.format(vo.getAssessmentTime(), "yyyy-MM-dd") : "";

            if (vo.getEvaluatorSignatureId() != null) {
                evaluatorSignatureUrl = ossService.selectUrlByIds(String.valueOf(vo.getEvaluatorSignatureId()));
            }
            if (vo.getAssessedSignatureId() != null) {
                assessedSignatureUrl = ossService.selectUrlByIds(String.valueOf(vo.getAssessedSignatureId()));
            }


            // 解析考核内容
            Map<String, Object> root = null;
            try {
                if (StrUtil.isNotBlank(vo.getAssessmentContent())) {
                    root = JSON.parseObject(vo.getAssessmentContent(), Map.class);
                }
            } catch (Exception ignored) {
            }

            Map<String, String> names = new HashMap<>();
            names.put("discipline", "工作纪律");
            names.put("safety", "安全驾驶");
            names.put("service", "服务质量");
            names.put("learn", "培训学习");

            Map<String, List<Map<String, Object>>> grouped = new HashMap<>();
            grouped.put("discipline", new ArrayList<>());
            grouped.put("safety", new ArrayList<>());
            grouped.put("service", new ArrayList<>());
            grouped.put("learn", new ArrayList<>());

            if (root != null) {
                Object idCard = root.get("driverIdCard");
                if (idCard != null) {
                    ctx.put("idCardNo", String.valueOf(idCard));
                }

                // 获取扣分详情
                Object detailsObj = root.get("details");

                if (detailsObj instanceof List<?> dlist) {
                    for (Object o : dlist) {
                        // fastjson2 可能会解析成 JSONObject (Map)
                        if (o instanceof Map) {
                            Map<?, ?> m = (Map<?, ?>) o;
                            String cat = String.valueOf(m.get("category"));
                            String content = String.valueOf(m.get("content"));
                            Number score = m.get("score") instanceof Number ? (Number) m.get("score") : 0;
                            Number deduction = m.get("deduction") instanceof Number ? (Number) m.get("deduction") : 0;

                            Map<String, Object> item = new HashMap<>();
                            item.put("content", content);
                            item.put("score", score.intValue()); // 单项总分
                            item.put("deduction", deduction.intValue()); // 扣分
                            
                            if (grouped.containsKey(cat)) {
                                grouped.get(cat).add(item);
                            }
                        }
                    }
                }
            }

            String[] order = new String[]{"discipline", "safety", "service", "learn"};
            for (String key : order) {
                List<Map<String, Object>> dets = grouped.get(key);

                // 计算当前分类的总分值 (累加该分类下所有题目的分数)
                int categoryTotalScore = 0;
                int categoryTotalDeduction = 0;
                
                if (dets != null) {
                    for (Map<String, Object> it : dets) {
                        int itemScore = (int) it.get("score");
                        int itemDeduction = (int) it.get("deduction");
                        categoryTotalScore += itemScore;
                        categoryTotalDeduction += itemDeduction;
                    }
                }

                // 计算当前分类的实际得分 (总分 - 扣分)
                int actual = Math.max(categoryTotalScore - categoryTotalDeduction, 0);

                // 累加总分
                totalValue += categoryTotalScore;
                totalScoreActual += actual;

                Map<String, Object> cat = new HashMap<>();
                cat.put("name", names.get(key));
                cat.put("value", categoryTotalScore);
                cat.put("score", actual);
                cat.put("details", dets == null ? new ArrayList<>() : dets);
                categories.add(cat);
            }
        }

        ctx.put("result", result);
        ctx.put("assessTime", assessTime);
        ctx.put("evaluatorSignatureUrl", evaluatorSignatureUrl);
        ctx.put("assessedSignatureUrl", assessedSignatureUrl);
        ctx.put("categories", categories);
        ctx.put("totalValue", totalValue);
        ctx.put("totalScore", totalScoreActual);

        return ctx;
    }
}
