package com.ruoyi.kaohe.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.kaohe.domain.*;
import com.ruoyi.kaohe.service.*;
import org.springframework.scheduling.annotation.Scheduled;
import java.math.BigDecimal;
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.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.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 投票评测Controller
 *
 * @author hs
 * @date 2025-06-17
 */
@RestController
@RequestMapping("/kaohe/vote")
public class KhVoteController extends BaseController {
    @Autowired
    private IKhVoteService khVoteService;
    @Autowired
    private IKhPcEmpService pcEmpService;
    @Autowired
    private IKhVoteEmpService voteEmpService;
    @Autowired
    private IKhPingceService khPingceService;
    @Autowired
    private IKhTemItemService khTemItemService;

    @Scheduled(cron = "0 * * * * ?") // 每分钟的第0秒执行一次   监测时间修改评分状态
    public void performTask() {
        System.out.println("进入定时任务-------------------------------------------------------------");
        //获取所有未完成的评分任务
        List<KhVote> list = khVoteService.selectUnfinishedVote();
        for (KhVote vote : list) {
            Date sTime = vote.getsTime();
            Date eTime = vote.geteTime();
            String state = vote.getState();
            // 获取当前日期和时间
            Date now = new Date();
            // 根据当前时间与开始、结束时间关系 修改状态
            if (state.equals("0") && (now.after(sTime) && now.before(eTime))) {
                vote.setState("1");
                khVoteService.updateKhVote(vote);
                System.out.println("执行定时任务: " + System.currentTimeMillis() + " 修改评分任务： " +vote.getId()+" "+ vote.getVoteTitle() + "  状态为进行中");
            }
            if (now.after(eTime)) {
                vote.setState("2");
                khVoteService.updateKhVote(vote);
                System.out.println("执行定时任务: " + System.currentTimeMillis() + " 修改评分任务： " +vote.getId()+" "+ vote.getVoteTitle() + "  状态为已完成");
            }
        }
        //修改考核任务状态，当考核任务下所有评分都为已完成时，修改考核任务状态为已完成
        KhPingce param = new KhPingce();
        param.setState("1");
        List<KhPingce> pingces = khPingceService.selectKhPingceList(param);
        for (KhPingce pingce : pingces) {
            boolean finishflag=true;
            //查询考核任务下面有几个考核项
            KhTemItem  temItem = new KhTemItem();
            temItem.setTemId(pingce.getTemplateId());
            int itemNo = khTemItemService.selectKhTemItemList(temItem).size();
            //查询考核任务已有评测任务
            KhVote khVote = new KhVote();
            khVote.setPingceId(pingce.getId());
            List<KhVote> khVotes = khVoteService.selectKhVoteList(khVote);
            if(khVotes.size()==itemNo){ //任务下所有考核项都已经发布
                for (KhVote vote : khVotes) {
                    if(!vote.getState().equals("2")){
                        finishflag=false;
                    }
                }
                if(finishflag){
                    pingce.setState("2");
                    khPingceService.updateKhPingce(pingce);
                    System.out.println("执行定时任务: " + System.currentTimeMillis() + " 修改考核任务： " +pingce.getId()+" "+ pingce.getPcTitle() + "  状态为已完成");
                }
            }

        }
    }

    /**
     * 查询投票评测列表
     */
    @PreAuthorize("@ss.hasPermi('kaohe:vote:list')")
    @GetMapping("/list")
    public TableDataInfo list(KhVote khVote) {
        startPage();
        List<KhVote> list = khVoteService.selectKhVoteList(khVote);
        return getDataTable(list);
    }

    /**
     * 职工首页根据pingceId、itemIds、state查询投票评测列表————废弃
     */
    @PreAuthorize("@ss.hasPermi('kaohe:vote:list')")
    @GetMapping("/listByConditons")
    public TableDataInfo getListByConditons(KhVote khVote) {
        khVote.setState("2");
        startPage();
        List<KhVote> list = khVoteService.getListByPcIdAndItemIds(khVote);
        return getDataTable(list);
    }
    /**
     * 评价账号登录首页根据pingceId、itemIds、state查询投票评测列表
     * 参数: voteIds
     */
    @PreAuthorize("@ss.hasPermi('kaohe:vote:list')")
    @GetMapping("/ListByVoteIds")
    public TableDataInfo getListByVoteIds(KhVote khVote) {
        khVote.setState("2");
        startPage();
        List<KhVote> list = khVoteService.getListByVoteIds(khVote);
        return getDataTable(list);
    }

