package com.ruoyi.kaohe.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.kaohe.domain.*;
import com.ruoyi.kaohe.mapper.KhVoteEmpMapper;
import com.ruoyi.kaohe.mapper.KhVoteMapper;
import com.ruoyi.kaohe.util.PinYinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.kaohe.mapper.KhKhrwResultMapper;
import com.ruoyi.kaohe.service.IKhKhrwResultService;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 考核结果Service业务层处理
 * 
 * @author hs
 * @date 2025-07-05
 */
@Service
public class KhKhrwResultServiceImpl implements IKhKhrwResultService 
{
    @Autowired
    private KhKhrwResultMapper khKhrwResultMapper;
    @Autowired
    private KhVoteMapper khVoteMapper;
    @Autowired
    private KhVoteEmpMapper khVoteEmpMapper;

    /**
     * 查询考核结果
     * 
     * @param id 考核结果主键
     * @return 考核结果
     */
    @Override
    public KhKhrwResult selectKhKhrwResultById(Long id)
    {
        return khKhrwResultMapper.selectKhKhrwResultById(id);
    }

    /**
     * 查询考核结果列表
     * 
     * @param khKhrwResult 考核结果
     * @return 考核结果
     */
    @Override
    public List<KhKhrwResult> selectKhKhrwResultList(KhKhrwResult khKhrwResult)
    {
        return khKhrwResultMapper.selectKhKhrwResultList(khKhrwResult);
    }

    /**
     * 新增考核结果
     * 
     * @param khKhrwResult 考核结果
     * @return 结果
     */
    @Override
    public int insertKhKhrwResult(KhKhrwResult khKhrwResult)
    {
        khKhrwResult.setCreateTime(DateUtils.getNowDate());
        return khKhrwResultMapper.insertKhKhrwResult(khKhrwResult);
    }

    /**
     * 修改考核结果
     * 
     * @param khKhrwResult 考核结果
     * @return 结果
     */
    @Override
    public int updateKhKhrwResult(KhKhrwResult khKhrwResult)
    {
        khKhrwResult.setUpdateTime(DateUtils.getNowDate());
        return khKhrwResultMapper.updateKhKhrwResult(khKhrwResult);
    }

    /**
     * 批量删除考核结果
     * 
     * @param ids 需要删除的考核结果主键
     * @return 结果
     */
    @Override
    public int deleteKhKhrwResultByIds(Long[] ids)
    {
        return khKhrwResultMapper.deleteKhKhrwResultByIds(ids);
    }

    /**
     * 删除考核结果信息
     * 
     * @param id 考核结果主键
     * @return 结果
     */
    @Override
    public int deleteKhKhrwResultById(Long id)
    {
        return khKhrwResultMapper.deleteKhKhrwResultById(id);
    }

