package com.ruoyi.kaohe.service.impl;

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

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.kaohe.domain.KhVoteItems;
import com.ruoyi.kaohe.domain.KhVoteRecard;
import com.ruoyi.kaohe.domain.KhVoteRecardParam;
import com.ruoyi.kaohe.mapper.KhVoteItemsMapper;
import com.ruoyi.kaohe.mapper.KhVoteRecardMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.kaohe.mapper.KhVoteEmpMapper;
import com.ruoyi.kaohe.domain.KhVoteEmp;
import com.ruoyi.kaohe.service.IKhVoteEmpService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 投票选项Service业务层处理
 *
 * @author hs
 * @date 2025-06-17
 */
@Service
public class KhVoteEmpServiceImpl implements IKhVoteEmpService {
    @Autowired
    private KhVoteEmpMapper khVoteEmpMapper;
    @Autowired
    private KhVoteRecardMapper khVoteRecardMapper;
    @Autowired
    private KhVoteItemsMapper khVoteItemsMapper;

    /**
     * 查询投票选项
     *
     * @param id 投票选项主键
     * @return 投票选项
     */
    @Override
    public KhVoteEmp selectKhVoteEmpById(Long id) {
        return khVoteEmpMapper.selectKhVoteEmpById(id);
    }

    /**
     * 查询投票选项列表
     *
     * @param khVoteEmp 投票选项
     * @return 投票选项
     */
    @Override
    public List<KhVoteEmp> selectKhVoteEmpList(KhVoteEmp khVoteEmp) {
        return khVoteEmpMapper.selectKhVoteEmpList(khVoteEmp);
    }

    @Override
    public List<KhVoteEmp> selectVoteEmpsByVoteId(KhVoteEmp khVoteEmp) {
        return khVoteEmpMapper.selectVoteEmpsByVoteId(khVoteEmp);
    }

    /**
     * 新增投票选项
     *
     * @param khVoteEmp 投票选项
     * @return 结果
     */
    @Override
    public int insertKhVoteEmp(KhVoteEmp khVoteEmp) {
        khVoteEmp.setCreateTime(DateUtils.getNowDate());
        return khVoteEmpMapper.insertKhVoteEmp(khVoteEmp);
    }

    /**
     * 修改投票选项
     *
     * @param khVoteEmp 投票选项
     * @return 结果
     */
    @Override
    public int updateKhVoteEmp(KhVoteEmp khVoteEmp) {
        khVoteEmp.setUpdateTime(DateUtils.getNowDate());
        return khVoteEmpMapper.updateKhVoteEmp(khVoteEmp);
    }

    /**
     * 批量删除投票选项
     *
     * @param ids 需要删除的投票选项主键
     * @return 结果
     */
    @Override
    public int deleteKhVoteEmpByIds(Long[] ids) {
        return khVoteEmpMapper.deleteKhVoteEmpByIds(ids);
    }

    /**
     * 删除投票选项信息
     * 手动实现乐观锁重试机制
     *
     * @param id 投票选项主键
     * @return 结果
     */
    @Override
    public int deleteKhVoteEmpById(Long id) {
        return khVoteEmpMapper.deleteKhVoteEmpById(id);
    }

