package com.ruoyi.mall.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.mall.domain.MallAcceptRule;
import com.ruoyi.mall.domain.MallCountMethod;
import com.ruoyi.mall.domain.Vo.CountRuleVO;
import com.ruoyi.mall.mapper.MallAcceptRuleMapper;
import com.ruoyi.mall.mapper.MallCountMethodMapper;
import com.ruoyi.mall.service.IMallAcceptRuleService;
import com.ruoyi.mall.service.IMallCountMethodService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

/**
 * 录取原则Service业务层处理
 *
 * @author Lsm
 * @date 2023-10-18
 */
@Service
public class MallAcceptRuleServiceImpl implements IMallAcceptRuleService
{
    @Resource
    private MallAcceptRuleMapper mallAcceptRuleMapper;

    @Resource
    private MallCountMethodMapper mallCountMethodMapper;

    @Resource
    private IMallCountMethodService mallCountMethodService;

    /**
     * 查询录取原则
     *
     * @param acceptRuleId 录取原则主键
     * @return 录取原则
     */
    @Override
    public MallAcceptRule selectMallAcceptRuleByAcceptRuleId(Long acceptRuleId)
    {
        return mallAcceptRuleMapper.selectMallAcceptRuleByAcceptRuleId(acceptRuleId);
    }

    /**
     * 查询录取原则列表
     *
     * @param mallAcceptRule 录取原则
     * @return 录取原则
     */
    @Override
    public List<MallAcceptRule> selectMallAcceptRuleList(MallAcceptRule mallAcceptRule)
    {
        return mallAcceptRuleMapper.selectMallAcceptRuleList(mallAcceptRule);
    }