    @Override
    public AjaxResult generateResult(KhPingce pc,boolean isUpdate) {
        JSONArray children = new JSONArray();
        JSONObject tableColumn = new JSONObject();
        tableColumn.put("name", "khdx");
        if (pc.getBkhdxType().equals("0")) {
            tableColumn.put("label", "单位");
        } else {
            tableColumn.put("label", "姓名");
        }
        children.add(tableColumn);

        JSONObject tableColumn2 = new JSONObject();
        //String pyPCtitle = PinYinUtil.getPinyinInitials(pc.getPcTitle());
        String pyPCtitle = PinYinUtil.getPinyinInitials(pc.getTemplateName());  //表格表头lable改为使用模板名称
        tableColumn2.put("name", pyPCtitle);
        //tableColumn2.put("label", pc.getPcTitle());
        tableColumn2.put("label", pc.getTemplateName());
//-----------------------------------------------------------------------------------------

        JSONArray endData = new JSONArray();  //存放表格数据
        List<KhVoteEmp> lists = new ArrayList<>();

        KhVote khVote = new KhVote();
        khVote.setPingceId(pc.getId());
        //查询该考核任务下的所有评分任务
        List<KhVote> votes = khVoteMapper.selectKhVoteList(khVote);
        for (KhVote vote : votes) {
            KhVoteEmp khVoteEmp = new KhVoteEmp();
            khVoteEmp.setVoteId(vote.getId());
            //查询该评分任务对应的所有被考核对象详情
            List<KhVoteEmp> khVoteEmps = khVoteEmpMapper.selectKhVoteEmpList(khVoteEmp);
            lists.addAll(khVoteEmps);
        }
        //根据被考核对象名分组数据到map中
        Map<String, List<KhVoteEmp>> khdxMap = lists.stream()
                .collect(Collectors.groupingBy(KhVoteEmp::getBkhdxName,
                        LinkedHashMap::new, // 使用LinkedHashMap保持插入顺序（这对于键很重要）
                        Collectors.toList())); // 根据getBkhdxName分组*/lists.stream().
        //循环map得到对应数据
        Set<Map.Entry<String, List<KhVoteEmp>>> entries = khdxMap.entrySet();
        Integer index1=0;
        for (Map.Entry<String, List<KhVoteEmp>> entry : entries) {
            index1++;
            BigDecimal sumScore = BigDecimal.ZERO;
            String key = entry.getKey();
            //获取表头数据
            List<Object> children2 = new ArrayList<>();
//------------------------------------------------------------------------------------------------------

            //获取表数据
            JSONObject pcdata = new JSONObject();
            List<KhVoteEmp> value = entry.getValue();
            JSONObject votesDatas = new JSONObject();
            Integer index2 = 0;
            for (KhVoteEmp voteEmp : value) {
                index2++;
                JSONObject tabledata = new JSONObject();
                tabledata.put("name", "khx"+index2);
                tabledata.put("label", voteEmp.getVoteTitle());

                Object objectData;
                //根据考核类型存储不同数据
                if (voteEmp.getKhitemTypeid().equals(1L)) { //评分选项
                    KhXxpf xxpf = new KhXxpf();
                    xxpf.setOptionA(voteEmp.getOptionA());
                    xxpf.setOptionB(voteEmp.getOptionB());
                    xxpf.setOptionC(voteEmp.getOptionC());
                    xxpf.setOptionD(voteEmp.getOptionD());
                    xxpf.setAvgScore(voteEmp.getAvgScore());
                    xxpf.setPercentage(voteEmp.getPercentage());
                    votesDatas.put("khx"+index2, xxpf);
                    sumScore = sumScore.add(voteEmp.getEndScore());
                    if (index1 == 1) {
                        List<Object> children3 = new ArrayList<>();
                        JSONObject child1 = new JSONObject();
                        JSONObject child2 = new JSONObject();
                        JSONObject child3 = new JSONObject();
                        JSONObject child4 = new JSONObject();
                        JSONObject child5 = new JSONObject();
                        JSONObject child6 = new JSONObject();
                        child1.put("name", "optionA");
                        child1.put("label", "优秀");
                        child2.put("name", "optionB");
                        child2.put("label", "合格");
                        child3.put("name", "optionC");
                        child3.put("label", "基本合格");
                        child4.put("name", "optionD");
                        child4.put("label", "不合格");
                        child5.put("name", "avgScore");
                        child5.put("label", "得分");
                        child6.put("name", "percentage");
                        child6.put("label", "占比");
                        children3.add(child1);
                        children3.add(child2);
                        children3.add(child3);
                        children3.add(child4);
                        children3.add(child5);
                        children3.add(child6);
                        tabledata.put("children", children3);
                        children2.add(tabledata);
                    }
                } else if (voteEmp.getKhitemTypeid().equals(2L)) {//评分占比
                    votesDatas.put("khx"+index2, voteEmp.getAvgScore());
                    votesDatas.put("khx"+index2+"_zb", voteEmp.getPercentage());
                    sumScore = sumScore.add(voteEmp.getEndScore());

                    if (index1 == 1) {
                        JSONObject tabledata2 = new JSONObject();
                        tabledata2.put("name", "khx"+index2 + "_zb");
                        tabledata2.put("label", "占比");
                        children2.add(tabledata);
                        children2.add(tabledata2);
                    }
                } else {//单独评分
                    sumScore = sumScore.add(voteEmp.getAvgScore());
                    votesDatas.put("khx"+index2, voteEmp.getAvgScore());
                    if (index1 == 1) {
                        children2.add(tabledata);
                    }
                }
            }
            pcdata.put("khdx", key);
            pcdata.put(pyPCtitle, votesDatas);
            pcdata.put(pyPCtitle+"_df", sumScore);
            endData.add(pcdata);

            if (index1 == 1) {
                tableColumn2.put("children", children2);
            }
        }

        children.add(tableColumn2);
        JSONObject tableColumn3 = new JSONObject();
        tableColumn3.put("name", pyPCtitle+"_df");
        tableColumn3.put("label", "得分");
        children.add(tableColumn3);


        KhKhrwResult   pcResult = new KhKhrwResult();
        pcResult.setPcId(pc.getId());
        pcResult.setPcName(pc.getPcTitle());
        pcResult.setTemName(pc.getTemplateName());
        pcResult.setTableHeader(children.toJSONString());
        pcResult.setTableData(endData.toJSONString());
        if(isUpdate){
            pcResult.setUpdateBy(getUsername());
            pcResult.setUpdateTime(DateUtils.getNowDate());
            pcResult.setId(pc.getPcResultId());
            this.updateKhKhrwResult(pcResult);
            return AjaxResult.success("更新成功");
        }else{
            pcResult.setCreateBy(getUsername());
            this.insertKhKhrwResult(pcResult);
            return AjaxResult.success("生成成功");
        }
    }
}
