package com.ruoyi.kaohe.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.kaohe.domain.*;
import com.ruoyi.kaohe.service.IKhVoteEmpService;
import com.ruoyi.kaohe.service.IKhVoteService;
import com.ruoyi.kaohe.util.PinYinUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.kaohe.service.IKhKhrwResultService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 考核结果Controller
 * 
 * @author hs
 * @date 2025-07-05
 */
@RestController
@RequestMapping("/kaohe/kh_result")
public class KhKhrwResultController extends BaseController
{
    @Autowired
    private IKhKhrwResultService khKhrwResultService;
    @Autowired
    private IKhVoteEmpService voteEmpService;
    @Autowired
    private IKhVoteService khVoteService;

    /**
     * 生成考核结果
     */
    @PreAuthorize("@ss.hasPermi('kaohe:kh_result:generate')")
    @PostMapping("/generateResult")
    public AjaxResult generateResult(@RequestBody KhPingce pc) {   //传递参数  id、pc_title、bkhdxtype
        JSONArray header = new JSONArray();//存放表头及表格关联数据
        JSONObject headerData = new JSONObject();
        headerData.put("name", null);
        headerData.put("label", pc.getPcTitle());
        List<Object> children = new ArrayList<>();
        JSONObject tableColumn = new JSONObject();
        tableColumn.put("name", "khdxName");
        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());
        tableColumn2.put("name", pyPCtitle);
        tableColumn2.put("label", pc.getPcTitle());

//-----------------------------------------------------------------------------------------

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

        KhVote khVote = new KhVote();
        khVote.setPingceId(pc.getId());
        //查询该考核任务下的所有评分任务
        List<KhVote> votes = khVoteService.selectKhVoteList(khVote);
        for (KhVote vote : votes) {
            KhVoteEmp khVoteEmp = new KhVoteEmp();
            khVoteEmp.setVoteId(vote.getId());
            //查询该评分任务对应的所有被考核对象详情
            List<KhVoteEmp> khVoteEmps = voteEmpService.selectKhVoteEmpList(khVoteEmp);

            //  votesMap.put(vote.getVoteTitle(),khVoteEmps);
            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();
        for (Map.Entry<String, List<KhVoteEmp>> entry : entries) {
            BigDecimal sumScore=BigDecimal.ZERO;
            String key = entry.getKey();
            //获取表头数据
            List<Object> children2 = new ArrayList<>();
            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();
//------------------------------------------------------------------------------------------------------

            //获取表数据
            JSONObject pcdata = new JSONObject();
            List<KhVoteEmp> value = entry.getValue();
            JSONObject votesDatas = new JSONObject();
            Integer index=0;
            for (KhVoteEmp voteEmp : value) {
                index++;
                String pyVoteTitle = PinYinUtil.getPinyinInitials(voteEmp.getVoteTitle());
                JSONObject tabledata = new JSONObject();
                tabledata.put("name", pyVoteTitle);
                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());
                    objectData = xxpf;
                    sumScore=sumScore.add(voteEmp.getEndScore());
                    if(index==1){
                        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);
                    }



                } else if (voteEmp.getKhitemTypeid().equals(2L)) {//评分占比
                    KhPfzb pfzb = new KhPfzb();
                    pfzb.setAvgScore(voteEmp.getAvgScore());
                    pfzb.setPercentage(voteEmp.getPercentage());
                    objectData = pfzb;
                    sumScore=sumScore.add(voteEmp.getEndScore());


                    if(index==1){
                        child1.put("name","avgScore");
                        child1.put("label","得分");
                        child2.put("name","percentage");
                        child2.put("label","占比");
                        children3.add(child2);
                        children3.add(child1);
                    }


                } else {//单独评分
                    KhDdpf ddpf = new KhDdpf();
                    ddpf.setAvgScore(voteEmp.getAvgScore());
                    objectData = ddpf;
                    sumScore=sumScore.add(voteEmp.getAvgScore());


                    if(index==1){{
                        child1.put("name","avgScore");
                        child1.put("label","得分");
                        children3.add(child1);
                    }}
                }
                votesDatas.put(pyVoteTitle, objectData);

                tabledata.put("children",children3);
                children2.add(tabledata);
            }
            pcdata.put("khdxName", key);
            pcdata.put(pyPCtitle, votesDatas);
            pcdata.put("df",sumScore);
            endData.add(pcdata);

            tableColumn2.put("children",children2);
        }

        children.add(tableColumn2);
        JSONObject tableColumn3 = new JSONObject();
        tableColumn3.put("name", "df");
        tableColumn3.put("label", "得分");
        children.add(tableColumn3);
        headerData.put("children",children);
        header.add(headerData);


        KhKhrwResult   pcResult = new KhKhrwResult();
        pcResult.setPcId(pc.getId());
        pcResult.setPcName(pc.getPcTitle());
        pcResult.setTableHeader(header.toJSONString());
        pcResult.setTableData(endData.toJSONString());
        khKhrwResultService.insertKhKhrwResult(pcResult);
        return AjaxResult.success();

    }

    /**
     * 查询考核结果列表
     */
    @PreAuthorize("@ss.hasPermi('kaohe:kh_result:list')")
    @GetMapping("/list")
    public TableDataInfo list(KhKhrwResult khKhrwResult)
    {
        startPage();
        List<KhKhrwResult> list = khKhrwResultService.selectKhKhrwResultList(khKhrwResult);
        return getDataTable(list);
    }

    /**
     * 导出考核结果列表
     */
    @PreAuthorize("@ss.hasPermi('kaohe:kh_result:export')")
    @Log(title = "考核结果", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KhKhrwResult khKhrwResult)
    {
        List<KhKhrwResult> list = khKhrwResultService.selectKhKhrwResultList(khKhrwResult);
        ExcelUtil<KhKhrwResult> util = new ExcelUtil<KhKhrwResult>(KhKhrwResult.class);
        util.exportExcel(response, list, "考核结果数据");
    }

    /**
     * 获取考核结果详细信息
     */
    @PreAuthorize("@ss.hasPermi('kaohe:kh_result:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(khKhrwResultService.selectKhKhrwResultById(id));
    }

    /**
     * 新增考核结果
     */
    @PreAuthorize("@ss.hasPermi('kaohe:kh_result:add')")
    @Log(title = "考核结果", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KhKhrwResult khKhrwResult)
    {
        return toAjax(khKhrwResultService.insertKhKhrwResult(khKhrwResult));
    }

    /**
     * 修改考核结果
     */
    @PreAuthorize("@ss.hasPermi('kaohe:kh_result:edit')")
    @Log(title = "考核结果", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KhKhrwResult khKhrwResult)
    {
        return toAjax(khKhrwResultService.updateKhKhrwResult(khKhrwResult));
    }

    /**
     * 删除考核结果
     */
    @PreAuthorize("@ss.hasPermi('kaohe:kh_result:remove')")
    @Log(title = "考核结果", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(khKhrwResultService.deleteKhKhrwResultByIds(ids));
    }
}