    /**
     * 导出投票评测列表
     */
    @PreAuthorize("@ss.hasPermi('kaohe:vote:export')")
    @Log(title = "投票评测", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KhVote khVote) {
        List<KhVote> list = khVoteService.selectKhVoteList(khVote);
        ExcelUtil<KhVote> util = new ExcelUtil<KhVote>(KhVote.class);
        util.exportExcel(response, list, "投票评测数据");
    }

    /**
     * 获取投票评测详细信息
     */
    @PreAuthorize("@ss.hasPermi('kaohe:vote:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(khVoteService.selectKhVoteById(id));
    }

    /**
     * 新增投票评测
     */
    @PreAuthorize("@ss.hasPermi('kaohe:vote:add')")
    @Log(title = "投票评测", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody KhVote khVote) {
        khVoteService.insertKhVote(khVote);
        //评分占比是否一致，0一致   1不一致
        if(khVote.getSamePercent()==null||khVote.getSamePercent().equals("0")){
            //根据评测id查询职工评测关联 职工
            KhPcEmp query = new KhPcEmp();
            query.setPcId(khVote.getPingceId());
            List<KhPcEmp> pcEmps = pcEmpService.selectKhPcEmpList(query);
            for (KhPcEmp pcEmp : pcEmps) {
                //新增投票选项关联表
                KhVoteEmp voteEmp = new KhVoteEmp();
                voteEmp.setBkhdxId(pcEmp.getBkhdxId());
                voteEmp.setBkhdxName(pcEmp.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);
                }
                voteEmpService.insertKhVoteEmp(voteEmp);
            }
        }else{
            for (KhVoteEmp vEmp : khVote.getVoteEmps()) {
                //新增投票选项关联表
                KhVoteEmp voteEmp = new KhVoteEmp();
                voteEmp.setBkhdxId(vEmp.getBkhdxId());
                voteEmp.setBkhdxName(vEmp.getBkhdxName());
                voteEmp.setVoteId(khVote.getId());
                voteEmp.setVoteTitle(khVote.getVoteTitle());
                voteEmp.setPercentage(vEmp.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);
                }
                voteEmpService.insertKhVoteEmp(voteEmp);
            }
        }

        return AjaxResult.success();
    }

    /**
     * 修改投票评测
     */
    @PreAuthorize("@ss.hasPermi('kaohe:vote:edit')")
    @Log(title = "投票评测", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody KhVote khVote) {
        //voteid查询职工评分修改对应值
        KhVoteEmp query = new KhVoteEmp();
        query.setVoteId(khVote.getId());
        List<KhVoteEmp> khVoteEmps = voteEmpService.selectKhVoteEmpList(query);
        if (khVote.getSamePercent()==null||khVote.getSamePercent().equals("0")) {
            for (KhVoteEmp khVoteEmp : khVoteEmps) {
                khVoteEmp.setPercentage(khVote.getPercentage());
                khVoteEmp.setVoteTitle(khVote.getVoteTitle());
                voteEmpService.updateKhVoteEmp(khVoteEmp);
            }
        }else{
            //修改投票选项关联表
            for (KhVoteEmp khVoteEmp : khVoteEmps) {
                for (KhVoteEmp vEmp : khVote.getVoteEmps()) {
                    if (vEmp.getBkhdxId().equals(khVoteEmp.getBkhdxId())) {
                        khVoteEmp.setPercentage(vEmp.getPercentage());
                    }
                }
                khVoteEmp.setVoteTitle(khVote.getVoteTitle());
                voteEmpService.updateKhVoteEmp(khVoteEmp);
            }
        }
            khVoteService.updateKhVote(khVote);
        return AjaxResult.success();
    }

    /**
     * 删除投票评测
     */
    @PreAuthorize("@ss.hasPermi('kaohe:vote:remove')")
    @Log(title = "投票评测", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(khVoteService.deleteKhVoteByIds(ids));
    }
}