    /**
     * 新增录取原则
     *
     * @param mallAcceptRule 录取原则
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertMallAcceptRule(MallAcceptRule mallAcceptRule)
    {
        // 默认类型本科
        mallAcceptRule.setRuleClass(0);
        String ruleStr = mallAcceptRule.getRuleStr().replaceAll("\\s*", "");
        // 查找公式是否重复
        //MallAcceptRule acceptRule = mallAcceptRuleMapper.selectMallAcceptRuleByAcceptRule(mallAcceptRule.getRuleClass(), mallAcceptRule.getFullCulture(), mallAcceptRule.getFullMajor(), ruleStr);
        //if (ObjectUtils.isNotEmpty(acceptRule)){
        //    return AjaxResult.error("已添加同样的录取原则");
        //}

        mallAcceptRule.setCreateAt(DateUtils.getTime());
        mallAcceptRule.setDelFlag("0");
        mallAcceptRule.setIsNew(1); // 新规则
        mallAcceptRuleMapper.insertMallAcceptRule(mallAcceptRule);

        // 生成计算公式
        Map<String, String> result =  this.getRuleCountStr(mallAcceptRule.getRuleStr(), mallAcceptRule.getAcceptRuleId());

        mallAcceptRule.setRuleCountStr(mallAcceptRule.getRuleStr());
        mallAcceptRule.setChangeRate(new BigDecimal(result.get("changeRate")));
        mallAcceptRuleMapper.updateMallAcceptRule(mallAcceptRule);

        // 计算满分
        BigDecimal fullScore = mallCountMethodService.getTotalScore(mallAcceptRule.getFullCulture(), mallAcceptRule.getFullMajor(), mallAcceptRule.getAcceptRuleId());
        mallAcceptRule.setFullScore(fullScore);
        return AjaxResult.toAjax(mallAcceptRuleMapper.updateMallAcceptRule(mallAcceptRule));

    }

    /**
     * 录取原则 生成 投档公式
     * @param ruleStr 录取原则
     * @return 结果
     */
    public Map<String, String> getRuleCountStr(String ruleStr, Long acceptRuleId){
        // 去除空格
        String strTrim = ruleStr.replaceAll("\\s*", "");
        String[] split = strTrim.split("\\+");

        if (split.length == 1){
            if (split[0].contains("文化")){
                strTrim = strTrim + "+联考*0";
            }else if (split[0].contains("联考")){
                strTrim = "文化*0+" + strTrim;
            }
            split = strTrim.split("\\+");
        }
        String nowTime = DateUtils.getTime();

        BigDecimal cultureCount = BigDecimal.ONE;
        BigDecimal majorCount = BigDecimal.ONE;

        BigDecimal changeRate = BigDecimal.ZERO;
        String ruleCountStr = "";

            if (!split[0].contains("文化排序")){
                // 文化分段
                if (split[0].length() > 3) {
                    String cultureStr = split[0].substring(3).trim();
                    int length = cultureStr.length();
                    List<MallCountMethod> list = new ArrayList<>();
                    for (int i = 0; i < length; i++) {

                        if (cultureStr.charAt(i) == '*') {
                            MallCountMethod mallCountMethod = new MallCountMethod();
                            mallCountMethod.setAcceptRuleId(acceptRuleId);
                            mallCountMethod.setCountMode(0);
                            mallCountMethod.setCreateAt(nowTime);
                            mallCountMethod.setDelFlag("0");
                            // 记录乘法
                            mallCountMethod.setCountType(0);
                            // 记录字符串中的下标
                            mallCountMethod.setSort(i);
                            list.add(mallCountMethod);
                        } else if (cultureStr.charAt(i) == '/') {
                            MallCountMethod mallCountMethod = new MallCountMethod();
                            mallCountMethod.setAcceptRuleId(acceptRuleId);
                            mallCountMethod.setCountMode(0);
                            mallCountMethod.setCreateAt(nowTime);
                            mallCountMethod.setDelFlag("0");
                            // 记录除法
                            mallCountMethod.setCountType(1);
                            // 记录字符串中的下标
                            mallCountMethod.setSort(i);
                            list.add(mallCountMethod);
                        }

                    }
                    if (list.size() > 0) {
                        int size = list.size();
                        for (int i = 0; i < size; i++) {
                            if (i == list.size() - 1) {
                                String substring = cultureStr.substring(list.get(i).getSort() + 1);
                                list.get(i).setCountValue(new BigDecimal(substring));
                            } else {
                                String substring = cultureStr.substring(list.get(i).getSort() + 1, list.get(i + 1).getSort());
                                list.get(i).setCountValue(new BigDecimal(substring));
                            }

                            //mallCountMethodMapper.insertMallCountMethod(list.get(i));
                        }

                        List<MallCountMethod> collect1 = list.stream().filter(item -> item.getCountType() == 0).collect(Collectors.toList());
                        List<MallCountMethod> collect2 = list.stream().filter(item -> item.getCountType() == 1).collect(Collectors.toList());
                        if (collect1.size() > 0) {
                            // 乘法
                            for (MallCountMethod mallCountMethod : collect1) {
                                cultureCount = cultureCount.multiply(mallCountMethod.getCountValue());
                            }
                        }

                        if (collect2.size() > 0) {
                            BigDecimal temp = BigDecimal.ONE;
                            // 除法
                            for (MallCountMethod mallCountMethod : collect2) {
                                temp = temp.multiply(mallCountMethod.getCountValue());
                            }
                            cultureCount = cultureCount.divide(temp, 2, RoundingMode.HALF_UP);
                        }
                    }
                }
            }else {
                MallCountMethod mallCountMethod = new MallCountMethod();
                mallCountMethod.setAcceptRuleId(acceptRuleId);
                mallCountMethod.setCountMode(0);
                mallCountMethod.setCountType(0);
                mallCountMethod.setCountValue(BigDecimal.ONE);
                mallCountMethod.setCreateAt(nowTime);
                mallCountMethod.setDelFlag("0");
                //mallCountMethodMapper.insertMallCountMethod(mallCountMethod);
            }

            if(split[1].length() > 2){
                // 专业分段
                String majorStr = split[1].substring(2).trim();
                int length = majorStr.length();
                List<MallCountMethod> list = new ArrayList<>();
                for (int i = 0; i < length; i++) {


                    if (majorStr.charAt(i) == '*'){
                        MallCountMethod mallCountMethod = new MallCountMethod();
                        mallCountMethod.setAcceptRuleId(acceptRuleId);
                        mallCountMethod.setCountMode(1);
                        mallCountMethod.setCreateAt(nowTime);
                        mallCountMethod.setDelFlag("0");
                        // 记录乘法
                        mallCountMethod.setCountType(0);
                        // 记录字符串中的下标
                        mallCountMethod.setSort(i);
                        list.add(mallCountMethod);

                    }else if( majorStr.charAt(i) == '/'){
                        MallCountMethod mallCountMethod = new MallCountMethod();
                        mallCountMethod.setAcceptRuleId(acceptRuleId);
                        mallCountMethod.setCountMode(1);
                        mallCountMethod.setCreateAt(nowTime);
                        mallCountMethod.setDelFlag("0");
                        // 记录除法
                        mallCountMethod.setCountType(1);
                        // 记录字符串中的下标
                        mallCountMethod.setSort(i);
                        list.add(mallCountMethod);
                    }

                }
                if (list.size() > 0){
                    int size = list.size();
                    for (int i = 0; i < size; i++) {
                        if (i == list.size() -1){
                            String substring = majorStr.substring(list.get(i).getSort() + 1);
                            list.get(i).setCountValue(new BigDecimal(substring));
                        }else{
                            String substring = majorStr.substring(list.get(i).getSort() + 1, list.get(i + 1).getSort());
                            list.get(i).setCountValue(new BigDecimal(substring));
                        }

                        //mallCountMethodMapper.insertMallCountMethod(list.get(i));
                    }

                    List<MallCountMethod> collect1 = list.stream().filter(item -> item.getCountType() == 0).collect(Collectors.toList());
                    List<MallCountMethod> collect2 = list.stream().filter(item -> item.getCountType() == 1).collect(Collectors.toList());
                    if (collect1.size() > 0){
                        // 乘法
                        for (MallCountMethod mallCountMethod : collect1) {
                            majorCount = majorCount.multiply(mallCountMethod.getCountValue());
                        }
                    }

                    if (collect2.size() > 0){
                        BigDecimal temp = BigDecimal.ONE;
                        // 除法
                        for (MallCountMethod mallCountMethod : collect2) {
                            temp = temp.multiply(mallCountMethod.getCountValue());
                        }
                        majorCount = majorCount.divide(temp, 2, RoundingMode.HALF_UP);
                    }
                }
            }else{
                MallCountMethod mallCountMethod = new MallCountMethod();
                mallCountMethod.setAcceptRuleId(acceptRuleId);
                mallCountMethod.setCountMode(1);
                mallCountMethod.setCountType(0);
                mallCountMethod.setCountValue(BigDecimal.ONE);
                mallCountMethod.setCreateAt(nowTime);
                mallCountMethod.setDelFlag("0");
                //mallCountMethodMapper.insertMallCountMethod(mallCountMethod);
            }
            if (cultureCount.compareTo(BigDecimal.ZERO) > 0){
                // 联考转换系数
                changeRate = majorCount.divide(cultureCount, 2, RoundingMode.HALF_UP);

            }else{
                changeRate = new BigDecimal("10");
            }

            // 生成计算方法
            MallCountMethod mallCountMethod1 = new MallCountMethod(); // 文化分部分
            mallCountMethod1.setAcceptRuleId(acceptRuleId);
            mallCountMethod1.setCountMode(0);
            mallCountMethod1.setCountType(0);
            mallCountMethod1.setCountValue(cultureCount);
            mallCountMethod1.setCreateAt(nowTime);
            mallCountMethod1.setDelFlag("0");
            mallCountMethod1.setSort(0);
            mallCountMethodService.insertMallCountMethod(mallCountMethod1);

            MallCountMethod mallCountMethod2 = new MallCountMethod(); // 联考分部分
            mallCountMethod2.setAcceptRuleId(acceptRuleId);
            mallCountMethod2.setCountMode(1);
            mallCountMethod2.setCountType(0);
            mallCountMethod2.setCountValue(majorCount);
            mallCountMethod2.setCreateAt(nowTime);
            mallCountMethod2.setDelFlag("0");
            mallCountMethod2.setSort(1);
            mallCountMethodService.insertMallCountMethod(mallCountMethod2);

        //// 拼接计算公式
        //String cultureStr = "";
        //String majorStr = "";
        //if (cultureCount.compareTo(BigDecimal.ZERO) > 0 ){
        //    if (cultureCount.compareTo(BigDecimal.ONE) == 0) {
        //        cultureStr = "文化";
        //    }else {
        //        if(cultureCount.setScale(2, RoundingMode.HALF_UP).compareTo(BigDecimal.ZERO) == 0){
        //            cultureStr = "文化*" + cultureCount.setScale(4, RoundingMode.HALF_UP);
        //        }else{
        //            cultureStr = "文化*" + cultureCount.setScale(2, RoundingMode.HALF_UP);
        //        }
        //
        //    }
        //}
        //
        //if (majorCount.compareTo(BigDecimal.ZERO) > 0){
        //    if (majorCount.compareTo(BigDecimal.ONE) == 0){
        //        majorStr = "联考";
        //    }else{
        //        if (majorCount.setScale(2, RoundingMode.HALF_UP).compareTo(BigDecimal.ZERO) == 0){
        //            majorStr = "联考*" + majorCount.setScale(4, RoundingMode.HALF_UP);
        //        }else{
        //            majorStr = "联考*" + majorCount.setScale(2, RoundingMode.HALF_UP);
        //        }
        //
        //    }
        //}



        Map<String, String> result = new HashMap<>();
        result.put("changeRate", changeRate.toString());
        return result;
    }

