package com.ruoyi.hezhi.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hezhi.domain.*;
import com.ruoyi.hezhi.domain.dto.ExamPayInfoDto;
import com.ruoyi.hezhi.mapper.*;
import com.ruoyi.hezhi.service.ITbMemberOrderService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * 会员订单信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-18
 */
@Service
public class TbMemberOrderServiceImpl implements ITbMemberOrderService
{
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TbMemberOrderMapper tbMemberOrderMapper;
    @Autowired
    private TbMemberScoreMapper tbMemberScoreMapper;
    @Autowired
    private TbExamRegistrationMapper tbExamRegistrationMapper;
    @Autowired
    private RedisCache redisCache;
    @Resource
    private TbConfigMapper tbConfigMapper;
    @Autowired
    private TbStudentMapper tbStudentMapper;
    @Resource
    private TbExamMapper tbExamMapper;

    /**
     * 查询会员订单信息
     *
     * @param orderId 会员订单信息主键
     * @return 会员订单信息
     */
    @Override
    public TbMemberOrder selectTbMemberOrderByOrderId(Long orderId)
    {
        return tbMemberOrderMapper.selectTbMemberOrderByOrderId(orderId);
    }

    /**
     * 查询会员订单信息列表
     *
     * @param tbMemberOrder 会员订单信息
     * @return 会员订单信息
     */
    @Override
    public List<TbMemberOrder> selectTbMemberOrderList(TbMemberOrder tbMemberOrder)
    {
        return tbMemberOrderMapper.selectTbMemberOrderList(tbMemberOrder);
    }

    /**
     * 新增会员订单信息
     *
     * @param tbMemberOrder 会员订单信息
     * @return 结果
     */
    @Override
    public int insertTbMemberOrder(TbMemberOrder tbMemberOrder)
    {
        tbMemberOrder.setCreateTime(DateUtils.getNowDate());
        return tbMemberOrderMapper.insertTbMemberOrder(tbMemberOrder);
    }

    /**
     * 修改会员订单信息
     *
     * @param tbMemberOrder 会员订单信息
     * @return 结果
     */
    @Override
    public int updateTbMemberOrder(TbMemberOrder tbMemberOrder)
    {
        tbMemberOrder.setUpdateTime(DateUtils.getNowDate());
        return tbMemberOrderMapper.updateTbMemberOrder(tbMemberOrder);
    }

    /**
     * 批量删除会员订单信息
     *
     * @param orderIds 需要删除的会员订单信息主键
     * @return 结果
     */
    @Override
    public int deleteTbMemberOrderByOrderIds(Long[] orderIds)
    {
        return tbMemberOrderMapper.deleteTbMemberOrderByOrderIds(orderIds);
    }

    /**
     * 删除会员订单信息信息
     *
     * @param orderId 会员订单信息主键
     * @return 结果
     */
    @Override
    public int deleteTbMemberOrderByOrderId(Long orderId)
    {
        return tbMemberOrderMapper.deleteTbMemberOrderByOrderId(orderId);
    }

    /**
     * 查询会员订单信息
     *
     * @param orderNo 订单编号
     * @return 会员订单信息
     */
    @Override
    public TbMemberOrder selectOrderByOrderNo(String orderNo) {
        return tbMemberOrderMapper.selectOrderByOrderNo(orderNo);
    }

    /**
     * 查询考试是否能支付的信息
     *
     * @param orderNo 订单编号
     * @return 考试是否能支付的信息
     */
    @Override
    public ExamPayInfoDto selectExamPayInfoByOrderNo(String orderNo) {
        return tbMemberOrderMapper.selectExamPayInfoByOrderNo(orderNo);
    }

    @Override
    public int deleteExamCantPayOrder(){
        // 1. 查询所有过期未支付的订单号
        List<String> orderNos = tbMemberOrderMapper.selectExpiredUnpaidOrderNos();

        if (CollectionUtils.isEmpty(orderNos)) {
            log.info("没有过期未支付的报名订单需要清理。");
            return 0;
        }

        log.info("开始清理过期未支付报名订单，数量：{}，订单号列表：{}", orderNos.size(), orderNos);

        // 2. 删除订单记录
        int deletedOrders = tbMemberOrderMapper.deleteMemberOrderByOrderNos(orderNos);
        log.info("已删除订单记录数量：{}", deletedOrders);

        // 3.将考试报名信息的支付状态改为已取消
        int updateRegistrations = tbExamRegistrationMapper.updateTbExamRegistrationByOrderNos(orderNos);
        log.info("已取消考试报名订单数量：{}", updateRegistrations);

        return deletedOrders;
    }



