package com.ym.mec.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.DegreeRegistrationActivityDto;
import com.ym.mec.biz.dal.dto.DegreeRegistrationDto;
import com.ym.mec.biz.dal.dto.PageInfoDegree;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.*;
import com.ym.mec.biz.dal.page.DegreeQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.IdGeneratorService;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

@Service
public class DegreeRegistrationServiceImpl extends BaseServiceImpl<Integer, DegreeRegistration> implements DegreeRegistrationService {

    @Autowired
    private DegreeRegistrationDao degreeRegistrationDao;
    @Autowired
    private SporadicChargeInfoDao sporadicChargeInfoDao;
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private PayService payService;
    @Autowired
    private StudentPaymentOrderDetailDao studentPaymentOrderDetailDao;
    @Autowired
    private SysUserCashAccountService sysUserCashAccountService;

    @Override
    public BaseDAO<Integer, DegreeRegistration> getDAO() {
        return degreeRegistrationDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public HttpResponseResult pay(DegreeRegistrationActivityDto degreeRegistration) throws Exception {
        //判断用户是否已存在订单
        List<StudentPaymentOrder> paymentOrders = studentPaymentOrderService.getUserOrderByType(degreeRegistration.getUserId(), OrderTypeEnum.DEGREE_REGISTRATION, DealStatusEnum.ING);
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(paymentOrders)) {
            HttpResponseResult result = studentPaymentOrderService.checkRepeatPay(paymentOrders.get(0), degreeRegistration.getIsRepay());
            if (result.getCode() != 200) {
                return result;
            }else {
                //关闭指定订单后，处理考级明细为未支付
                StudentPaymentOrder order = paymentOrders.get(0);
                List<DegreeRegistration> degreeRegistrations = degreeRegistrationDao.findByByOrderId(order.getOrderNo());
                if(!CollectionUtils.isEmpty(degreeRegistrations)){
                    degreeRegistrations.forEach(e->e.setStatus(0));
                    degreeRegistrationDao.batchUpdate(degreeRegistrations);
                }
            }
        }
        degreeRegistration.setActivityTag(ACTIVITY_TAG);
        Date nowDate = new Date();
        String orderNo = idGeneratorService.generatorId("payment") + "";
        degreeRegistration.setOrderNo(orderNo);
        //获取收费项价格
        BigDecimal money = BigDecimal.ZERO;
        List<DegreeRegistrationDto> registrationDtos = degreeRegistration.getDegreeRegistrationDtos();
        List<DegreeRegistration> degreeRegistrationList = new ArrayList<>();
        JSONObject jsonObject = JSON.parseObject(sysConfigDao.findConfigValue("degree_theory_amount_config"));
        for (DegreeRegistrationDto registrationDto : registrationDtos) {
            DegreeRegistration degree = new DegreeRegistration();
            BeanUtils.copyProperties(degreeRegistration,degree);
            String level = registrationDto.getLevel();
            degree.setLevel(level);
            degree.setSporadicId(registrationDto.getSporadicId());
            degree.setMoney(registrationDto.getMoney());
            degree.setTheoryCert(registrationDto.getTheoryCert());
            degree.setType(registrationDto.getType());
            degree.setStatus(1);
            degree.setCreateTime(nowDate);
            degree.setUpdateTime(nowDate);
            if(Objects.nonNull(registrationDto.getSporadicId())){
                SporadicChargeInfo chargeInfo = sporadicChargeInfoDao.get(registrationDto.getSporadicId());
                if (chargeInfo == null || chargeInfo.getDelFlag().equals(1) || chargeInfo.getOpenFlag().equals(1)) {
                    throw new BizException("你选的考试级别不存在");
                }
                money = money.add(chargeInfo.getAmount());
                degree.setMoney(chargeInfo.getAmount());
            }else{
                BigDecimal theoryPrice = new BigDecimal(jsonObject.get(level.equals("一级") ? "ONE" : level.equals("二级") ? "TWO" : level.equals("三级") ? "THREE" : "FOUR").toString());
                money = money.add(theoryPrice);
                degree.setMoney(theoryPrice);
            }
            degreeRegistrationList.add(degree);
        }
        degreeRegistrationDao.batchInsert(degreeRegistrationList);

        if(money.compareTo(degreeRegistration.getPrice())!=0){
            throw new BizException("商品价格不符");
        }
        
        Integer userId = degreeRegistration.getUserId();

        String channelType = "";
        StudentPaymentOrder studentPaymentOrder = new StudentPaymentOrder();
        studentPaymentOrder.setUserId(userId);
        studentPaymentOrder.setGroupType(GroupType.SPORADIC);
        studentPaymentOrder.setOrderNo(orderNo);
        studentPaymentOrder.setType(OrderTypeEnum.DEGREE_REGISTRATION);
        studentPaymentOrder.setExpectAmount(money);
        
        if(degreeRegistration.isUseBalance()){
        	SysUserCashAccount userCashAccount = sysUserCashAccountService.getLocked(userId);
            if (userCashAccount == null) {
                throw new BizException("用户账户找不到");
            }
            BigDecimal deductBalance = BigDecimal.ZERO;
            if (userCashAccount.getBalance().subtract(money).doubleValue() >= 0) {
                // 更新订单信息
                studentPaymentOrder.setActualAmount(BigDecimal.ZERO);
                studentPaymentOrder.setBalancePaymentAmount(money);
                deductBalance = money;
                studentPaymentOrder.setPaymentChannel("BALANCE");
            } else {
                studentPaymentOrder.setActualAmount(money.subtract(userCashAccount.getBalance()));
                studentPaymentOrder.setBalancePaymentAmount(userCashAccount.getBalance());
                deductBalance = userCashAccount.getBalance();
            }
            money = money.subtract(deductBalance);
            sysUserCashAccountService.updateBalance(userId, deductBalance.negate(), PlatformCashAccountDetailTypeEnum.PAY_FEE, "考级报名");
        }else{
            studentPaymentOrder.setActualAmount(money);
            studentPaymentOrder.setBalancePaymentAmount(BigDecimal.ZERO);
        }
        studentPaymentOrder.setStatus(DealStatusEnum.ING);
        studentPaymentOrder.setClassGroupId(degreeRegistration.getId());
        String collect = degreeRegistrationList.stream().filter(e -> e.getSporadicId() != null).map(e -> e.getSporadicId().toString()).collect(Collectors.joining(","));
        if(StringUtils.isNotEmpty(collect)){
            studentPaymentOrder.setMusicGroupId(collect);
        }
        studentPaymentOrder.setOrganId(degreeRegistration.getOrganId());
        studentPaymentOrder.setRoutingOrganId(degreeRegistration.getOrganId());
        studentPaymentOrderService.insert(studentPaymentOrder);
        studentPaymentOrder.setVersion(0);

        StudentPaymentOrderDetail studentPaymentOrderDetail = new StudentPaymentOrderDetail();
        studentPaymentOrderDetail.setType(OrderDetailTypeEnum.DEGREE_REGISTRATION);
        studentPaymentOrderDetail.setPrice(money);
        studentPaymentOrderDetail.setRemitFee(BigDecimal.ZERO);
        studentPaymentOrderDetail.setPaymentOrderId(studentPaymentOrder.getId());
        studentPaymentOrderDetail.setCreateTime(nowDate);
        studentPaymentOrderDetail.setUpdateTime(nowDate);
        studentPaymentOrderDetailDao.insert(studentPaymentOrderDetail);

        if (money.compareTo(BigDecimal.ZERO) == 0) {
            Map<String, String> notifyMap = new HashMap<>();
            notifyMap.put("tradeState", "1");
            notifyMap.put("merOrderNo", studentPaymentOrder.getOrderNo());
            notifyMap.put("channelType", channelType);
            notifyMap.put("orderNo", "");
            studentPaymentOrderService.updateOrder(notifyMap);
            return BaseController.failed(HttpStatus.CREATED, notifyMap,"恭喜您,支付成功!");
        }

        String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");

        String receiver = "kjRegister";
        Map payMap = payService.getPayMap(
                money,
                BigDecimal.ZERO,
                orderNo,
                baseApiUrl + "/api-student/studentOrder/callback",
                baseApiUrl + "/api-student/studentOrder/paymentResult?orderNo=" + orderNo,
                "考级报名活动",
                "考级报名活动",
                degreeRegistration.getOrganId(),
                receiver
        );

        studentPaymentOrder.setOrganId(degreeRegistration.getOrganId());
        studentPaymentOrder.setMerNos((String) payMap.get("routingMerNos"));
        studentPaymentOrder.setPaymentChannel((String) payMap.get("type"));
        studentPaymentOrder.setUpdateTime(nowDate);
        studentPaymentOrderService.update(studentPaymentOrder);
        return BaseController.succeed(payMap);
    }
/*

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public HttpResponseResult theoryPay(DegreeRegistrationActivityDto degreeRegistration) throws Exception {
        studentDao.getLocked(degreeRegistration.getUserId());

        List<DegreeRegistration> userLevelDegrees = degreeRegistrationDao.getUserLevelDegrees(degreeRegistration.getUserId(), ACTIVITY_TAG,degreeRegistration.getDegreeType(),degreeRegistration.getSporadicId());

        long endTheoryLevelNum = userLevelDegrees.stream().filter(d -> StringUtils.isNotBlank(d.getTheoryLevel())&&d.getStatus().equals(2)).count();
        long ingTheoryLevelNum = userLevelDegrees.stream().filter(d -> StringUtils.isNotBlank(d.getTheoryLevel())&&d.getStatus().equals(1)).count();

        if(StringUtils.isNotBlank(degreeRegistration.getTheoryLevel())&&endTheoryLevelNum>0){
            throw new BizException("您已报考过选择的考级项目");
        }

        degreeRegistration.setActivityTag(ACTIVITY_TAG);

        Date nowDate = new Date();

        if(ACTIVITY_END_TIME.compareTo(nowDate)<0){
            throw new BizException("活动已截至");
        }

        String orderNo = idGeneratorService.generatorId("payment") + "";

        degreeRegistration.setMoney(BigDecimal.ZERO);

        List<String> courseInfos = new ArrayList<>();

        if("免考".equals(degreeRegistration.getTheoryLevel())){
            degreeRegistration.setTheoryLevel(null);
        }
        if(StringUtils.isNotBlank(degreeRegistration.getTheoryLevel())){
            degreeRegistration.setOrderNo(orderNo);
            BigDecimal theoryMoney = BigDecimal.ZERO;
            switch (degreeRegistration.getTheoryLevel()) {
                case "一级":
                    theoryMoney = new BigDecimal(200);
                    break;
                case "二级":
                    theoryMoney = new BigDecimal(240);
                    break;
                case "三级":
                    theoryMoney = new BigDecimal(280);
                    break;
                case "四级":
                    theoryMoney = new BigDecimal(320);
                    break;
                default:
                    throw new BizException("您选择的乐理级别不存在，请核对");
            }
            degreeRegistration.setTheoryMoney(theoryMoney);
        }else{
            degreeRegistration.setTheoryMoney(BigDecimal.ZERO);
        }

        if(Objects.nonNull(degreeRegistration.getSporadicId())||StringUtils.isNotBlank(degreeRegistration.getTheoryLevel())){
            degreeRegistration.setStatus(1);
            degreeRegistration.setCreateTime(nowDate);
            degreeRegistration.setUpdateTime(nowDate);
            degreeRegistrationDao.insert(degreeRegistration);

            List<DegreeRegistration> updateDegrees = new ArrayList<>();
            if(ingTheoryLevelNum>0){
                for (DegreeRegistration userLevelDegree : userLevelDegrees) {
                    if(Objects.nonNull(userLevelDegree.getSporadicId())&&Objects.nonNull(userLevelDegree.getSporadicId())){
                        userLevelDegree.setStatus(0);
                        updateDegrees.add(userLevelDegree);
                    }
                    if(Objects.nonNull(userLevelDegree.getTheoryLevel())&&StringUtils.isNotBlank(userLevelDegree.getTheoryLevel())){
                        userLevelDegree.setStatus(0);
                        updateDegrees.add(userLevelDegree);
                    }
                }
                if(!CollectionUtils.isEmpty(updateDegrees)){
                    degreeRegistrationDao.batchUpdate(updateDegrees);
                }
            }
        }

        BigDecimal additionCoursePrice = new BigDecimal("0");
        if(Objects.nonNull(degreeRegistration.getAdditionCourseInfo())){
            Map<CourseSchedule.CourseScheduleType, Integer> additionCourseInfo = degreeRegistration.getAdditionCourseInfo();
            PracticeGroupSellPrice practiceGroupSellPrice = practiceGroupSellPriceDao.get(degreeRegistration.getOrganId());
            if(Objects.isNull(practiceGroupSellPrice)){
                throw new BizException("该分部暂未参与此活动");
            }

            BigDecimal practiceUnitPrice = practiceGroupSellPrice.getOnceOriginalPrice(),
                    vipUnitPrice = practiceGroupSellPrice.getVipOneStudentTwelveCourseOriginalPriceWithNewUser(),
                    highUnitPrice = practiceGroupSellPrice.getHighOnlineTenCourseOriginalPriceWithNewUser();

            for (Map.Entry<CourseSchedule.CourseScheduleType, Integer> courseScheduleTypeIntegerEntry : additionCourseInfo.entrySet()) {
                BigDecimal courseTime = new BigDecimal(courseScheduleTypeIntegerEntry.getValue());
                switch (courseScheduleTypeIntegerEntry.getKey()){
                    case VIP:
                        BigDecimal vipPrice = vipUnitPrice.multiply(courseTime);
                        additionCoursePrice = additionCoursePrice.add(vipPrice);
                        courseInfos.add((courseTime.multiply(new BigDecimal(12)))+"节VIP-1V1课程费用：" + vipPrice);
                        break;
                    case PRACTICE:
                        BigDecimal practicePrice = practiceUnitPrice.multiply(courseTime);
                        additionCoursePrice = additionCoursePrice.add(practicePrice);
                        courseInfos.add((courseTime.multiply(new BigDecimal(12)))+"节1V1网管课课程费用：" + practicePrice);
                        break;
                    case HIGH:
                        BigDecimal highPrice = highUnitPrice.multiply(courseTime);
                        additionCoursePrice = additionCoursePrice.add(highPrice);
                        courseInfos.add((courseTime.multiply(new BigDecimal(10)))+"节乐理课程费用：" + highPrice);
                        break;
                }
            }
        }

        BigDecimal amount = degreeRegistration.getMoney();
        amount = amount.add(degreeRegistration.getTheoryMoney());
        amount = amount.add(additionCoursePrice);

        if(amount.compareTo(degreeRegistration.getPrice())!=0){
            throw new BizException("商品价格不符");
        }

        OrderTypeEnum type = OrderTypeEnum.DEGREE_REGISTRATION;

        Integer userId = degreeRegistration.getUserId();
        String channelType = "";
        StudentPaymentOrder studentPaymentOrder = new StudentPaymentOrder();
        studentPaymentOrder.setUserId(userId);
        studentPaymentOrder.setGroupType(GroupType.SPORADIC);
        studentPaymentOrder.setOrderNo(orderNo);
        studentPaymentOrder.setType(type);
        studentPaymentOrder.setExpectAmount(amount);
        studentPaymentOrder.setActualAmount(amount);
        studentPaymentOrder.setStatus(DealStatusEnum.ING);
        studentPaymentOrder.setClassGroupId(degreeRegistration.getId());
        if(Objects.nonNull(degreeRegistration.getSporadicId())){
            studentPaymentOrder.setMusicGroupId(degreeRegistration.getSporadicId().toString());
        }
        studentPaymentOrder.setOrganId(degreeRegistration.getOrganId());
        studentPaymentOrder.setRoutingOrganId(degreeRegistration.getOrganId());
        if (StringUtils.isNotBlank(degreeRegistration.getTheoryLevel())) {
            courseInfos.add("乐理" + degreeRegistration.getTheoryLevel() + ",费用：" + degreeRegistration.getTheoryMoney());
        }
        studentPaymentOrder.setMemo(StringUtils.join(courseInfos, "；"));
        studentPaymentOrderService.insert(studentPaymentOrder);
        studentPaymentOrder.setVersion(0);

        if(BigDecimal.ZERO.compareTo(additionCoursePrice)<0){
            StudentPaymentOrderDetail studentPaymentOrderDetail = new StudentPaymentOrderDetail();
            studentPaymentOrderDetail.setType(OrderDetailTypeEnum.DEGREE_REGISTRATION);
            if(Objects.nonNull(degreeRegistration.getAdditionCourseInfo())){
                studentPaymentOrderDetail.setGoodsIdList(JSON.toJSONString(degreeRegistration.getAdditionCourseInfo()));
            }
            studentPaymentOrderDetail.setPrice(additionCoursePrice);
            studentPaymentOrderDetail.setRemitFee(BigDecimal.ZERO);
            studentPaymentOrderDetail.setPaymentOrderId(studentPaymentOrder.getId());
            studentPaymentOrderDetail.setCreateTime(nowDate);
            studentPaymentOrderDetail.setUpdateTime(nowDate);
            studentPaymentOrderDetailDao.insert(studentPaymentOrderDetail);
        }

        if (amount.compareTo(BigDecimal.ZERO) == 0) {
            Map<String, String> notifyMap = new HashMap<>();
            notifyMap.put("tradeState", "1");
            notifyMap.put("merOrderNo", studentPaymentOrder.getOrderNo());
            notifyMap.put("channelType", channelType);
            notifyMap.put("orderNo", "");
            studentPaymentOrderService.updateOrder(notifyMap);
            return BaseController.failed(HttpStatus.CREATED, notifyMap,"恭喜您,支付成功!");
        }

        String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");

        String receiver = "kjRegister";
        Map payMap = payService.getPayMap(
                amount,
                BigDecimal.ZERO,
                orderNo,
                baseApiUrl + "/api-student/studentOrder/notify",
                baseApiUrl + "/api-student/studentOrder/paymentResult?orderNo=" + orderNo,
                "乐理考级报名活动",
                "乐理考级报名活动",
                degreeRegistration.getOrganId(),
                receiver
        );

        studentPaymentOrder.setOrganId(degreeRegistration.getOrganId());
        studentPaymentOrder.setMerNos((String) payMap.get("routingMerNos"));
        studentPaymentOrder.setPaymentChannel((String) payMap.get("type"));
        studentPaymentOrder.setUpdateTime(nowDate);
        studentPaymentOrderService.update(studentPaymentOrder);
        return BaseController.succeed(payMap);
    }*/