    /**
     * 修改录取原则
     *
     * @param mallAcceptRule 录取原则
     * @return 结果
     */
    @Override
    public int updateMallAcceptRule(MallAcceptRule mallAcceptRule)
    {
        return mallAcceptRuleMapper.updateMallAcceptRule(mallAcceptRule);
    }

    /**
     * 批量删除录取原则
     *
     * @param acceptRuleIds 需要删除的录取原则主键
     * @return 结果
     */
    @Override
    public int deleteMallAcceptRuleByAcceptRuleIds(Long[] acceptRuleIds)
    {
        return mallAcceptRuleMapper.deleteMallAcceptRuleByAcceptRuleIds(acceptRuleIds);
    }

    /**
     * 删除录取原则信息
     *
     * @param acceptRuleId 录取原则主键
     * @return 结果
     */
    @Override
    public int deleteMallAcceptRuleByAcceptRuleId(Long acceptRuleId)
    {
        return mallAcceptRuleMapper.deleteMallAcceptRuleByAcceptRuleId(acceptRuleId);
    }

    /**
     * 后台录取规则列表
     * @param ruleClass 类别(0-本科,1-专科)
     * @return 结果
     */
    @Override
    public List<CountRuleVO> selectNewAcceptRuleList(Long ruleClass) {
        return mallAcceptRuleMapper.selectNewAcceptRuleList(ruleClass);
    }
}