    /**
     * 支付回调业务处理
     * @param orderNo 订单号
     * @param payType 支付方式 （1-微信支付，2-支付宝支付）
     */
    @Override
    public String orderPayNotify(String orderNo, Integer payType) {
        TbMemberOrder order = tbMemberOrderMapper.selectOrderByOrderNo(orderNo);

        if (order.getPayStatus() != 1) {
            order.setPayStatus(1);
            order.setPayType(payType);
            order.setPayTime(DateUtils.getTime());
            tbMemberOrderMapper.updateTbMemberOrder(order);

            TbExamRegistration tbExamRegistration = tbExamRegistrationMapper.selectTbExamRegistrationByExamRegistrationId(order.getDataId());
            // 更新报名信息
            if (tbExamRegistration != null) {
                tbExamRegistration.setPayType(payType);
                tbExamRegistration.setIsPay(1);
                tbExamRegistration.setPayPrice(order.getPayPrice());
                //生成准考证号
                String examNumber =  getZkzh(tbExamRegistration);
                tbExamRegistration.setZkzh(examNumber);
                tbExamRegistrationMapper.updateTbExamRegistration(tbExamRegistration);

                //将报名信息回填入个人资料为空的字段
                TbStudent tbStudent = tbStudentMapper.selectTbStudentByStudentId(tbExamRegistration.getMemberUserId());
                //姓名、性别、学历、毕业院校、出生日期
                if (StringUtils.isEmpty(tbStudent.getStudentName())){
                    tbStudent.setStudentName(tbExamRegistration.getName());
                }
                if (tbStudent.getSex() == null|| tbStudent.getSex() == 2){
                    tbStudent.setSex(tbExamRegistration.getSex());
                }
                if (StringUtils.isEmpty(tbStudent.getEducation())){
                    tbStudent.setEducation(tbExamRegistration.getEducation());
                }
                if (StringUtils.isEmpty(tbStudent.getGraduationSchool())){
                    tbStudent.setGraduationSchool(tbExamRegistration.getGraduationSchool());
                }
                if (StringUtils.isEmpty(tbStudent.getBirthday())){
                    tbStudent.setBirthday(tbExamRegistration.getBirthday());
                }
                //更新个人资料
                tbStudentMapper.updateTbStudent(tbStudent);
            }

            if (order.getDeductionScore().compareTo(new BigDecimal(0)) > 0) {
                // 扣除积分
                TbMemberScore memberScore = new TbMemberScore();
                memberScore.setMemberUserId(order.getMemberUserId());
                memberScore.setName(order.getRemarks());
                memberScore.setScore(order.getDeductionScore());
                memberScore.setType(4);
                memberScore.setIncomeExpenses(2);
                memberScore.setCreateTime(DateUtils.getNowDate());
                tbMemberScoreMapper.insertTbMemberScore(memberScore);
            }
            TbConfig aboutIntegral = tbConfigMapper.selectTbConfigByIdentifying("aboutIntegral");

            // 每支付X元赠送1积分
            // 积分抵扣百分比
            String deductionProportionString = aboutIntegral.getConfigString3();
            //默认支付0元赠送1积分
            BigDecimal deductionProportion = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(deductionProportionString)) {
                try {
                    deductionProportion = new BigDecimal(deductionProportionString);
                    // 检查 rate 是否在有效范围内，大于0
                    if (deductionProportion.compareTo(BigDecimal.ZERO) < 0) {
                        // 如果不在有效范围内，设置为默认值
                        deductionProportion = BigDecimal.ZERO;
                        System.err.println("deductionProportion out of range: " + deductionProportion); // 记录错误信息
                    }
                } catch (NumberFormatException e) {
                    // 捕获无效数字格式，记录日志、返回默认值
                    deductionProportion = BigDecimal.ZERO;
                    System.err.println("Invalid deductionProportion format: " + deductionProportion); // 记录错误信息
                }
            }

            if (order.getPayPrice().compareTo(new BigDecimal(0)) > 0 && deductionProportion.compareTo(BigDecimal.ZERO)!= 0 ){
                //如果实付金额大于0并且正确设置了赠送比例，计算是否返积分
                //赠送积分 = 实付金额/1积分所需金额
                BigDecimal integral = order.getPayPrice().divide(deductionProportion, 0, RoundingMode.HALF_UP);
                if (integral.compareTo(new BigDecimal(0)) > 0){
                    //如果赠送积分大于0，则进行积分赠送
                    TbMemberScore memberScore = new TbMemberScore();
                    memberScore.setMemberUserId(order.getMemberUserId());
                    memberScore.setName("购买商品赠送积分");
                    memberScore.setScore(integral);
                    memberScore.setType(3);
                    memberScore.setIncomeExpenses(1);
                    memberScore.setCreateTime(DateUtils.getNowDate());
                    tbMemberScoreMapper.insertTbMemberScore(memberScore);
                }
            }
        }
        return "SUCCESS";
    }

    /**
     * 修改会员订单信息
     *
     * @param tbMemberOrder 会员订单信息
     * @return 结果
     */
    @Override
    public int updateTbMemberOrderByOrderNo(TbMemberOrder tbMemberOrder) {
        return tbMemberOrderMapper.updateTbMemberOrderByOrderNo(tbMemberOrder);
    }

    /**
     * 我的订单列表
     *
     * @param params 参数
     * @return 结果
     */
    @Override
    public List<Map<String, Object>> getMemberOrderList(Map<String, Object> params) {
        return tbMemberOrderMapper.getMemberOrderList(params);
    }

    //生成准考证号
    public String getZkzh(TbExamRegistration tbExamRegistration){
        //生成准考证号
        String redisKey = "zkzh:" + tbExamRegistration.getCourseId()+tbExamRegistration.getStudyCenterId()+tbExamRegistration.getAgencyCode();
        int number = 1;
        if (redisCache.hasKey(redisKey)) {
            //查出缓存中的数据
            Integer cachedData = redisCache.getCacheObject(redisKey);
            if (cachedData!=null) {
                number = cachedData;
                if (number > 999999) {//大于了重置，否则就生成准考证号并加1存储
                    number = 1;
                }
            }
        }
        redisCache.setCacheObject(redisKey, number+1);
        // 给number前面补0，使其总长度为6位
        String formattedNumber = String.format("%06d", number);
        return tbExamRegistration.getRegistrationBatch()+tbExamRegistration.getStudyCenterId()+tbExamRegistration.getAgencyCode()+formattedNumber;
    }
}
