package com.ruoyi.mall.service.impl;

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

import cn.hutool.core.map.MapUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.weixin.utils.WeiXinUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.Bo.VipCodeBO;
import com.ruoyi.mall.domain.Vo.MemberUserVO;
import com.ruoyi.mall.mapper.*;
import com.ruoyi.mall.service.IMallCountMethodService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.service.IMallMemberUserService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 用户会员Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-12
 */
@Service
public class MallMemberUserServiceImpl implements IMallMemberUserService
{
    @Resource
    private MallMemberUserMapper mallMemberUserMapper;

    @Resource
    private WeiXinUtils weiXinUtils;

    @Resource
    private MallPosterSettingMapper mallPosterSettingMapper;

    @Resource
    private TbVipCodeMapper tbVipCodeMapper;

    @Resource
    private MallSchoolAcceptMapper acceptMapper;

    @Resource
    private MallAcceptRuleMapper acceptRuleMapper;

    @Resource
    private IMallCountMethodService countMethodService;

    @Resource
    private MallMemberRateMapper rateMapper;

    @Resource
    private RedisCache redisCache;

    @Resource
    private MallSchoolBatchLinkMapper schoolBatchLinkMapper;

    @Resource
    private MallMemberRateSchoolMapper rateSchoolMapper;

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询用户会员
     *
     * @param id 用户会员主键
     * @return 用户会员
     */
    @Override
    public MallMemberUser selectMallMemberUserById(Long id)
    {
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);
        if (ObjectUtils.isNotEmpty(mallMemberUser)){
            // 查询下级人数
            Integer count = mallMemberUserMapper.selectUserCountByParentId(mallMemberUser.getId());
            mallMemberUser.setChildrenNum(count);
        }

