package com.ruoyi.kaohe.controller;

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

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.kaohe.domain.*;
import com.ruoyi.kaohe.service.*;
import com.ruoyi.kaohe.service.impl.KhVoteServiceImpl;
import com.ruoyi.kaohe.util.PinYinUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
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.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 考核评测Controller
 *
 * @author hs
 * @date 2025-06-17
 */
@RestController
@RequestMapping("/kaohe/pingce")
public class KhPingceController extends BaseController {
    @Autowired
    private IKhPingceService khPingceService;
    @Autowired
    private IKhPcEmpService pcEmpService;
    @Autowired
    private IKhVoteService khVoteService;
    @Autowired
    private IKhVoteEmpService khVoteEmpService;
    @Autowired
    private IKhVoteRecardService khVoteRecardService;

    /**
     * 查询考核评测列表
     */
    @PreAuthorize("@ss.hasPermi('kaohe:pingce:list')")
    @GetMapping("/list")
    public TableDataInfo list(KhPingce khPingce) {
        startPage();
        List<KhPingce> list = khPingceService.selectKhPingceList(khPingce);
        return getDataTable(list);
    }

    /**
     * 导出考核评测列表
     */
    @PreAuthorize("@ss.hasPermi('kaohe:pingce:export')")
    @Log(title = "考核评测", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KhPingce khPingce) {
        List<KhPingce> list = khPingceService.selectKhPingceList(khPingce);
        ExcelUtil<KhPingce> util = new ExcelUtil<KhPingce>(KhPingce.class);
        util.exportExcel(response, list, "考核评测数据");
    }

    /**
     * 获取考核评测详细信息
     */
    @PreAuthorize("@ss.hasPermi('kaohe:pingce:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(khPingceService.selectKhPingceById(id));
    }