    @Override
    public Boolean updateStatus(StudentPaymentOrder studentPaymentOrder) {
        int updateCount = studentPaymentOrderService.update(studentPaymentOrder);
        if (updateCount <= 0) {
            throw new BizException("订单更新失败");
        }
        if(DealStatusEnum.SUCCESS.equals(studentPaymentOrder.getStatus())){
            List<StudentPaymentOrderDetail> orderDetails = studentPaymentOrderDetailDao.getOrderDetail(studentPaymentOrder.getId());
            BigDecimal additionCoursePrice = new BigDecimal(0);
            if(!CollectionUtils.isEmpty(orderDetails)){
                additionCoursePrice = orderDetails.stream().map(StudentPaymentOrderDetail::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            if(additionCoursePrice.compareTo(BigDecimal.ZERO)>0){
                sysUserCashAccountService.appendCourseBalance(studentPaymentOrder.getUserId(), additionCoursePrice, PlatformCashAccountDetailTypeEnum.RECHARGE, "2020考级报名");
            }
        }

        if (studentPaymentOrder.getStatus() == DealStatusEnum.CLOSE || studentPaymentOrder.getStatus() == DealStatusEnum.FAILED) {
            if (studentPaymentOrder.getBalancePaymentAmount() != null && studentPaymentOrder.getBalancePaymentAmount().compareTo(BigDecimal.ZERO) > 0) {
                sysUserCashAccountService.updateBalance(studentPaymentOrder.getUserId(), studentPaymentOrder.getBalancePaymentAmount(), PlatformCashAccountDetailTypeEnum.REFUNDS, "支付失败-退回");
            }
        }
        List<DegreeRegistration> degreeList = degreeRegistrationDao.getLockByOrderId(studentPaymentOrder.getOrderNo());
        Date date = new Date();
        for (DegreeRegistration degree : degreeList) {
            degree.setUpdateTime(date);
            degree.setOrderNo(studentPaymentOrder.getOrderNo());
            degree.setTransNo(studentPaymentOrder.getTransNo());
            switch (studentPaymentOrder.getStatus()){
                case SUCCESS:
                    degree.setStatus(2);
                    break;
                case FAILED:
                case CLOSE:
                    degree.setStatus(0);
                    break;
            }
        }
        if (degreeRegistrationDao.batchUpdate(degreeList) <= 0) {
            throw new BizException("更新支付状态失败");
        }
        return true;
    }

    @Override
    public PageInfoDegree<DegreeRegistration> getPageList(DegreeQueryInfo queryInfo) {
        PageInfoDegree<DegreeRegistration> pageInfo = new PageInfoDegree<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        List<DegreeRegistration> dataList = new ArrayList<>();
        int count = this.findCount(params);

        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = degreeRegistrationDao.queryPage(params);
            DegreeRegistration degree = degreeRegistrationDao.getTotalAmount(params);
//            BigDecimal totalAmount = degree.getMoney() == null ? BigDecimal.ZERO : degree.getMoney();
//            BigDecimal theoryLevelAmount = degree.getTheoryMoney() == null ? BigDecimal.ZERO : degree.getTheoryMoney();
//            BigDecimal totalAmount = subjectLevelAmount.add(theoryLevelAmount);
            pageInfo.setApplyNum(degreeRegistrationDao.countApplyNum(params));
//            pageInfo.setSubjectLevelAmount(subjectLevelAmount);
//            pageInfo.setTheoryLevelAmount(theoryLevelAmount);
            pageInfo.setTotalAmount(degree.getMoney());
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public HttpResponseResult check(DegreeRegistrationActivityDto degreeRegistration) {
        Date nowDate = new Date();
        String startTimeStr = sysConfigDao.findConfigValue(SysConfigService.DEGREE_ACTIVITY_START_TIME);
        if(StringUtils.isEmpty(startTimeStr)){
            throw new BizException("活动还未开始，谢谢关注");
        }
        Date startTime = DateUtil.stringToDate(startTimeStr);
        if (startTime.compareTo(nowDate) > 0) {
            throw new BizException("活动还未开始，谢谢关注");
        }
        String endTimeStr = sysConfigDao.findConfigValue(SysConfigService.DEGREE_ACTIVITY_END_TIME);
        if(StringUtils.isEmpty(endTimeStr)){
            throw new BizException("活动还未开始，谢谢关注");
        }
        Date endTime = DateUtil.stringToDate(endTimeStr);
        if (endTime.compareTo(nowDate) <= 0) {
            throw new BizException("活动已结束，谢谢关注");
        }
        List<DegreeRegistrationDto> registrationDtos = degreeRegistration.getDegreeRegistrationDtos();
        if(CollectionUtils.isEmpty(registrationDtos)){
            return BaseController.failed(HttpStatus.CREATED,"请选择考级项目");
        }
        List<DegreeRegistrationDto> collect = registrationDtos.stream().filter(e -> e.getType() == 1).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(collect)){
            List<Integer> collect1 = collect.stream().map(e -> e.getSporadicId()).collect(Collectors.toList());
            List<DegreeRegistration> userLevelDegrees = degreeRegistrationDao.getUserLevelDegrees(degreeRegistration.getUserId(),
                    DegreeRegistrationService.ACTIVITY_TAG,degreeRegistration.getDegreeType(),StringUtils.join(collect1,",")
                    ,null,2,degreeRegistration.getSubject());
            if(!CollectionUtils.isEmpty(userLevelDegrees)){
                return BaseController.failed(HttpStatus.CREATED, "您选择的 " + userLevelDegrees.get(0).getLevel() +  " 乐器考级已报名，请勿重复选择");
            }
        }
        collect = registrationDtos.stream().filter(e -> e.getType() == 2).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(collect)){
            List<String> collect1 = collect.stream().map(e -> e.getLevel()).collect(Collectors.toList());
            List<DegreeRegistration> userLevelDegrees = degreeRegistrationDao.getUserLevelDegrees(degreeRegistration.getUserId(),
                    DegreeRegistrationService.ACTIVITY_TAG,degreeRegistration.getDegreeType(),null,StringUtils.join(collect1,","),2,null);
            if(!CollectionUtils.isEmpty(userLevelDegrees)){
                return BaseController.failed(HttpStatus.CREATED, "您选择的 " + userLevelDegrees.get(0).getLevel() +  " 乐理考级已报名，请勿重复选择");
            }
        }
        return BaseController.succeed();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int refund(Integer degreeRegistrationId) {
        DegreeRegistration degreeRegistration = degreeRegistrationDao.getLock(degreeRegistrationId);
        if(Objects.isNull(degreeRegistration)){
            throw new BizException("报名信息不存在");
        }
        if(degreeRegistration.getStatus() != 2){
            throw new BizException("当前状态不支持退费");
        }
        StudentPaymentOrder order = studentPaymentOrderService.findOrderByOrderNo(degreeRegistration.getOrderNo());
        if(Objects.isNull(order)){
            throw new BizException("订单信息不存在");
        }
        if(order.getStatus() != DealStatusEnum.SUCCESS){
            throw new BizException("当前订单状态不支持退费");
        }
        //退到账户余额
        if(degreeRegistration.getMoney().compareTo(BigDecimal.ZERO) <= 0){
            throw new BizException("订单金额异常");
        }
        sysUserCashAccountService.updateBalance(order.getUserId(), degreeRegistration.getMoney(), PlatformCashAccountDetailTypeEnum.REFUNDS, "考级退费");
        degreeRegistration.setStatus(3);
        degreeRegistration.setUpdateTime(new Date());
        return degreeRegistrationDao.update(degreeRegistration);
    }
}