        return mallMemberUser;
    }

    /**
     * 查询用户会员列表
     *
     * @param mallMemberUser 用户会员
     * @return 用户会员
     */
    @Override
    public List<MallMemberUser> selectMallMemberUserList(MallMemberUser mallMemberUser)
    {
        List<MallMemberUser> list = mallMemberUserMapper.selectMallMemberUserList(mallMemberUser);
        if (!list.isEmpty()){
            for (MallMemberUser memberUser : list) {
                // 查询下级人数
                Integer count = mallMemberUserMapper.selectUserCountByParentId(memberUser.getId());
                memberUser.setChildrenNum(count);
            }
        }
        return list;
    }

    /**
     * 新增用户会员
     *
     * @param mallMemberUser 用户会员
     * @return 结果
     */
    @Override
    public int insertMallMemberUser(MallMemberUser mallMemberUser)
    {
        mallMemberUser.setCreateAt(DateUtils.getTime());
        mallMemberUser.setDelFlag("0");
        return mallMemberUserMapper.insertMallMemberUser(mallMemberUser);
    }

    /**
     * 修改用户会员
     *
     * @param mallMemberUser 用户会员
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMallMemberUser(MallMemberUser mallMemberUser)
    {
        if (StringUtils.isNotBlank(mallMemberUser.getSubjectType()) && ObjectUtils.isNotEmpty(mallMemberUser.getCultureScore()) && ObjectUtils.isNotEmpty(mallMemberUser.getMajorScore())){
            String newSubjectType = mallMemberUser.getSubjectType();       // 新学科
            Integer newCultureScore = mallMemberUser.getCultureScore();  // 新文化分
            Integer newMajorScore = mallMemberUser.getMajorScore();      // 新专业分
            // 查询用户原成绩信息
            MallMemberUser oldMember = mallMemberUserMapper.selectMallMemberUserById(mallMemberUser.getId());


            if (!(null != oldMember.getSubjectType() && oldMember.getSubjectType().equals(newSubjectType)
                    && null != oldMember.getCultureScore() && oldMember.getCultureScore().equals(newCultureScore)
                    && null != oldMember.getMajorScore() && oldMember.getMajorScore().equals(newMajorScore))){
                // 学科,分数有变化,更新录取率表
                MallMemberUser user = new MallMemberUser();
                user.setId(mallMemberUser.getId());
                user.setRateFlag(0);
                mallMemberUserMapper.updateMallMemberUser(user);
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        updateRate(mallMemberUser.getId(), newCultureScore, newMajorScore);
                    }
                }).start();
            }
        }

        mallMemberUser.setUpdateAt(DateUtils.getTime());
        return mallMemberUserMapper.updateMallMemberUser(mallMemberUser);
    }
    // 更新录取率表


    @Override
    public void updateRate(Long userId, Integer cultureScore, Integer majorScore)
    {
            // 计算学生各种录取率下的成绩
            List<MallAcceptRule> rules = acceptRuleMapper.selectNewAcceptRule();
            List<Map<String, Object>> scoreList = new ArrayList<>();
            // 计算综合分
            CountDownLatch countDownLatch = new CountDownLatch(rules.size());
            try {
                for (MallAcceptRule rule : rules) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            BigDecimal totalScore = countMethodService.getTotalScore(cultureScore, majorScore, rule.getAcceptRuleId());
                            Map<String, Object> map = new HashMap<>();
                            map.put("acceptRuleId", rule.getAcceptRuleId());
                            map.put("totalScore", totalScore);
                            scoreList.add(map);
                            countDownLatch.countDown();
                        }
                    }).start();
                }
                countDownLatch.await();
            }catch (Exception e){
                e.printStackTrace();
            }

            // 查询最新所有学校专业录取数据
            List<MallMemberRate> insertRateList = new ArrayList<>();
            List<MallMemberRate> updateRateList = new ArrayList<>();

            List<MallMemberRateSchool> insertSchoolRateList = new ArrayList<>();
            List<MallMemberRateSchool> updateSchoolRateList = new ArrayList<>();

            List<MallMemberRate> allList = new ArrayList<>();  // 全部集合

            List<MallSchoolAccept> mallSchoolAccepts = acceptMapper.selectAllAcceptList();
            if (!mallSchoolAccepts.isEmpty()){
                CountDownLatch countDownLatch2 = new CountDownLatch(mallSchoolAccepts.size());
                try {
                    for (MallSchoolAccept accept : mallSchoolAccepts) {
                        Long batchId = accept.getBatchId();
                        Long linkId = accept.getLinkId();
                        Long schoolId = accept.getSchoolId();
                        String subjectType1 = accept.getSubjectType();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 个人综合分
                                List<Map<String, Object>> collect = scoreList.stream().filter(item -> ((Long)item.get("acceptRuleId")).equals(accept.getAcceptRuleId())).collect(Collectors.toList());
                                BigDecimal totalScore = new BigDecimal(MapUtil.getStr(collect.get(0), "totalScore"));
                                BigDecimal reference = accept.getReference();  // 参考分
                                BigDecimal  acceptRate = BigDecimal.ZERO;
                                Integer rateType = 0;

                                Map<String, Object> result = new HashMap<>();
                                if (accept.getAcceptRuleId() == 338){
                                    // 专科
                                    if (null != accept.getAcceptLowest() ){
                                        result = countMethodService.zhuankegetAcceptRateForReport2(accept.getAcceptLowest(), totalScore, cultureScore, majorScore);
                                    }else{
                                        result.put("acceptRate", 0);
                                        result.put("rateType", -2);
                                    }

                                }else{
                                    // 本科
                                    if (null != accept.getReference()){
                                        result = countMethodService.getAcceptRateForReport2(accept.getReference(), totalScore, cultureScore, majorScore);
                                    }else{
                                        result.put("acceptRate", 0);
                                        result.put("rateType", -2);
                                    }

                                }
                                acceptRate = new BigDecimal(MapUtil.getStr(result, "acceptRate"));
                                rateType = MapUtil.getInt(result, "rateType");

                                // 查询是否有记录
                                MallMemberRate oldRate = mallMemberUserMapper.selectRateRecordByUserId(userId,  batchId, schoolId, linkId, subjectType1);
                                if (ObjectUtils.isNotEmpty(oldRate)){
                                    if (acceptRate.compareTo(BigDecimal.ZERO) > 0){
                                        // 修改
                                        oldRate.setAcceptRate(acceptRate);
                                        oldRate.setShowAcceptRate(acceptRate + "%");
                                        oldRate.setRateType(rateType);

                                    }else{
                                        oldRate.setDelFlag(1); // 录取率等于0 删除已有记录
                                    }
                                    updateRateList.add(oldRate);

                                }else{

                                    if (acceptRate.compareTo(BigDecimal.ZERO) > 0){
                                        // 录取率不为0新增
                                        MallMemberRate memberRate = new MallMemberRate();
                                        memberRate.setUserId(userId);
                                        memberRate.setSchoolId(schoolId);
                                        memberRate.setBatchId(batchId);
                                        memberRate.setLinkId(linkId);
                                        memberRate.setSubjectType(subjectType1);
                                        memberRate.setAcceptRate(acceptRate);
                                        memberRate.setShowAcceptRate(acceptRate + "%");
                                        memberRate.setRateType(rateType);
                                        memberRate.setCreateTime(DateUtils.getNowDate());
                                        memberRate.setDelFlag(0);
                                        insertRateList.add(memberRate);
                                    }

                                }
                                countDownLatch2.countDown();
                            }
                        }).start();
                    }
                    countDownLatch2.await();
                }catch (Exception e){
                    e.printStackTrace();
                }

                if (insertRateList.size() > 0){
                    allList.addAll(insertRateList);
                }
                if (updateRateList.size() > 0){
                    allList.addAll(updateRateList);
                }
                if (allList.size() > 0){

                    // 按批次查询全部学校
                    List<MallSchoolBatchLink> schoolBatchLinkList = schoolBatchLinkMapper.selectSchoolIdByBatchId();
                    CountDownLatch countDownLatch3 = new CountDownLatch(schoolBatchLinkList.size());// 学校批次关联
                    try{
                        for (MallSchoolBatchLink schoolBatchLink : schoolBatchLinkList) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    Long schoolId = schoolBatchLink.getSchoolId();

                                    if (schoolBatchLink.getBatchId() == 2){

                                        // 本科批文科
                                        List<MallMemberRate> collect1 = allList.stream().filter(item -> item.getSchoolId().equals(schoolId) && item.getBatchId() == 2 && item.getSubjectType().equals("0") && null != item.getDelFlag() && 1 != item.getDelFlag()).collect(Collectors.toList());
                                        MallMemberRateSchool rateSchool1 = rateSchoolMapper.selectRateSchoolBySchoolIdAndBatchId(schoolId, 2L, "0", userId);
                                        if (collect1.size() > 0){
                                            collect1.sort(Comparator.comparing(MallMemberRate :: getAcceptRate));  // 排序
                                            BigDecimal schoolAcceptRate = collect1.get(0).getAcceptRate();
                                            Integer schoolRateType = collect1.get(0).getRateType();

                                            // 是否有记录
                                            if (null != rateSchool1 ){
                                                rateSchool1.setAcceptRate(schoolAcceptRate);
                                                rateSchool1.setShowAcceptRate(schoolAcceptRate + "%");
                                                rateSchool1.setRateType(schoolRateType);
                                                rateSchool1.setUpdateTime(DateUtils.getNowDate());
                                                updateSchoolRateList.add(rateSchool1);  // 修改

                                            }else{
                                                MallMemberRateSchool memberRateSchool = new MallMemberRateSchool(); // 新增
                                                memberRateSchool.setUserId(userId);
                                                memberRateSchool.setSchoolId(schoolId);
                                                memberRateSchool.setAcceptRate(schoolAcceptRate);
                                                memberRateSchool.setShowAcceptRate(schoolAcceptRate + "%");
                                                memberRateSchool.setRateType(schoolRateType);
                                                memberRateSchool.setBatchId(2L);
                                                memberRateSchool.setSubjectType("0");
                                                memberRateSchool.setCreateTime(DateUtils.getNowDate());
                                                insertSchoolRateList.add(memberRateSchool);
                                            }
                                        }else{
                                            if (null != rateSchool1){
                                                rateSchool1.setDelFlag(1);
                                                updateSchoolRateList.add(rateSchool1);
                                            }
                                        }

                                        // 本科理科
                                        List<MallMemberRate> collect2 = allList.stream().filter(item -> item.getSchoolId().equals(schoolId) && item.getBatchId() == 2 && item.getSubjectType().equals("1") && null != item.getDelFlag() && 1 != item.getDelFlag()).collect(Collectors.toList());
                                        MallMemberRateSchool rateSchool2 = rateSchoolMapper.selectRateSchoolBySchoolIdAndBatchId(schoolId, 2L, "1", userId);
                                        if (collect2.size() > 0){
                                            collect2.sort(Comparator.comparing(MallMemberRate :: getAcceptRate));  // 排序
                                            BigDecimal schoolAcceptRate = collect2.get(0).getAcceptRate();
                                            Integer schoolRateType = collect2.get(0).getRateType();

                                            // 查询是否有记录
                                            if (null != rateSchool2 ){
                                                rateSchool2.setAcceptRate(schoolAcceptRate);
                                                rateSchool2.setShowAcceptRate(schoolAcceptRate + "%");
                                                rateSchool2.setRateType(schoolRateType);
                                                rateSchool2.setUpdateTime(DateUtils.getNowDate());
                                                updateSchoolRateList.add(rateSchool2);  // 修改

                                            }else{
                                                MallMemberRateSchool memberRateSchool = new MallMemberRateSchool(); // 新增
                                                memberRateSchool.setUserId(userId);
                                                memberRateSchool.setSchoolId(schoolId);
                                                memberRateSchool.setAcceptRate(schoolAcceptRate);
                                                memberRateSchool.setShowAcceptRate(schoolAcceptRate + "%");
                                                memberRateSchool.setRateType(schoolRateType);
                                                memberRateSchool.setBatchId(2L);
                                                memberRateSchool.setSubjectType("1");
                                                memberRateSchool.setCreateTime(DateUtils.getNowDate());
                                                insertSchoolRateList.add(memberRateSchool);
                                            }
                                        }else{
                                            if (null != rateSchool2 ){
                                                rateSchool2.setDelFlag(1);
                                                updateSchoolRateList.add(rateSchool2);
                                            }
                                        }

                                    }else if (schoolBatchLink.getBatchId() == 4){
                                        // 专科批次
                                        // 专科文科
                                        List<MallMemberRate> collect3 = allList.stream().filter(item -> item.getSchoolId().equals(schoolId) && item.getBatchId() == 4 && item.getSubjectType().equals("0") && null != item.getDelFlag() && 1 != item.getDelFlag()).collect(Collectors.toList());
                                        MallMemberRateSchool rateSchool3 = rateSchoolMapper.selectRateSchoolBySchoolIdAndBatchId(schoolId, 4L, "0", userId);

                                        if (collect3.size() > 0){
                                            collect3.sort(Comparator.comparing(MallMemberRate :: getAcceptRate));  // 排序
                                            BigDecimal schoolAcceptRate = collect3.get(0).getAcceptRate();
                                            Integer schoolRateType = collect3.get(0).getRateType();
                                            // 查询是否有记录
                                            if (null != rateSchool3 ){
                                                rateSchool3.setAcceptRate(schoolAcceptRate);
                                                rateSchool3.setShowAcceptRate(schoolAcceptRate + "%");
                                                rateSchool3.setRateType(schoolRateType);
                                                rateSchool3.setUpdateTime(DateUtils.getNowDate());
                                                updateSchoolRateList.add(rateSchool3);  // 修改

                                            }else{
                                                MallMemberRateSchool memberRateSchool = new MallMemberRateSchool(); // 新增
                                                memberRateSchool.setUserId(userId);
                                                memberRateSchool.setSchoolId(schoolId);
                                                memberRateSchool.setAcceptRate(schoolAcceptRate);
                                                memberRateSchool.setShowAcceptRate(schoolAcceptRate + "%");
                                                memberRateSchool.setRateType(schoolRateType);
                                                memberRateSchool.setBatchId(4L);
                                                memberRateSchool.setSubjectType("0");
                                                memberRateSchool.setCreateTime(DateUtils.getNowDate());
                                                insertSchoolRateList.add(memberRateSchool);
                                            }
                                        }else{
                                            if (null != rateSchool3){
                                                rateSchool3.setDelFlag(1);  //  没有专业记录删除学校录取率记录
                                                updateSchoolRateList.add(rateSchool3);
                                            }

                                        }
                                        // 专科理科
                                        List<MallMemberRate> collect4 = allList.stream().filter(item -> item.getSchoolId().equals(schoolId) && item.getBatchId() == 4 && item.getSubjectType().equals("1") && null != item.getDelFlag() && 1 != item.getDelFlag()).collect(Collectors.toList());
                                        MallMemberRateSchool rateSchool4 = rateSchoolMapper.selectRateSchoolBySchoolIdAndBatchId(schoolId, 4L, "1", userId);
                                        if (collect4.size() > 0){
                                            collect4.sort(Comparator.comparing(MallMemberRate :: getAcceptRate));  // 排序
                                            BigDecimal schoolAcceptRate = collect4.get(0).getAcceptRate();
                                            Integer schoolRateType = collect4.get(0).getRateType();
                                            // 查询是否有记录
                                            if (null != rateSchool4 ){
                                                rateSchool4.setAcceptRate(schoolAcceptRate);
                                                rateSchool4.setShowAcceptRate(schoolAcceptRate + "%");
                                                rateSchool4.setRateType(schoolRateType);
                                                rateSchool4.setUpdateTime(DateUtils.getNowDate());
                                                updateSchoolRateList.add(rateSchool4);  // 修改

                                            }else{
                                                MallMemberRateSchool memberRateSchool = new MallMemberRateSchool(); // 新增
                                                memberRateSchool.setUserId(userId);
                                                memberRateSchool.setSchoolId(schoolId);
                                                memberRateSchool.setAcceptRate(schoolAcceptRate);
                                                memberRateSchool.setShowAcceptRate(schoolAcceptRate + "%");
                                                memberRateSchool.setRateType(schoolRateType);
                                                memberRateSchool.setBatchId(4L);
                                                memberRateSchool.setSubjectType("1");
                                                memberRateSchool.setCreateTime(DateUtils.getNowDate());
                                                insertSchoolRateList.add(memberRateSchool);
                                            }
                                        }else{
                                            if (null != rateSchool4){
                                                rateSchool4.setDelFlag(1);
                                                updateSchoolRateList.add(rateSchool4);
                                            }

                                        }
                                    }
                                    countDownLatch3.countDown();
                                }
                            }).start();
                        }
                        countDownLatch3.countDown();
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }

                // 批量插入和修改专业录取率
                if (insertRateList.size() > 0){
                    rateMapper.insertBatch(insertRateList);
                }
                if (updateRateList.size() > 0){
                    rateMapper.updateBatch(updateRateList);
                }

                // 批量插入修改学校录取率
                if (insertSchoolRateList.size() > 0){
                    rateSchoolMapper.insertBatch(insertSchoolRateList);
                }
                if (updateSchoolRateList.size() > 0){
                    rateSchoolMapper.updateBatch(updateSchoolRateList);
                }

                // 修改用户录取率状态
                MallMemberUser afterUser = new MallMemberUser();
                afterUser.setId(userId);
                afterUser.setRateFlag(1);
                mallMemberUserMapper.updateMallMemberUser(afterUser);
            }
        }


    /**
     * 批量删除用户会员
     *
     * @param ids 需要删除的用户会员主键
     * @return 结果
     */
    @Override
    public int deleteMallMemberUserByIds(Long[] ids)
    {
        return mallMemberUserMapper.deleteMallMemberUserByIds(ids);
    }

    /**
     * 删除用户会员信息
     *
     * @param id 用户会员主键
     * @return 结果
     */
    @Override
    public int deleteMallMemberUserById(Long id)
    {
        return mallMemberUserMapper.deleteMallMemberUserById(id);
    }

    /**
     * 根据openid用户会员信息
     *
     * @param openid
     * @return 结果
     */
    @Override
    public MallMemberUser queryByOpenid(String openid) {
        return mallMemberUserMapper.queryByOpenid(openid);
    }

    /**
     * 获取海报图片
     * @param id 用户id
     * @return 结果
     */
    @Override
    public AjaxResult getPoster(Long id) {
        // 用户信息
        MemberUserVO memberUserVO = mallMemberUserMapper.selectUserTitleInfo(id);

        String qrCode = "";
        String backImage = "";

        if (StringUtils.isBlank(memberUserVO.getQrCode())) {
            // 小程序码
            Long parentId = memberUserVO.getId();

            String key =  parentId + ".png";
            qrCode = weiXinUtils.getQRCode(parentId, key);

            MallMemberUser mallMemberUser = new MallMemberUser();
            mallMemberUser.setId(id);
            mallMemberUser.setQrCode(qrCode);
            mallMemberUserMapper.updateMallMemberUser(mallMemberUser);
        }

        qrCode = memberUserVO.getQrCode();


        // 获取海报背景图
        MallPosterSetting mallPosterSetting = mallPosterSettingMapper.selectMallPosterSetting();
        backImage = mallPosterSetting.getImage();

        Map<String , Object> result = new HashMap<>();

        result.put("memberUser", memberUserVO);
        result.put("qrCode", qrCode);
        result.put("backImage", backImage);

        return AjaxResult.success(result);
    }

    /**
     * 生成邀请码
     * @return 结果
     */
    @Override
    public String getCode() {
        Integer count = mallMemberUserMapper.selectUserCount();
        String s = String.valueOf(count + 1);
        int length1 = s.length();
        String string = "00000000";
        int length2 = string.length();
        String code = IdUtils.buildNumberCode(4) + string.substring(0, length2 - length1) + count; ;

        return code;
    }

    /**
     * 使用会员码
     * @param vipCodeBO 参数
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult useVipCode(VipCodeBO vipCodeBO) {
        Long userId = vipCodeBO.getUserId();
        String vipCode = vipCodeBO.getVipCode();

        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(userId);
        if (ObjectUtils.isEmpty(mallMemberUser)){
            return AjaxResult.error("用户信息异常");
        }
        if ( mallMemberUser.getIsOpen().equals("1")){
            return AjaxResult.error("用户已开通会员");
        }
        // 查询会员码信息
        TbVipCode tbVipCode = tbVipCodeMapper.selectTbVipCodeByVipCode(vipCode);
        if (ObjectUtils.isEmpty(tbVipCode)){
            return AjaxResult.error("会员码不存在");
        }
        if (tbVipCode.getStatus() == 1){
            return AjaxResult.error("该会员码已使用");
        }

        // 会员信息修改
        String nowTime = DateUtils.getTime();
        mallMemberUser.setIsOpen("1");
        mallMemberUser.setOpenTypeId(4L);
        mallMemberUser.setOpenTypeName("智能填报指南");
        mallMemberUser.setOpenAt(nowTime);
        mallMemberUser.setUpdateAt(nowTime);
        mallMemberUser.setUseCode(1);
        mallMemberUser.setCodeId(tbVipCode.getCodeId());
        mallMemberUser.setVipCode(vipCode);
        mallMemberUserMapper.updateMallMemberUser(mallMemberUser);

        // 会员码状态修改
        Date nowDate = DateUtils.getNowDate();
        tbVipCode.setStatus(1);
        tbVipCode.setCheckTime(nowDate);
        tbVipCode.setUpdateTime(nowDate);
        return AjaxResult.toAjax(tbVipCodeMapper.updateTbVipCode(tbVipCode));

    }

    /**
     * 生成用户录取率记录表
     */
    @Override
    public void createUserRate() {
        // 查询用户
        List<MallMemberUser> list = mallMemberUserMapper.selectMallMemberUserList(new MallMemberUser());
        // 按批次查询全部学校
        List<MallSchoolBatchLink> schoolBatchLinkList = schoolBatchLinkMapper.selectSchoolIdByBatchId();

        List<MallSchoolAccept> mallSchoolAccepts = acceptMapper.selectAllAcceptList();
        for (MallMemberUser mallMemberUser : list) {
            if (null != mallMemberUser.getCultureScore() && null != mallMemberUser.getMajorScore()){
                updateRate2(mallMemberUser.getId(), mallMemberUser.getCultureScore(),
                        mallMemberUser.getMajorScore(), schoolBatchLinkList, mallSchoolAccepts);
            }
        }
    }

    public void updateRate2(Long userId, Integer cultureScore, Integer majorScore, List<MallSchoolBatchLink> schoolBatchLinkList, List<MallSchoolAccept> mallSchoolAccepts){

        // 计算学生各种录取率下的成绩
        List<MallAcceptRule> rules = acceptRuleMapper.selectNewAcceptRule();
        List<Map<String, Object>> scoreList = new ArrayList<>();
        // 计算综合分
        CountDownLatch countDownLatch = new CountDownLatch(rules.size());
        try {
            for (MallAcceptRule rule : rules) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        BigDecimal totalScore = countMethodService.getTotalScore(cultureScore, majorScore, rule.getAcceptRuleId());
                        Map<String, Object> map = new HashMap<>();
                        map.put("acceptRuleId", rule.getAcceptRuleId());
                        map.put("totalScore", totalScore);
                        scoreList.add(map);
                        countDownLatch.countDown();
                    }
                }).start();
            }
            countDownLatch.await();
        }catch (Exception e){
            e.printStackTrace();
        }

        // 查询最新所有学校专业录取数据
        List<MallMemberRate> insertRateList = new ArrayList<>();
        List<MallMemberRate> updateRateList = new ArrayList<>();

        List<MallMemberRateSchool> insertSchoolRateList = new ArrayList<>();
        List<MallMemberRateSchool> updateSchoolRateList = new ArrayList<>();

        List<MallMemberRate> allList = new ArrayList<>();  // 全部集合


        if (!mallSchoolAccepts.isEmpty()){
            //CountDownLatch countDownLatch2 = new CountDownLatch(mallSchoolAccepts.size());
            //try {
                for (MallSchoolAccept accept : mallSchoolAccepts) {
                    Long batchId = accept.getBatchId();
                    Long linkId = accept.getLinkId();
                    Long schoolId = accept.getSchoolId();
                    String subjectType1 = accept.getSubjectType();
                    //new Thread(new Runnable() {
                    //    @Override
                    //    public void run() {
                            // 个人综合分
                            List<Map<String, Object>> collect = scoreList.stream().filter(item -> ((Long)item.get("acceptRuleId")).equals(accept.getAcceptRuleId())).collect(Collectors.toList());
                            BigDecimal totalScore = new BigDecimal(MapUtil.getStr(collect.get(0), "totalScore"));
                            BigDecimal reference = accept.getReference();  // 参考分
                            BigDecimal  acceptRate = BigDecimal.ZERO;
                            Integer rateType = 0;

                            Map<String, Object> result = new HashMap<>();
                            if (accept.getAcceptRuleId() == 338){
                                // 专科
                                if (null != accept.getAcceptLowest() ){
                                    result = countMethodService.zhuankegetAcceptRateForReport2(accept.getAcceptLowest(), totalScore, cultureScore, majorScore);
                                }else{
                                    result.put("acceptRate", 0);
                                    result.put("rateType", -2);
                                }

                            }else{
                                // 本科
                                if (null != accept.getReference()){
                                    result = countMethodService.getAcceptRateForReport2(accept.getReference(), totalScore, cultureScore, majorScore);
                                }else{
                                    result.put("acceptRate", 0);
                                    result.put("rateType", -2);
                                }

                            }
                            acceptRate = new BigDecimal(MapUtil.getStr(result, "acceptRate"));
                            rateType = MapUtil.getInt(result, "rateType");

                            // 查询是否有记录
                            MallMemberRate oldRate = mallMemberUserMapper.selectRateRecordByUserId(userId,  batchId, schoolId, linkId, subjectType1);
                            if (ObjectUtils.isNotEmpty(oldRate)){
                                if (acceptRate.compareTo(BigDecimal.ZERO) > 0){
                                    // 修改
                                    oldRate.setAcceptRate(acceptRate);
                                    oldRate.setShowAcceptRate(acceptRate + "%");
                                    oldRate.setRateType(rateType);

                                }else{
                                    oldRate.setDelFlag(1); // 录取率等于0 删除已有记录
                                }
                                updateRateList.add(oldRate);

                            }else{

                                if (acceptRate.compareTo(BigDecimal.ZERO) > 0){
                                    // 录取率不为0新增
                                    MallMemberRate memberRate = new MallMemberRate();
                                    memberRate.setUserId(userId);
                                    memberRate.setSchoolId(schoolId);
                                    memberRate.setBatchId(batchId);
                                    memberRate.setLinkId(linkId);
                                    memberRate.setSubjectType(subjectType1);
                                    memberRate.setAcceptRate(acceptRate);
                                    memberRate.setShowAcceptRate(acceptRate + "%");
                                    memberRate.setRateType(rateType);
                                    memberRate.setCreateTime(DateUtils.getNowDate());
                                    memberRate.setDelFlag(0);
                                    insertRateList.add(memberRate);
                                }

                            }
                        //    countDownLatch2.countDown();
                        //}
                    //}).start();
                }
                //countDownLatch2.await();
            //}catch (Exception e){
            //    e.printStackTrace();
            //}

            if (insertRateList.size() > 0){
                allList.addAll(insertRateList);
            }
            if (updateRateList.size() > 0){
                allList.addAll(updateRateList);
            }
            if (allList.size() > 0){


                //CountDownLatch countDownLatch3 = new CountDownLatch(schoolBatchLinkList.size());// 学校批次关联
                //try{
                    for (MallSchoolBatchLink schoolBatchLink : schoolBatchLinkList) {
                        //new Thread(new Runnable() {
                        //    @Override
                        //    public void run() {
                                Long schoolId = schoolBatchLink.getSchoolId();

                                if (schoolBatchLink.getBatchId() == 2){

                                    // 本科批文科
                                    List<MallMemberRate> collect1 = allList.stream().filter(item -> item.getSchoolId().equals(schoolId) && item.getBatchId() == 2 && item.getSubjectType().equals("0") && null != item.getDelFlag() && 1 != item.getDelFlag()).collect(Collectors.toList());
                                    MallMemberRateSchool rateSchool1 = rateSchoolMapper.selectRateSchoolBySchoolIdAndBatchId(schoolId, 2L, "0", userId);
                                    if (collect1.size() > 0){
                                        collect1.sort(Comparator.comparing(MallMemberRate :: getAcceptRate));  // 排序
                                        BigDecimal schoolAcceptRate = collect1.get(0).getAcceptRate();
                                        Integer schoolRateType = collect1.get(0).getRateType();

                                        // 是否有记录
                                        if (null != rateSchool1 ){
                                            rateSchool1.setAcceptRate(schoolAcceptRate);
                                            rateSchool1.setShowAcceptRate(schoolAcceptRate + "%");
                                            rateSchool1.setRateType(schoolRateType);
                                            rateSchool1.setUpdateTime(DateUtils.getNowDate());
                                            updateSchoolRateList.add(rateSchool1);  // 修改

                                        }else{
                                            MallMemberRateSchool memberRateSchool = new MallMemberRateSchool(); // 新增
                                            memberRateSchool.setUserId(userId);
                                            memberRateSchool.setSchoolId(schoolId);
                                            memberRateSchool.setAcceptRate(schoolAcceptRate);
                                            memberRateSchool.setShowAcceptRate(schoolAcceptRate + "%");
                                            memberRateSchool.setRateType(schoolRateType);
                                            memberRateSchool.setBatchId(2L);
                                            memberRateSchool.setSubjectType("0");
                                            memberRateSchool.setCreateTime(DateUtils.getNowDate());
                                            insertSchoolRateList.add(memberRateSchool);
                                        }
                                    }else{
                                        if (null != rateSchool1){
                                            rateSchool1.setDelFlag(1);
                                            updateSchoolRateList.add(rateSchool1);
                                        }
                                    }

                                    // 本科理科
                                    List<MallMemberRate> collect2 = allList.stream().filter(item -> item.getSchoolId().equals(schoolId) && item.getBatchId() == 2 && item.getSubjectType().equals("1") && null != item.getDelFlag() && 1 != item.getDelFlag()).collect(Collectors.toList());
                                    MallMemberRateSchool rateSchool2 = rateSchoolMapper.selectRateSchoolBySchoolIdAndBatchId(schoolId, 2L, "1", userId);
                                    if (collect2.size() > 0){
                                        collect2.sort(Comparator.comparing(MallMemberRate :: getAcceptRate));  // 排序
                                        BigDecimal schoolAcceptRate = collect2.get(0).getAcceptRate();
                                        Integer schoolRateType = collect2.get(0).getRateType();

                                        // 查询是否有记录
                                        if (null != rateSchool2 ){
                                            rateSchool2.setAcceptRate(schoolAcceptRate);
                                            rateSchool2.setShowAcceptRate(schoolAcceptRate + "%");
                                            rateSchool2.setRateType(schoolRateType);
                                            rateSchool2.setUpdateTime(DateUtils.getNowDate());
                                            updateSchoolRateList.add(rateSchool2);  // 修改

                                        }else{
                                            MallMemberRateSchool memberRateSchool = new MallMemberRateSchool(); // 新增
                                            memberRateSchool.setUserId(userId);
                                            memberRateSchool.setSchoolId(schoolId);
                                            memberRateSchool.setAcceptRate(schoolAcceptRate);
                                            memberRateSchool.setShowAcceptRate(schoolAcceptRate + "%");
                                            memberRateSchool.setRateType(schoolRateType);
                                            memberRateSchool.setBatchId(2L);
                                            memberRateSchool.setSubjectType("1");
                                            memberRateSchool.setCreateTime(DateUtils.getNowDate());
                                            insertSchoolRateList.add(memberRateSchool);
                                        }
                                    }else{
                                        if (null != rateSchool2 ){
                                            rateSchool2.setDelFlag(1);
                                            updateSchoolRateList.add(rateSchool2);
                                        }
                                    }

                                }else if (schoolBatchLink.getBatchId() == 4){
                                    // 专科批次
                                    // 专科文科
                                    List<MallMemberRate> collect3 = allList.stream().filter(item -> item.getSchoolId().equals(schoolId) && item.getBatchId() == 4 && item.getSubjectType().equals("0") && null != item.getDelFlag() && 1 != item.getDelFlag()).collect(Collectors.toList());
                                    MallMemberRateSchool rateSchool3 = rateSchoolMapper.selectRateSchoolBySchoolIdAndBatchId(schoolId, 4L, "0", userId);

                                    if (collect3.size() > 0){
                                        collect3.sort(Comparator.comparing(MallMemberRate :: getAcceptRate));  // 排序
                                        BigDecimal schoolAcceptRate = collect3.get(0).getAcceptRate();
                                        Integer schoolRateType = collect3.get(0).getRateType();
                                        // 查询是否有记录
                                        if (null != rateSchool3 ){
                                            rateSchool3.setAcceptRate(schoolAcceptRate);
                                            rateSchool3.setShowAcceptRate(schoolAcceptRate + "%");
                                            rateSchool3.setRateType(schoolRateType);
                                            rateSchool3.setUpdateTime(DateUtils.getNowDate());
                                            updateSchoolRateList.add(rateSchool3);  // 修改

                                        }else{
                                            MallMemberRateSchool memberRateSchool = new MallMemberRateSchool(); // 新增
                                            memberRateSchool.setUserId(userId);
                                            memberRateSchool.setSchoolId(schoolId);
                                            memberRateSchool.setAcceptRate(schoolAcceptRate);
                                            memberRateSchool.setShowAcceptRate(schoolAcceptRate + "%");
                                            memberRateSchool.setRateType(schoolRateType);
                                            memberRateSchool.setBatchId(4L);
                                            memberRateSchool.setSubjectType("0");
                                            memberRateSchool.setCreateTime(DateUtils.getNowDate());
                                            insertSchoolRateList.add(memberRateSchool);
                                        }
                                    }else{
                                        if (null != rateSchool3){
                                            rateSchool3.setDelFlag(1);  //  没有专业记录删除学校录取率记录
                                            updateSchoolRateList.add(rateSchool3);
                                        }

                                    }
                                    // 专科理科
                                    List<MallMemberRate> collect4 = allList.stream().filter(item -> item.getSchoolId().equals(schoolId) && item.getBatchId() == 4 && item.getSubjectType().equals("1") && null != item.getDelFlag() && 1 != item.getDelFlag()).collect(Collectors.toList());
                                    MallMemberRateSchool rateSchool4 = rateSchoolMapper.selectRateSchoolBySchoolIdAndBatchId(schoolId, 4L, "1", userId);
                                    if (collect4.size() > 0){
                                        collect4.sort(Comparator.comparing(MallMemberRate :: getAcceptRate));  // 排序
                                        BigDecimal schoolAcceptRate = collect4.get(0).getAcceptRate();
                                        Integer schoolRateType = collect4.get(0).getRateType();
                                        // 查询是否有记录
                                        if (null != rateSchool4 ){
                                            rateSchool4.setAcceptRate(schoolAcceptRate);
                                            rateSchool4.setShowAcceptRate(schoolAcceptRate + "%");
                                            rateSchool4.setRateType(schoolRateType);
                                            rateSchool4.setUpdateTime(DateUtils.getNowDate());
                                            updateSchoolRateList.add(rateSchool4);  // 修改

                                        }else{
                                            MallMemberRateSchool memberRateSchool = new MallMemberRateSchool(); // 新增
                                            memberRateSchool.setUserId(userId);
                                            memberRateSchool.setSchoolId(schoolId);
                                            memberRateSchool.setAcceptRate(schoolAcceptRate);
                                            memberRateSchool.setShowAcceptRate(schoolAcceptRate + "%");
                                            memberRateSchool.setRateType(schoolRateType);
                                            memberRateSchool.setBatchId(4L);
                                            memberRateSchool.setSubjectType("1");
                                            memberRateSchool.setCreateTime(DateUtils.getNowDate());
                                            insertSchoolRateList.add(memberRateSchool);
                                        }
                                    }else{
                                        if (null != rateSchool4){
                                            rateSchool4.setDelFlag(1);
                                            updateSchoolRateList.add(rateSchool4);
                                        }

                                    }
                                }
                        //        countDownLatch3.countDown();
                        //    }
                        //}).start();
                    }
                    //countDownLatch3.countDown();
                //}catch (Exception e){
                //    e.printStackTrace();
                //}

            }

            // 批量插入和修改专业录取率
            if (insertRateList.size() > 0){
                rateMapper.insertBatch(insertRateList);
            }
            if (updateRateList.size() > 0){
                rateMapper.updateBatch(updateRateList);
            }

            // 批量插入修改学校录取率
            if (insertSchoolRateList.size() > 0){
                rateSchoolMapper.insertBatch(insertSchoolRateList);
            }
            if (updateSchoolRateList.size() > 0){
                rateSchoolMapper.updateBatch(updateSchoolRateList);
            }

            // 修改用户录取率状态
            MallMemberUser afterUser = new MallMemberUser();
            afterUser.setId(userId);
            afterUser.setRateFlag(1);
            mallMemberUserMapper.updateMallMemberUser(afterUser);
        }
    }

    /**
     * 修改用户会员信息
     *
     * @param mallMemberUser 用户会员
     * @return 结果
     */
    @Override
    public int updateMallMemberUserInfo(MallMemberUser mallMemberUser) {
        return mallMemberUserMapper.updateMallMemberUserInfo(mallMemberUser);
    }

    /**
     * 新增系统用户
     *
     * @param mallMemberUser 用户
     * @return 结果
     */
    @Override
    public AjaxResult submitUser(MallMemberUser mallMemberUser) {
        if (mallMemberUser.getIndexPrice().compareTo(new BigDecimal(0)) < 1) {
            return AjaxResult.error("小程序邀请价需大于0");
        }


        MallMemberUser memberUser = mallMemberUserMapper.selectMallMemberUserById(mallMemberUser.getId());

        String account = mallMemberUser.getSysUserName();// 账号
        String password = mallMemberUser.getSysUserPassword();// 密码

        MallMemberUser updateMemberUser = new MallMemberUser();
        updateMemberUser.setId(mallMemberUser.getId());
        updateMemberUser.setIndexName(mallMemberUser.getIndexName());
        updateMemberUser.setIndexLogo(mallMemberUser.getIndexLogo());
        updateMemberUser.setIndexPrice(mallMemberUser.getIndexPrice());
        updateMemberUser.setSysUserName(account);
        updateMemberUser.setSysUserPassword(password);
        updateMemberUser.setSysUserStatus(mallMemberUser.getSysUserStatus());


        if (memberUser.getSysUserId() == 0 || memberUser.getSysUserId() == null) {
            MallMemberUser sysUserName = mallMemberUserMapper.selectMallMemberUserBySysUserName(account);
            // 新增
            if (sysUserName != null) {
                return AjaxResult.error("账号已存在");
            }

            // 新增系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserName(account);
            sysUser.setNickName(memberUser.getName());
            sysUser.setStatus(mallMemberUser.getSysUserStatus().toString());
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUserMapper.insertUser(sysUser);

            // 新增用户与角色管理
            List<SysUserRole> userRoleList = new ArrayList<>();
            SysUserRole ur = new SysUserRole();
            ur.setUserId(sysUser.getUserId());
            ur.setRoleId(104L);
            userRoleList.add(ur);
            sysUserRoleMapper.batchUserRole(userRoleList);

            updateMemberUser.setSysUserId(sysUser.getUserId());

        } else {
            MallMemberUser sysUserName = mallMemberUserMapper.selectMallMemberUserBySysUserName(account);
            // 修改
            if (sysUserName != null && !sysUserName.getId().equals(mallMemberUser.getId())) {
                return AjaxResult.error("账号已存在");
            }

            // 修改系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserId(memberUser.getSysUserId());
            sysUser.setUserName(account);
            sysUser.setNickName(memberUser.getName());
            sysUser.setStatus(mallMemberUser.getSysUserStatus().toString());
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUserMapper.updateUser(sysUser);
        }

        if (StringUtils.isBlank(memberUser.getIndexCode())) {
            String qrCode = "";
            // 小程序码
            Long schoolId = memberUser.getId();
            String key =  schoolId + ".png";
            qrCode = weiXinUtils.getSchoolQRCode(schoolId, key);
            updateMemberUser.setIndexCode(qrCode);
        }

        mallMemberUserMapper.updateMallMemberUserInfo(updateMemberUser);
        return AjaxResult.success();
    }

    /**
     * 查询用户会员
     *
     * @param sysUserId 系统用户ID
     * @return 用户会员
     */
    @Override
    public MallMemberUser selectMallMemberUserBySysUserId(Long sysUserId) {
        return mallMemberUserMapper.selectMallMemberUserBySysUserId(sysUserId);
    }

    /**
     * 统计-开通未开通指南人数
     *
     * @param params 参数
     * @return 统计-开通未开通指南人数
     */
    @Override
    public Map<String, Object> setIsOpenStatisticsNum(Map<String, Object> params) {
        return mallMemberUserMapper.setIsOpenStatisticsNum(params);
    }
}