    @Override
    @Transactional
   // @Async("threadPoolTaskExecutor")
    public AjaxResult voteSubmit(KhVoteRecardParam param) {
        System.out.println("------------------------开始异步批量处理用户数据，线程：" + Thread.currentThread().getName());
        Map<String, String> xuanxiangDetails = new LinkedHashMap<>();
        Map<String, BigDecimal> pingFenDetails = new LinkedHashMap<>();
        BigDecimal num = new BigDecimal("1");//投票人数+1
        List<KhVoteEmp> voteEmpList = param.getVoteEmpList();
        Date nowDate = DateUtils.getNowDate();
        Long typeid = param.getKhitemTypeid();

        //存储投票记录
        KhVoteRecard recard = new KhVoteRecard();
        recard.setRemark(JSON.toJSONString(voteEmpList));
        recard.setPcId(param.getPingceId());
        recard.setVoteId(param.getVoteId());
        recard.setUserId(param.getUserId());
        recard.setUserName(param.getUserName());
        // recard.setUid(param.getUid());

        //选项评分
        if (typeid.equals(1L)) {
            List<KhVoteItems> voteItems = khVoteItemsMapper.selectKhVoteItemsList(null);//从数据库获取分值
            BigDecimal a = new BigDecimal("100");
            BigDecimal b = new BigDecimal("80");
            BigDecimal c = new BigDecimal("60");
            BigDecimal d = new BigDecimal("40");
            String aName = "优秀";
            String bName = "合格";
            String cName = "基本合格";
            String dName = "不合格";
            if (voteItems != null && voteItems.size() > 0) {
                for (KhVoteItems voteItem : voteItems) {
                    if (voteItem.getId() == 1) {
                        a = voteItem.getScore();
                        aName = voteItem.getVitemName();
                    } else if (voteItem.getId() == 2) {
                        b = voteItem.getScore();
                        bName = voteItem.getVitemName();
                    } else if (voteItem.getId() == 3) {
                        c = voteItem.getScore();
                        cName = voteItem.getVitemName();
                    } else {
                        d = voteItem.getScore();
                        dName = voteItem.getVitemName();
                    }
                }
            }
            for (KhVoteEmp voteEmp : voteEmpList) {
                // 最大重试次数
                // final int MAX_RETRY_COUNT = 3;
                int retryCount = 0;
              /*  while (true) {*/
                    voteEmp.setUpdateTime(nowDate);
                    //根据id查询数据得到原值及版本号
                    KhVoteEmp oldvoteEmp = khVoteEmpMapper.selectKhVoteEmpById(voteEmp.getId());
                    //存储投票详情到map
                    if (voteEmp.getOptionA().compareTo(BigDecimal.ZERO) == 1) {
                        // xuanxiangDetails.put(voteEmp.getBkhdxId().toString(), voteEmp.getBkhdxName()+":优秀");
                        xuanxiangDetails.put(voteEmp.getBkhdxName(), aName);
                    }
                    if (voteEmp.getOptionB().compareTo(BigDecimal.ZERO) == 1) {
                        //xuanxiangDetails.put(voteEmp.getBkhdxId().toString(), voteEmp.getBkhdxName()+":合格");
                        xuanxiangDetails.put(voteEmp.getBkhdxName(), bName);
                    }
                    if (voteEmp.getOptionC().compareTo(BigDecimal.ZERO) == 1) {
                        //xuanxiangDetails.put(voteEmp.getBkhdxId().toString(), voteEmp.getBkhdxName()+":基本合格");
                        xuanxiangDetails.put(voteEmp.getBkhdxName(), cName);
                    }
                    if (voteEmp.getOptionD().compareTo(BigDecimal.ZERO) == 1) {
                        //xuanxiangDetails.put(voteEmp.getBkhdxId().toString(), voteEmp.getBkhdxName()+":不合格");
                        xuanxiangDetails.put(voteEmp.getBkhdxName(), dName);
                    }
                    //修改投票情况
                    BigDecimal optionA = voteEmp.getOptionA().add(oldvoteEmp.getOptionA());
                    BigDecimal optionB = voteEmp.getOptionB().add(oldvoteEmp.getOptionB());
                    BigDecimal optionC = voteEmp.getOptionC().add(oldvoteEmp.getOptionC());
                    BigDecimal optionD = voteEmp.getOptionD().add(oldvoteEmp.getOptionD());
                    voteEmp.setVoteNum(oldvoteEmp.getVoteNum().add(num));
                    BigDecimal avgScore = (optionA.multiply(a).add(optionB.multiply(b).add(optionC.multiply(c).add(optionD.multiply(d)))
                    )).divide(voteEmp.getVoteNum(), 4, RoundingMode.HALF_UP);
                    voteEmp.setAvgScore(avgScore);//投票后计算平均分
                    voteEmp.setOptionA(optionA);
                    voteEmp.setOptionB(optionB);
                    voteEmp.setOptionC(optionC);
                    voteEmp.setOptionD(optionD);
                    if (oldvoteEmp.getPercentage() != null) {  //计算最后得分
                        voteEmp.setEndScore(avgScore.multiply(oldvoteEmp.getPercentage()));
                    } else {
                        voteEmp.setEndScore(avgScore);
                    }
                    voteEmp.setVersion(oldvoteEmp.getVersion());
                    int result = khVoteEmpMapper.updateKhVoteEmp(voteEmp);
                    /*if (result > 0) {
                        break;
                    } else {
                        // 更新失败，版本冲突，增加重试计数
                        retryCount++;
                        if (retryCount > 3) {
                            throw new RuntimeException("重试次数过多被中断-------------");
                        }
                        System.out.println("-----------版本冲突，" + voteEmp.getBkhdxName() + "第" + retryCount + "次重试");
                        // 等待一段时间后重试，避免立即重试导致的持续冲突
                        try {
                            Thread.sleep(1000 * retryCount); // 重试间隔递增
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw new RuntimeException("重试过程异常中断-------------", e);
                        }
                        // }
                    }
                }*/
            }
        } else if (typeid.equals(2L)) {//占比评分
            for (KhVoteEmp voteEmp : voteEmpList) {
                int retryCount = 0;
               /* while (true) {*/
                    voteEmp.setUpdateTime(nowDate);
                    //根据id查询数据得到之前的值
                    KhVoteEmp oldvoteEmp = khVoteEmpMapper.selectKhVoteEmpById(voteEmp.getId());
                    BigDecimal sumScore = voteEmp.getScore().add(oldvoteEmp.getVoteScore());
                    voteEmp.setVoteScore(sumScore);
                    //修改投票人数   平均分*占比=最后得分
                    voteEmp.setVoteNum(oldvoteEmp.getVoteNum().add(num));
                    voteEmp.setAvgScore(sumScore.divide(voteEmp.getVoteNum(), 4, RoundingMode.HALF_UP));
                    voteEmp.setEndScore(voteEmp.getAvgScore().multiply(oldvoteEmp.getPercentage()));
                    voteEmp.setVersion(oldvoteEmp.getVersion());
                    int result = khVoteEmpMapper.updateKhVoteEmp(voteEmp);
                    /*if (result > 0) {
                        break;
                    } else {
                        // 更新失败，版本冲突，增加重试计数
                        retryCount++;
                        if (retryCount > 3) {
                            throw new RuntimeException("重试次数过多被中断-------------");
                        }
                        System.out.println("-----------版本冲突，" + voteEmp.getBkhdxName() + "第" + retryCount + "次重试");
                        // 等待一段时间后重试，避免立即重试导致的持续冲突
                        try {
                            Thread.sleep(1000 * retryCount); // 重试间隔递增
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw new RuntimeException("重试过程异常中断-------------", e);
                        }
                    }
                }*/
            }
        } else {//单独评分    不占比   以平均分为最后得分
            for (KhVoteEmp voteEmp : voteEmpList) {
                int retryCount = 0;
               /* while (true) {*/
                    voteEmp.setUpdateTime(nowDate);
                    //根据id查询数据得到之前的值
                    KhVoteEmp oldvoteEmp = khVoteEmpMapper.selectKhVoteEmpById(voteEmp.getId());
                    BigDecimal sumScore = voteEmp.getScore().add(oldvoteEmp.getVoteScore());
                    voteEmp.setVoteNum(oldvoteEmp.getVoteNum()
                            .add(num));
                    voteEmp.setVoteScore(sumScore);
                    voteEmp.setAvgScore(sumScore.divide(voteEmp.getVoteNum(), 4, RoundingMode.HALF_UP));
                    voteEmp.setEndScore(voteEmp.getAvgScore());
                    voteEmp.setVersion(oldvoteEmp.getVersion());
                    int result = khVoteEmpMapper.updateKhVoteEmp(voteEmp);
                    /*if (result > 0) {
                        break;
                    } else {
                        // 更新失败，版本冲突，增加重试计数
                        retryCount++;
                        if (retryCount > 3) {
                            throw new RuntimeException("重试次数过多被中断-------------");
                        }
                        System.out.println("-----------版本冲突，" + voteEmp.getBkhdxName() + "第" + retryCount + "次重试");
                        // 等待一段时间后重试，避免立即重试导致的持续冲突
                        try {
                            Thread.sleep(1000 * retryCount); // 重试间隔递增
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw new RuntimeException("重试过程异常中断-------------", e);
                        }
                    }
                }*/
            }
        }

        //存储投票记录
        recard.setVoteTime(nowDate);
        if (typeid.equals(1L)) {//选项评分
            recard.setVoteDetails(JSON.toJSONString(xuanxiangDetails));
        } else {
            for (KhVoteEmp voteEmp : voteEmpList) {
                //xuanxiangDetails.put(voteEmp.getBkhdxId().toString(), voteEmp.getBkhdxName()+":"+voteEmp.getScore());
                pingFenDetails.put(voteEmp.getBkhdxName()/*+voteEmp.getBkhdxId()*/, voteEmp.getScore());
                recard.setVoteDetails(JSON.toJSONString(pingFenDetails));
            }
            /*List<String> details = voteEmpList.stream()
                    .map(emp -> emp.getBkhdxName() + " : " + emp.getScore())
                    .collect(Collectors.toList());
            recard.setVoteDetails(JSON.toJSONString(details));*/
        }
        khVoteRecardMapper.insertKhVoteRecard(recard);
        return AjaxResult.success();
    }
}