    /**
     * 新增考核评测
     */
    @PreAuthorize("@ss.hasPermi('kaohe:pingce:add')")
    @Log(title = "考核评测", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping
    public AjaxResult add(@RequestBody KhPingce khPingce) {
        khPingce.setCreateBy(getUsername());
        khPingceService.insertKhPingce(khPingce);
        //增加关联表
        List<Bkhdx> pcEmps = khPingce.getPcBkhdxs();
        if (pcEmps != null && pcEmps.size() > 0) {
            for (Bkhdx item : pcEmps) {
                KhPcEmp pcEmp = new KhPcEmp();
                pcEmp.setPcId(khPingce.getId());
                pcEmp.setBkhdxId(item.getBkhdxId());
                pcEmp.setBkhdxName(item.getBkhdxName());
                pcEmp.setDeptId(item.getDeptId());
                pcEmp.setDeptName(item.getDeptName());
                pcEmpService.insertKhPcEmp(pcEmp);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改考核评测
     */
    @PreAuthorize("@ss.hasPermi('kaohe:pingce:edit')")
    @Log(title = "考核评测", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody KhPingce khPingce) {
        khPingceService.updateKhPingce(khPingce);

        List<Bkhdx> pcEmps = khPingce.getPcBkhdxs();
        if (pcEmps != null && pcEmps.size() > 0) {
            //删除原来关联
            KhPcEmp query = new KhPcEmp();
            query.setPcId(khPingce.getId());
            List<KhPcEmp> temItems = pcEmpService.selectKhPcEmpList(query);
            List<Long> ids = temItems.stream().map(KhPcEmp::getId).collect(Collectors.toList());
            if (ids != null && ids.size() > 0) {
                pcEmpService.deleteKhPcEmpByIds(ids.toArray(new Long[ids.size()]));
            }
            //增加新的关联
            for (Bkhdx item : pcEmps) {
                KhPcEmp pcEmp = new KhPcEmp();
                pcEmp.setPcId(khPingce.getId());
                pcEmp.setBkhdxId(item.getBkhdxId());
                pcEmp.setBkhdxName(item.getBkhdxName());
                pcEmp.setDeptId(item.getDeptId());
                pcEmp.setDeptName(item.getDeptName());
                pcEmpService.insertKhPcEmp(pcEmp);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 删除考核评测
     */
    @PreAuthorize("@ss.hasPermi('kaohe:pingce:remove')")
    @Log(title = "考核评测", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) {
            KhPingce khPingce = khPingceService.selectKhPingceById(id);
            if (!khPingce.getState().equals("0")) {
                return AjaxResult.error("评测：" + khPingce.getPcTitle() + " 当前状态不能删除");
            }
        }
        return toAjax(khPingceService.deleteKhPingceByIds(ids));
    }

    /**
     * 考核任务 修改被考核对象（添加/删除被考核对象）
     * 传参：id、pcBkhdxs、addOrDel、bkhdxType
     */
    // @PreAuthorize("@ss.hasPermi('kaohe:pingce:modifyBkhdx')")
    @Log(title = "任务添加/删除被考核对象", businessType = BusinessType.UPDATE)
    @PutMapping("/modifyBkhdx")
    @Transactional
    public AjaxResult modifyBkhdx(@RequestBody ModifyBkhdxParam bkhdxParam) {
        Long id = bkhdxParam.getId();
        List<Bkhdx> pcEmps = bkhdxParam.getPcBkhdxs();
        if (pcEmps == null || pcEmps.size() <= 0) {
            return AjaxResult.error("选择的被考核对象为空！");
        }
        //查询已发布考核项vote
        KhVote vote = new KhVote();
        vote.setPingceId(id);
        List<KhVote> khVotes = khVoteService.selectKhVoteList(vote);

        if (bkhdxParam.getAddOrDel().equals("0")) {  //0添加被考核对象  1删除
            for (Bkhdx item : pcEmps) {
                KhPcEmp pcEmp = new KhPcEmp();
                pcEmp.setPcId(bkhdxParam.getId());
                pcEmp.setBkhdxId(item.getBkhdxId());
                pcEmp.setBkhdxName(item.getBkhdxName());
                pcEmp.setDeptId(item.getDeptId());
                pcEmp.setDeptName(item.getDeptName());
                pcEmpService.insertKhPcEmp(pcEmp);
            }
            //已发布考核需添加对应考核项的关联人
            if (khVotes != null && khVotes.size() > 0) {
                for (KhVote khVote : khVotes) {
                    for (Bkhdx item : pcEmps) {
                        //新增投票选项关联表
                        KhVoteEmp voteEmp = new KhVoteEmp();
                        voteEmp.setBkhdxId(item.getBkhdxId());
                        voteEmp.setBkhdxName(item.getBkhdxName());
                        voteEmp.setVoteId(khVote.getId());
                        voteEmp.setVoteTitle(khVote.getVoteTitle());
                        voteEmp.setPercentage(khVote.getPercentage());
                        voteEmp.setKhitemTypeid(khVote.getKhitemTypeid());
                        if (khVote.getKhitemTypeid().equals(1L)) {
                            voteEmp.setOptionA(BigDecimal.ZERO);
                            voteEmp.setOptionB(BigDecimal.ZERO);
                            voteEmp.setOptionC(BigDecimal.ZERO);
                            voteEmp.setOptionD(BigDecimal.ZERO);
                        }
                        khVoteEmpService.insertKhVoteEmp(voteEmp);
                    }
                }
            }
        } else {
            //删除关联
            List<Long> ids = new ArrayList<>();
            KhPcEmp query = new KhPcEmp();
            query.setPcId(id);
            List<KhPcEmp> pcEmpsItems = pcEmpService.selectKhPcEmpList(query);
            for (Bkhdx pcEmp : pcEmps) {
                for (KhPcEmp pcEmpsItem : pcEmpsItems) {
                    if (pcEmpsItem.getBkhdxId().equals(pcEmp.getBkhdxId())) {
                        ids.add(pcEmpsItem.getId());
                    }
                }
            }
            if (ids != null && ids.size() > 0) {
                pcEmpService.deleteKhPcEmpByIds(ids.toArray(new Long[ids.size()]));
            }
            //已发布考核vote   删除对应数据
            if (khVotes != null && khVotes.size() > 0) {
                List<Long> veIds = new ArrayList<>();
                for (KhVote khVote : khVotes) {
                    KhVoteEmp vEmp = new KhVoteEmp();
                    vEmp.setVoteId(khVote.getId());
                    List<KhVoteEmp> khVEmps = khVoteEmpService.selectKhVoteEmpList(vEmp);
                    for (Bkhdx item : pcEmps) {
                        for (KhVoteEmp khVEmp : khVEmps) {
                            if (khVEmp.getBkhdxId().equals(item.getBkhdxId())) {
                                veIds.add(khVEmp.getId());
                            }
                        }
                    }
                }
                if (veIds.size() > 0) {
                    khVoteEmpService.deleteKhVoteEmpByIds(veIds.toArray(new Long[veIds.size()]));
                }
            }
        }
        return AjaxResult.success();
    }


    /**
     * ids传入为null——————清理数据库时调用， 清除已完成的全部关联数据、进行中的仅清除voteemp的打票成绩  保留考核项及关联的voteemp
     * 清理数据库时：vote_recard表截断表即可
     * ids有值   按任务id-----修改所有关联的vote的voteemp数据为原始状态
     */
    // @PreAuthorize("@ss.hasPermi('kaohe:pingce:remove')")
    @Log(title = "任务清除打分数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/clean")
    @Transactional
    public AjaxResult removeTest(@RequestParam Long[] ids) {
        if (ids != null && ids.length > 0) { //按任务id-----修改所有关联的vote的voteemp数据为原始状态
            for (Long cleanId : ids) {
                KhVote vote = new KhVote();
                vote.setPingceId(cleanId);
                List<KhVote> votes = khVoteService.selectKhVoteList(vote);
                if (votes != null && votes.size() > 0) {
                    List<Long> vIds = votes.stream().map(KhVote::getId).collect(Collectors.toList());
                    //修改voteemp
                    for (Long vId : vIds) {
                        KhVoteEmp vemp = new KhVoteEmp();
                        vemp.setVoteId(vId);
                        List<KhVoteEmp> vEmps = khVoteEmpService.selectKhVoteEmpList(vemp);
                        if (vEmps != null && vEmps.size() > 0) {
                            //修改关联的员工数据到最初创建状态
                            for (KhVoteEmp uPEmp : vEmps) {
                                uPEmp.setVoteNum(BigDecimal.ZERO);
                                uPEmp.setVoteScore(BigDecimal.ZERO);
                                uPEmp.setAvgScore(BigDecimal.ZERO);
                                uPEmp.setEndScore(BigDecimal.ZERO);
                                if (uPEmp.getKhitemTypeid().equals(1L)) {
                                    uPEmp.setOptionA(BigDecimal.ZERO);
                                    uPEmp.setOptionB(BigDecimal.ZERO);
                                    uPEmp.setOptionC(BigDecimal.ZERO);
                                    uPEmp.setOptionD(BigDecimal.ZERO);
                                }
                                khVoteEmpService.updateKhVoteEmp(uPEmp);
                            }
                        }
                    }
                    //清空投票记录表  根据pcId查询
                    KhVoteRecard vr = new KhVoteRecard();
                    vr.setPcId(cleanId);
                    List<KhVoteRecard> khVoteRecards = khVoteRecardService.selectKhVoteRecardList(vr);
                    if (khVoteRecards != null & khVoteRecards.size() > 0) {
                        List<Long> vrIds = khVoteRecards.stream().map(KhVoteRecard::getId).collect(Collectors.toList());
                        khVoteRecardService.deleteKhVoteRecardByIds(vrIds.toArray(new Long[vrIds.size()]));
                    }
                }
            }
            return toAjax(1);
        } /*else {//null认为清理所有 （已完成删除全部数据，进行中数据清除评分数据）
            //已完成的数据直接清除任务及所有关联数据————完全删除已完成任务
            KhPingce khPingce = new KhPingce();
            khPingce.setState("2");
            List<KhPingce> wPingces = khPingceService.selectKhPingceList(khPingce);
            if (wPingces != null && wPingces.size() > 0) {
                List<Long> wIds = wPingces.stream().map(KhPingce::getId).collect(Collectors.toList());
                khPingceService.deleteKhPingceByIds2(wIds.toArray(new Long[wIds.size()]));
            }
            //进行中  的数据   修改关联的vote及voteemp数据为原始状态
            KhPingce jxz = new KhPingce();
            jxz.setState("1");
            List<KhPingce> jxzPingces = khPingceService.selectKhPingceList(jxz);
            if (jxzPingces != null && jxzPingces.size() > 0) {
                List<Long> jxzIds = jxzPingces.stream().map(KhPingce::getId).collect(Collectors.toList());
                for (Long jxzId : jxzIds) {
                    KhVote vote = new KhVote();
                    vote.setPingceId(jxzId);
                    List<KhVote> votes = khVoteService.selectKhVoteList(vote);
                    if (votes != null && votes.size() > 0) {
                        List<Long> vIds = votes.stream().map(KhVote::getId).collect(Collectors.toList());
                        //修改voteemp
                        for (Long vId : vIds) {
                            KhVoteEmp vemp = new KhVoteEmp();
                            vemp.setVoteId(vId);
                            List<KhVoteEmp> vEmps = khVoteEmpService.selectKhVoteEmpList(vemp);
                            if (vEmps != null && vEmps.size() > 0) {
                                //修改关联的员工数据到最初创建状态
                                for (KhVoteEmp uPEmp : vEmps) {
                                    uPEmp.setVoteNum(BigDecimal.ZERO);
                                    uPEmp.setVoteScore(BigDecimal.ZERO);
                                    uPEmp.setAvgScore(BigDecimal.ZERO);
                                    uPEmp.setEndScore(BigDecimal.ZERO);
                                    if (uPEmp.getKhitemTypeid().equals(1L)) {
                                        uPEmp.setOptionA(BigDecimal.ZERO);
                                        uPEmp.setOptionB(BigDecimal.ZERO);
                                        uPEmp.setOptionC(BigDecimal.ZERO);
                                        uPEmp.setOptionD(BigDecimal.ZERO);
                                    }
                                    khVoteEmpService.updateKhVoteEmp(uPEmp);
                                }
                            }
                        }

                        //清空投票记录表  根据pcId查询
                        KhVoteRecard vr = new KhVoteRecard();
                        vr.setPcId(jxzId);
                        List<KhVoteRecard> khVoteRecards = khVoteRecardService.selectKhVoteRecardList(vr);
                        if (khVoteRecards != null & khVoteRecards.size() > 0) {
                            List<Long> vrIds = khVoteRecards.stream().map(KhVoteRecard::getId).collect(Collectors.toList());
                            khVoteRecardService.deleteKhVoteRecardByIds(vrIds.toArray(new Long[vrIds.size()]));
                        }
                    }
                }
            }
            AjaxResult.success("按要求清理数据库成功")
        }*/

        return AjaxResult.error("请选择需要清理的考核任务！");
    }
}
