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

import static com.ym.mec.biz.dal.enums.CouponDetailTypeEnum.MEMBER;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import com.ym.mec.biz.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 com.alibaba.fastjson.JSONArray;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.ActivityUserMapperDao;
import com.ym.mec.biz.dal.dao.MemberRankPrivilegesDao;
import com.ym.mec.biz.dal.dao.MemberRankSettingDao;
import com.ym.mec.biz.dal.dao.StudentPaymentOrderDetailDao;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dao.TempBuyFreeLiveTheoryCourseDao;
import com.ym.mec.biz.dal.dao.TempLittleArtistTrainingCampUserRelationDao;
import com.ym.mec.biz.dal.dao.VipGroupActivityDao;
import com.ym.mec.biz.dal.dto.Cloud2022ActivityDto;
import com.ym.mec.biz.dal.dto.MemberPayParamDto;
import com.ym.mec.biz.dal.entity.ActivityUserMapper;
import com.ym.mec.biz.dal.entity.CloudCoachPaymentProgram;
import com.ym.mec.biz.dal.entity.CloudTeacherOrder;
import com.ym.mec.biz.dal.entity.MemberRankPrivileges;
import com.ym.mec.biz.dal.entity.MemberRankSetting;
import com.ym.mec.biz.dal.entity.Student;
import com.ym.mec.biz.dal.entity.StudentCloudCoachPaymentDetails;
import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
import com.ym.mec.biz.dal.entity.StudentPaymentOrderDetail;
import com.ym.mec.biz.dal.entity.SysUserCashAccount;
import com.ym.mec.biz.dal.entity.TempBuyFreeLiveTheoryCourse;
import com.ym.mec.biz.dal.entity.TempLittleArtistTrainingCampUserRelation;
import com.ym.mec.biz.dal.entity.VipGroupActivity;
import com.ym.mec.biz.dal.enums.CouponDetailTypeEnum;
import com.ym.mec.biz.dal.enums.CourseViewTypeEnum;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.dal.enums.OrderDetailTypeEnum;
import com.ym.mec.biz.dal.enums.OrderTypeEnum;
import com.ym.mec.biz.dal.enums.PeriodEnum;
import com.ym.mec.biz.dal.enums.PlatformCashAccountDetailTypeEnum;
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.thirdparty.adapay.Payment;
import com.ym.mec.thirdparty.adapay.entity.HfMerchantConfig;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.http.HttpUtil;

@Service
public class MemberRankSettingServiceImpl extends BaseServiceImpl<Integer, MemberRankSetting> implements MemberRankSettingService {

    @Autowired
    private MemberRankSettingDao memberRankSettingDao;
    @Autowired
    private MemberRankPrivilegesDao memberRankPrivilegesDao;
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private SysUserCashAccountService sysUserCashAccountService;
    @Autowired
    private SysUserCashAccountDetailService sysUserCashAccountDetailService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private CloudTeacherOrderService cloudTeacherOrderService;
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private SysCouponCodeService sysCouponCodeService;
    @Autowired
    private StudentCloudCoachPaymentDetailsService studentCloudCoachPaymentDetailsService;
    @Autowired
    private CloudCoachPaymentProgramService cloudCoachPaymentProgramService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private VipGroupActivityDao vipGroupActivityDao;
    @Autowired
    private TenantConfigService tenantConfigService;
    @Autowired
    private ActivityUserMapperService activityUserMapperService;
    @Autowired
    private MemberFeeSettingService memberFeeSettingService;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private LiveGoodsService liveGoodsService;
    @Autowired
    private TempBuyFreeLiveTheoryCourseDao tempBuyFreeLiveTheoryCourseDao;
    @Autowired
    private TempLittleArtistTrainingCampUserRelationDao tempLittleArtistTrainingCampUserRelationDao;
    @Autowired
    private StudentPaymentOrderDetailDao studentPaymentOrderDetailDao;
    
    @Autowired
    private HfMerchantConfigService hfMerchantConfigService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public BaseDAO<Integer, MemberRankSetting> getDAO() {
        return memberRankSettingDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(MemberRankSetting memberRankSetting) {
        memberRankSettingDao.insert(memberRankSetting);
        List<Integer> memberPrivilegesItemIdList = memberRankSetting.getMemberPrivilegesItemIdList();
        if (memberPrivilegesItemIdList == null || memberPrivilegesItemIdList.size() == 0) {
            throw new BizException("操作失败：请配置会员权益");
        }
        memberRankPrivilegesDao.batchInsert(memberRankSetting.getId(), memberPrivilegesItemIdList);
    }

    @Override
    public MemberRankSetting getDetail(Integer memberRankSettingId) {
        MemberRankSetting memberRankSetting = memberRankSettingDao.get(memberRankSettingId);
        List<MemberRankPrivileges> byRankSettingId = memberRankPrivilegesDao.findByRankSettingId(memberRankSettingId);
        if (byRankSettingId != null && byRankSettingId.size() > 0) {
            memberRankSetting.setMemberRankPrivileges(byRankSettingId);
            memberRankSetting.setMemberPrivilegesItemIdList(byRankSettingId.stream().map(e -> e.getMemberPrivilegesId()).collect(Collectors.toList()));
        }
        return memberRankSetting;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSetting(MemberRankSetting memberRankSetting) {
        memberRankSettingDao.update(memberRankSetting);
        memberRankPrivilegesDao.deleteByRankSettingId(memberRankSetting.getId());
        List<Integer> memberPrivilegesItemIdList = memberRankSetting.getMemberPrivilegesItemIdList();
        if (memberPrivilegesItemIdList != null && memberPrivilegesItemIdList.size() > 0) {
            memberRankPrivilegesDao.batchInsert(memberRankSetting.getId(), memberPrivilegesItemIdList);
        }
    }

    @Override
    public List<MemberRankSetting> queryListByIsDefault(Boolean isDefault) {
        return memberRankSettingDao.queryListByIsDefault(isDefault);
    }

    //原有购买会员支付接口  思路：分部等于59的时候 修改计算时间的地方 按齐齐哈尔的来
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult buy(MemberPayParamDto memberPayParamDto) throws Exception {
        logger.info("云教练购买:memberPayParamDto:{} ", memberPayParamDto);
        Long paymentId = memberPayParamDto.getPaymentId();
        CloudCoachPaymentProgram cloudCoachPaymentProgram = cloudCoachPaymentProgramService.get(paymentId);
        if (cloudCoachPaymentProgram == null) {
            throw new BizException("云教练缴费订单不存在，请联系指导老师");
        }
        if (cloudCoachPaymentProgram.getStatus() != CloudCoachPaymentProgram.StatusEnum.OPEN) {
            throw new BizException("当前云教练缴费订单状态不允许缴费");
        }
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        StudentCloudCoachPaymentDetails cloudCoachPaymentDetails = studentCloudCoachPaymentDetailsService.findByUserId(paymentId, sysUser.getId());
        if (cloudCoachPaymentDetails == null) {
            throw new BizException("您不在当前云教练缴费项目中，请联系指导老师");
        }
        if (cloudCoachPaymentDetails.getPaymentStatus() == 1) {
            throw new BizException("当前云教练订单已支付，感谢您的支持");
        }
        //判断用户是否已存在订单
        List<StudentPaymentOrder> applyOrderList = studentPaymentOrderService.queryByDealStatus(paymentId.toString(), OrderTypeEnum.MEMBER, DealStatusEnum.ING);
        if (CollectionUtils.isNotEmpty(applyOrderList)) {
            HttpResponseResult result = studentPaymentOrderService.checkRepeatPay(applyOrderList.get(0), memberPayParamDto.getRepeatPay());
            if (result.getCode() != 200) {
                return result;
            }
        }

        Integer userId = cloudCoachPaymentDetails.getUserId();
        Student student = studentService.getLocked(userId);
        if (student == null) {
            throw new BizException("非法访问");
        }
        SysUser user = teacherDao.getUser(userId);
        Integer organId = user.getOrganId();
        if (organId == null) {
            throw new BizException("学生没有分部编号");
        }
        BigDecimal actualAmount = cloudCoachPaymentProgram.getActualAmount();
        //优惠券使用范围
        String[] checkCoupon = CouponDetailTypeEnum.getAllowType(MEMBER);
        //校验优惠券
        StudentPaymentOrder studentPaymentOrder = sysCouponCodeService.use(memberPayParamDto.getCouponIdList(), actualAmount, true, checkCoupon);
        studentPaymentOrder.setUserId(userId);
        studentPaymentOrder.setOrganId(organId);
        studentPaymentOrder.setMusicGroupId(paymentId.toString());
        studentPaymentOrder.setMemo(cloudCoachPaymentProgram.getRemark());
        studentPaymentOrder.setGroupType(GroupType.MEMBER);
        Map<String, Object> result = getMap(memberPayParamDto.getAmount(), memberPayParamDto.getUseBalancePayment(),studentPaymentOrder);
        return BaseController.succeed(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult buy1(MemberPayParamDto memberPayParamDto) throws Exception {
        logger.info("云教练购买:memberPayParamDto:{} ", memberPayParamDto);
        SysUser sysUser = Optional.ofNullable(sysUserFeignService.queryUserInfo()).orElseThrow(() -> new BizException("用户信息不存在"));
        //判断用户是否已存在订单
        StudentPaymentOrder memberIngOrder = studentPaymentOrderService.getMemberIngOrder(OrderTypeEnum.MEMBER, DealStatusEnum.ING);
        if (Objects.nonNull(memberIngOrder)) {
            HttpResponseResult result = studentPaymentOrderService.checkRepeatPay(memberIngOrder, memberPayParamDto.getRepeatPay());
            if (result.getCode() != 200) {
                return result;
            }
        }
        //获取团练宝价格
        BigDecimal actualAmount = memberFeeSettingService.getAmount(sysUser.getOrganId(),1,
                memberPayParamDto.getPeriodEnum(),new BigDecimal(1),
                MemberFeeSettingServiceImpl::getCurrentFee);
        //优惠券使用范围
        String[] checkCoupon = CouponDetailTypeEnum.getAllowType(MEMBER);
        //校验优惠券
        StudentPaymentOrder studentPaymentOrder = sysCouponCodeService.use(memberPayParamDto.getCouponIdList(), actualAmount, true, checkCoupon);
        studentPaymentOrder.setUserId(sysUser.getId());
        studentPaymentOrder.setOrganId(sysUser.getOrganId());
        studentPaymentOrder.setMemo("学员云教练购买");
        studentPaymentOrder.setGroupType(GroupType.MEMBER);
        Map<String, Object> result = getMap(memberPayParamDto.getAmount(), memberPayParamDto.getUseBalancePayment(),studentPaymentOrder);
        //生产团练宝订单
        CloudTeacherOrder cloudTeacherOrder = new CloudTeacherOrder();
        cloudTeacherOrder.setOrderId(studentPaymentOrder.getId());
        cloudTeacherOrder.setLevel(1);
        cloudTeacherOrder.setStatus(0);
        cloudTeacherOrder.setType(memberPayParamDto.getPeriodEnum());
        cloudTeacherOrder.setTime(1);
        cloudTeacherOrder.setStudentId(sysUser.getId());
        cloudTeacherOrder.setOrganId(studentPaymentOrder.getOrganId());
        cloudTeacherOrder.setAmount(studentPaymentOrder.getExpectAmount());
        cloudTeacherOrderService.insert(cloudTeacherOrder);
        return BaseController.succeed(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    public HttpResponseResult activeBuy(MemberPayParamDto memberPayParamDto) throws Exception {
        SysUser sysUser = Optional.ofNullable(sysUserFeignService.queryUserInfo()).orElseThrow(()-> new BizException("请登录"));
        Student student = studentService.getLocked(sysUser.getId());
        String activeConfig = sysConfigDao.findConfigValue("cloud_teacher_active_config");
        List<Cloud2022ActivityDto> cloud2022ActivityDtos = JSONArray.parseArray(activeConfig, Cloud2022ActivityDto.class);
        List<Cloud2022ActivityDto> activityDtos = cloud2022ActivityDtos.stream().
                filter(e -> Arrays.stream(e.getOrganId().split(",")).collect(Collectors.toList()).
                        contains(sysUser.getOrganId().toString())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(activityDtos)){
            throw new BizException("当前分部暂未开通活动");
        }
        logger.error("activeBuy params goodsId: {},liveId: {}",memberPayParamDto.getLiveGoodsId(),memberPayParamDto.getLiveId());
        BigDecimal amount = BigDecimal.ZERO;
        Integer activityId = null;
        //判断当前商品是否可以购买（库存、上架状态、是否购买过）
        //如果是云教练商品，那么只能购买一次、如果是免费直播课，那么每次上架只能买一次，总共只能买2次
        if(memberPayParamDto.getLiveGoodsId() == 1 || memberPayParamDto.getLiveGoodsId() == 5){
            //判断用户是否已存在订单
            List<StudentPaymentOrder> memberIngOrders = studentPaymentOrderService.queryByCondition(GroupType.LIVE_BUY,null,student.getUserId(), DealStatusEnum.ING,OrderTypeEnum.LIVE_BUY);
            if (CollectionUtils.isNotEmpty(memberIngOrders)) {
                HttpResponseResult result = studentPaymentOrderService.checkRepeatPay(memberIngOrders.get(0), memberPayParamDto.getRepeatPay());
                if (result.getCode() != 200) {
                    return result;
                }
                //还原库存
                liveGoodsService.addGoodsStock(memberPayParamDto.getLiveGoodsId(),memberPayParamDto.getLiveId());
            }
            if(memberPayParamDto.getLiveGoodsId() == 1){
                activityId = Integer.parseInt(activityDtos.get(0).getActivityId());
            }else {
                activityId = Integer.parseInt(activityDtos.get(1).getActivityId());
            }
            //是否还有购买资格
            VipGroupActivity vipGroupActivity = Optional.ofNullable(vipGroupActivityDao.get(activityId)).orElseThrow(()-> new BizException("活动不存在"));
            if(vipGroupActivity.getStudentMaxUsedTimes() != -1){
                //获取活动购买次数
                int activityBuyNum = activityUserMapperService.countActivityBuyNum(vipGroupActivity.getId(),sysUser.getId());
                if(activityBuyNum >= vipGroupActivity.getStudentMaxUsedTimes()){
                    throw new BizException("您已达到购买次数上限");
                }
            }
            amount = vipGroupActivity.getMarketPrice();
            //扣减库存
            liveGoodsService.reduceGoodsStock(memberPayParamDto.getLiveGoodsId(),memberPayParamDto.getLiveId());
        } else if (memberPayParamDto.getLiveGoodsId() == 2 || memberPayParamDto.getLiveGoodsId() == 3 || memberPayParamDto.getLiveGoodsId() == 4){
            TempBuyFreeLiveTheoryCourse temp = tempBuyFreeLiveTheoryCourseDao.findByGoodsIdAndUserId(memberPayParamDto.getLiveGoodsId(),student.getUserId());
            if(Objects.nonNull(temp)){
                throw new BizException("您已领取过本轮免费直播课");
            }
//            StringBuffer sb = new StringBuffer(RedisKeyConstant.LIVE_GOODS_ZERO_CACHE_KEY).append(memberPayParamDto.getLiveGoodsId());
//            RBucket<List<Integer>> bucket = redissonClient.getBucket(sb.toString());
//            List<Integer> list = bucket.get();
//            if(CollectionUtils.isEmpty(list)){
//                list = new ArrayList<>();
//            }
//            //当前用户是否购买过免费直播课
//            if(list.contains(sysUser.getId())){
//                throw new BizException("您已领取过本轮免费直播课");
//            }
            //购买次数是否超过2次
//            int count = tempBuyFreeLiveTheoryCourseDao.countByUserId(sysUser.getId());
//            if(count >= 2){
//                throw new BizException("免费直播课已达到领取次数上限");
//            }
            //保存购买记录
            tempBuyFreeLiveTheoryCourseDao.insert(
                    new TempBuyFreeLiveTheoryCourse(sysUser.getId(),memberPayParamDto.getLiveId(),memberPayParamDto.getLiveGoodsId()));
            //扣减库存
            liveGoodsService.reduceGoodsStock(memberPayParamDto.getLiveGoodsId(),memberPayParamDto.getLiveId());
//            list.add(sysUser.getId());
//            bucket.set(list);
            return BaseController.succeed();
        }else {
            throw new BizException("当前商品不可购买");
        }
        //优惠券使用范围
        String[] checkCoupon = CouponDetailTypeEnum.getAllowType(MEMBER);
        //校验优惠券
        StudentPaymentOrder studentPaymentOrder = sysCouponCodeService.use(memberPayParamDto.getCouponIdList(),amount, true, checkCoupon);
        studentPaymentOrder.setUserId(sysUser.getId());
        studentPaymentOrder.setOrganId(sysUser.getOrganId());
        studentPaymentOrder.setMemo("小小训练营云教练购买");
        studentPaymentOrder.setGroupType(GroupType.LIVE_BUY);
        studentPaymentOrder.setType(OrderTypeEnum.LIVE_BUY);
        studentPaymentOrder.setActivityId(activityId.toString());
        studentPaymentOrder.setActivityBuyNum(1);
        studentPaymentOrder.setMusicGroupId(memberPayParamDto.getLiveId());
        //保存商品编号
        studentPaymentOrder.setClassGroupId(memberPayParamDto.getLiveGoodsId());
        Map<String, Object> result = getMap(memberPayParamDto.getAmount(), memberPayParamDto.getUseBalancePayment(),studentPaymentOrder);
        return BaseController.succeed(result);
    }

    @Override
    public HttpResponseResult<Integer> checkActiveBuy(MemberPayParamDto memberPayParamDto) {
        SysUser sysUser = Optional.ofNullable(sysUserFeignService.queryUserInfo()).orElseThrow(()-> new BizException("请登录"));
        //判断当前商品是否可以购买（库存、上架状态、是否购买过）
        //如果是云教练商品，那么只能购买一次、如果是免费直播课，那么每次上架只能买一次，总共只能买2次
        HttpResponseResult<Integer> succeed = BaseController.succeed(0);
        String activeConfig = sysConfigDao.findConfigValue("cloud_teacher_active_config");
        List<Cloud2022ActivityDto> cloud2022ActivityDtos = JSONArray.parseArray(activeConfig, Cloud2022ActivityDto.class);
        List<Cloud2022ActivityDto> activityDtos = cloud2022ActivityDtos.stream().
                filter(e -> Arrays.stream(e.getOrganId().split(",")).collect(Collectors.toList()).contains(sysUser.getOrganId().toString())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(activityDtos)){
            succeed.setMsg("当前分部暂未开通活动");
            return succeed;
        }
        if(memberPayParamDto.getLiveGoodsId() == 1 || memberPayParamDto.getLiveGoodsId() == 5){
            //是否还有购买资格
            Integer activityId = Integer.parseInt(activityDtos.get(0).getActivityId());
            if(memberPayParamDto.getLiveGoodsId() == 5){
                activityId = Integer.parseInt(activityDtos.get(1).getActivityId());
            }
            VipGroupActivity vipGroupActivity = Optional.ofNullable(vipGroupActivityDao.get(activityId)).orElseThrow(()-> new BizException("活动不存在"));
            if(vipGroupActivity.getStudentMaxUsedTimes() != -1){
                //获取活动购买次数
                int activityBuyNum = activityUserMapperService.countActivityBuyNum(vipGroupActivity.getId(),sysUser.getId());
                if(activityBuyNum >= vipGroupActivity.getStudentMaxUsedTimes()){
                    succeed.setMsg("您已达到购买次数上限");
                    return succeed;
                }
            }
        } else if (memberPayParamDto.getLiveGoodsId() == 2 || memberPayParamDto.getLiveGoodsId() == 3 || memberPayParamDto.getLiveGoodsId() == 4){
            TempBuyFreeLiveTheoryCourse temp = tempBuyFreeLiveTheoryCourseDao.findByGoodsIdAndUserId(memberPayParamDto.getLiveGoodsId(),sysUser.getId());
            if(Objects.nonNull(temp)){
                succeed.setMsg("您已领取过本轮免费直播课");
                return succeed;
            }
//            StringBuffer sb = new StringBuffer(RedisKeyConstant.LIVE_GOODS_ZERO_CACHE_KEY).append(memberPayParamDto.getLiveGoodsId());
//            RBucket<List<Integer>> bucket = redissonClient.getBucket(sb.toString());
//            List<Integer> list = bucket.get();
//            if(CollectionUtils.isEmpty(list)){
//                list = new ArrayList<>();
//            }
//            //当前用户是否购买过免费直播课
//            if(list.contains(sysUser.getId())){
//                succeed.setMsg("您已领取过本轮免费直播课");
//                return succeed;
//            }
            //购买次数是否超过2次
//            int count = tempBuyFreeLiveTheoryCourseDao.countByUserId(sysUser.getId());
//            if(count >= 2){
//                succeed.setMsg("免费直播课已达到领取次数上限");
//                return succeed;
//            }
        }else {
            succeed.setMsg("当前商品不可购买");
            return succeed;
        }
        return BaseController.succeed(1);
    }

    public static final String BUY_2_QQHE_LOCK = "BUY_2_QQHE_LOCK:";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult buy2Qqhe(MemberPayParamDto dto) throws Exception {
        //获取学员信息
        SysUser sysUser = getSysUser();
        if (!dto.getRepeatPay()) {
            //查询是否有待支付订单
            List<StudentPaymentOrder> studentPaymentOrders = studentPaymentOrderService.queryByCondition(GroupType.MEMBER,
                    null, sysUser.getId(), DealStatusEnum.ING, OrderTypeEnum.MEMBER);
            if (CollectionUtils.isNotEmpty(studentPaymentOrders)) {
                return BaseController.failed(HttpStatus.CONTINUE, studentPaymentOrders.get(0), "您有待支付的订单,是否继续支付");
            }
        }

        //重新支付 需要传入订单号 并关闭订单  退余额 退优惠券
        if (dto.getRepeatPay() && StringUtils.isNotBlank(dto.getOrderNo())) {
            StudentPaymentOrder studentPaymentOrder = Optional.ofNullable(dto.getOrderNo())
                    .map(studentPaymentOrderService::findOrderByOrderNo)
                    .orElseThrow(() -> new BizException("未查询到继续支付的订单！"));
            if (studentPaymentOrder.getStatus().getCode().equals(DealStatusEnum.ING.getCode())) {
                checkOrder(studentPaymentOrder);
                //关闭订单  退余额 退优惠券
                studentPaymentOrderService.quitCouponAndBalance(studentPaymentOrder);
                //将订单关闭
                studentPaymentOrder.setStatus(DealStatusEnum.CLOSE);
                studentPaymentOrder.setUpdateTime(new Date());
                studentPaymentOrderService.update(studentPaymentOrder);
                //从缓存取出上次传入参数
                RBucket<Object> cache = redissonClient.getBucket(BUY_2_QQHE_LOCK + studentPaymentOrder.getOrderNo());
                if (!cache.isExists()) {
                    return BaseController.failed("订单超时，请重新购买！");
                }
                Map<String, Object> cacheMap = (Map<String, Object>) cache.get();
                dto = (MemberPayParamDto) cacheMap.get("dto");
            } else if (studentPaymentOrder.getStatus().getCode().equals(DealStatusEnum.SUCCESS.getCode())) {
                return BaseController.failed("该订单已支付成功！");
            } else {
                return BaseController.failed("该订单已关闭，请重新购买！");
            }
        }

        int val = dto.getVal();
        //获取赠送的月份
        BigDecimal giveMonth = getGiveMonth(val);
        //转换格式
        BigDecimal valDecimal = new BigDecimal(val);
        //获取单价
        BigDecimal price = Optional.ofNullable("qqhe_2022_buy_member_activity_amount")
                .map(sysConfigDao::findConfigValue)
                .filter(StringUtils::isNotBlank)
                .map(BigDecimal::new)
                .orElseThrow(() -> new BizException("未配置活动单价，请联系教务老师。"));
        //计算出购买的价格 单价 X 购买的月份
        BigDecimal amount = price.multiply(valDecimal);
        //获取会员总激活时间
        BigDecimal totalMonth = valDecimal.add(giveMonth);
        //使用优惠券 设置优惠券使用范围
        StudentPaymentOrder studentPaymentOrder = sysCouponCodeService.use(dto.getCouponIdList(), amount, true, CouponDetailTypeEnum.getAllowType(MEMBER));
        //写入redis证明是活动购买
        String orderNo = idGeneratorService.generatorId("payment") + "";
        RBucket<Object> cache = redissonClient.getBucket(BUY_2_QQHE_LOCK + orderNo);
        Map<String, Object> cacheMap = new HashMap<>();
        cacheMap.put("totalMonth", totalMonth);
        cacheMap.put("dto", dto);
        cache.set(cacheMap, 40, TimeUnit.MINUTES);
        //创建订单
        studentPaymentOrder.setOrderNo(orderNo);
        studentPaymentOrder.setUserId(sysUser.getId());
        studentPaymentOrder.setOrganId(sysUser.getOrganId());
        studentPaymentOrder.setGroupType(GroupType.MEMBER);
        studentPaymentOrder.setMemo("团练宝购买");
        Map<String, Object> result = getMap(dto.getAmount(), dto.getUseBalancePayment(),studentPaymentOrder);
        return BaseController.succeed(result);
    }

    /**
     * 查询是否有订单待支付
     */
    @Override
    public HttpResponseResult queryBuy2Qqhe() {
        SysUser sysUser = getSysUser();
        List<StudentPaymentOrder> studentPaymentOrders = studentPaymentOrderService.queryByCondition(GroupType.MEMBER,
                null, sysUser.getId(), DealStatusEnum.ING, OrderTypeEnum.MEMBER);
        if (CollectionUtils.isEmpty(studentPaymentOrders)) {
            return BaseController.succeed();
        }
        return BaseController.succeed(studentPaymentOrders.get(0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult closeBuy2Qqhe(String orderNo) throws Exception {
        StudentPaymentOrder orderByOrderNo = studentPaymentOrderService.findOrderByOrderNo(orderNo);
        if (Objects.isNull(orderByOrderNo)) {
            logger.info("closeBuy2Qqhe>>>>> 未找到 orderNo {}", orderNo);
            return BaseController.succeed();
        }
        //订单是ing 才可以关闭
        if (orderByOrderNo.getStatus().getCode().equals(DealStatusEnum.ING.getCode())) {
            //有第三方支付编号的 要主动去查询一下
            checkOrder(orderByOrderNo);
            //关闭订单  退余额 退优惠券
            studentPaymentOrderService.quitCouponAndBalance(orderByOrderNo);
            //将订单关闭
            orderByOrderNo.setStatus(DealStatusEnum.CLOSE);
            orderByOrderNo.setUpdateTime(new Date());
            studentPaymentOrderService.update(orderByOrderNo);
            return BaseController.succeed();
        } else if (orderByOrderNo.getStatus().getCode().equals(DealStatusEnum.SUCCESS.getCode())) {
            throw new BizException("该订单已经支付成功，无法关闭。");
        }
        return BaseController.succeed();
    }

    //检查订单在第三方是否支付成功
    private void checkOrder(StudentPaymentOrder orderByOrderNo) throws Exception {
        if (StringUtils.isNotBlank(orderByOrderNo.getTransNo())) {

            HfMerchantConfig hfMerchantConfig = hfMerchantConfigService.queryByTenantId(orderByOrderNo.getTenantId());
            if(hfMerchantConfig == null){
            	throw new BizException("机构[{}]汇付商户信息找不到", orderByOrderNo.getTenantId());
            }
            
            Map<String, Object> payment = Payment.queryPayment(orderByOrderNo.getTransNo(), hfMerchantConfig.getMerKey());
            String status = (String) payment.get("status");
            if (status.equals("succeeded")) {
                throw new BizException("该订单已经支付成功，无法关闭。");
            }
        }
    }

    private SysUser getSysUser() {
        Optional<SysUser> sysUserOpt = Optional.ofNullable(sysUserFeignService.queryUserInfo());
        sysUserOpt.filter(s -> s.getOrganId() == 59).orElseThrow(() -> new BizException("该分部无此活动"));
        SysUser sysUser = sysUserOpt.orElseThrow(() -> new BizException("未查询到学生信息，请重新登录！"));
        sysUserOpt.map(SysUser::getId)
                .map(studentService::getLocked)
                .orElseThrow(() -> new BizException("非法访问"));
        return sysUser;
    }

    private BigDecimal getGiveMonth(int val) {
        if (val < 0) {
            throw new BizException("最少购买1个月！");
        }
        if (val > 12) {
            throw new BizException("最多购买12个月！");
        }
        BigDecimal giveMonth;
        //最小数o  最大数s
        BiPredicate<Integer, Integer> predicate = (o, s) -> val >= o && val < s;
        if (predicate.test(2, 4)) {
            //购买2到4(不包含)之间月赠送1个月
            giveMonth = BigDecimal.ONE;
        } else if (predicate.test(4, 6)) {
            //购买4到6(不包含)之间月赠送1个月
            giveMonth = new BigDecimal("3");
        } else if (val >= 6) {
            //购买6(包含)个月以上送6个月
            giveMonth = new BigDecimal("6");
        } else {
            //默认不赠送
            giveMonth = BigDecimal.ZERO;
        }
        return giveMonth;
    }

    //写入支付数据
    private Map<String, Object> getMap(BigDecimal amount, Boolean UseBalance,StudentPaymentOrder studentPaymentOrder) throws Exception {
        Date date = new Date();
        BigDecimal actualAmount = studentPaymentOrder.getActualAmount();
        studentPaymentOrder.setRoutingOrganId(studentPaymentOrder.getOrganId());
        studentPaymentOrder.setCreateTime(date);
        studentPaymentOrder.setUpdateTime(date);
        studentPaymentOrder.setBalancePaymentAmount(BigDecimal.ZERO);
        studentPaymentOrder.setStatus(DealStatusEnum.ING);
        studentPaymentOrder.setVersion(0);
        if (studentPaymentOrder.getType() == null){
            studentPaymentOrder.setType(OrderTypeEnum.MEMBER);
        }
        studentPaymentOrder.setRemitFee(BigDecimal.ZERO);
        studentPaymentOrder.setCourseRemitFee(BigDecimal.ZERO);
        studentPaymentOrder.setPaymentChannel("BALANCE");
        // 判断金额是否正确
        if (actualAmount.compareTo(amount) != 0) {
            throw new BizException("非法请求");
        }
        //使用余额支付
        if (UseBalance) {
            useBalanceAmount(studentPaymentOrder, "购买会员");
        }
        if (StringUtils.isBlank(studentPaymentOrder.getOrderNo())) {
            String orderNo = idGeneratorService.generatorId("payment") + "";
            studentPaymentOrder.setOrderNo(orderNo);
        }
        studentPaymentOrder.setCreateTime(date);
        studentPaymentOrder.setUpdateTime(date);
        studentPaymentOrder.setVersion(0);
        studentPaymentOrderService.insert(studentPaymentOrder);
        Map<String, Object> result = studentPaymentOrderService.createOrder(studentPaymentOrder, null, "BUY_MEMBER");
        return result;
    }

    public void useBalanceAmount(StudentPaymentOrder studentPaymentOrder, String memo) {
        Integer userId = studentPaymentOrder.getUserId();
        SysUserCashAccount userCashAccount = sysUserCashAccountService.getLocked(userId);
        if (userCashAccount == null) {
            throw new BizException("用户账户找不到");
        }
        BigDecimal actualAmount = studentPaymentOrder.getActualAmount();
        studentPaymentOrder.setPaymentChannel("BALANCE");
        if (userCashAccount.getBalance().subtract(actualAmount).doubleValue() >= 0) {
            studentPaymentOrder.setActualAmount(BigDecimal.ZERO);
            studentPaymentOrder.setBalancePaymentAmount(actualAmount);
            sysUserCashAccountService.updateBalance(userId, actualAmount.negate(), PlatformCashAccountDetailTypeEnum.PAY_FEE, memo);

        } else {
            if (userCashAccount.getBalance().doubleValue() > 0) {
                sysUserCashAccountService.updateBalance(userId, userCashAccount.getBalance().negate(), PlatformCashAccountDetailTypeEnum.PAY_FEE, memo);
                studentPaymentOrder.setBalancePaymentAmount(userCashAccount.getBalance());
                studentPaymentOrder.setActualAmount(studentPaymentOrder.getExpectAmount().subtract(userCashAccount.getBalance()));
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public boolean liveBuyOrderCallback(StudentPaymentOrder studentPaymentOrder) {
        //查询原定的是否已处理
        StudentPaymentOrder orignStudentPaymentOrder = studentPaymentOrderService.lockOrder(studentPaymentOrder.getId());
        if (orignStudentPaymentOrder == null) {
            return false;
        }
        if (orignStudentPaymentOrder.getStatus() != DealStatusEnum.ING) {
            return false;
        }
        Integer userId = studentPaymentOrder.getUserId();
        Date nowDate = new Date();
        // 更新订单信息
        studentPaymentOrder.setUpdateTime(nowDate);
        studentPaymentOrderService.update(studentPaymentOrder);

        if (studentPaymentOrder.getStatus() == DealStatusEnum.CLOSE || studentPaymentOrder.getStatus() == DealStatusEnum.FAILED) {
            //退还优惠券和余额
            studentPaymentOrderService.returnBalanceAndCoupon(studentPaymentOrder, "直播购买云教练支付失败");
            if(Objects.nonNull(studentPaymentOrder.getActivityId())){
                //还原库存
                liveGoodsService.addGoodsStock(1,null);
            }
            return true;
        }

        // 支付成功
        if (studentPaymentOrder.getStatus() == DealStatusEnum.SUCCESS) {
            Student student = studentService.get(userId);
            VipGroupActivity activity = vipGroupActivityDao.get(Integer.parseInt(studentPaymentOrder.getActivityId()));
            //保存团练宝数据
            CloudTeacherOrder cloudTeacherOrder = new CloudTeacherOrder();
            cloudTeacherOrder.setOrderId(studentPaymentOrder.getId());
            cloudTeacherOrder.setLevel(1);
            cloudTeacherOrder.setStatus(1);
            cloudTeacherOrder.setType(activity.getPeriodEnum());
            cloudTeacherOrder.setTime(studentPaymentOrder.getActivityBuyNum());
            cloudTeacherOrder.setStudentId(studentPaymentOrder.getUserId());
            cloudTeacherOrder.setOrganId(studentPaymentOrder.getOrganId());
            cloudTeacherOrder.setAmount(studentPaymentOrder.getExpectAmount());
            cloudTeacherOrderService.save(cloudTeacherOrder,tenantConfigService.autoActivationFlag(cloudTeacherOrder.getTenantId()));
            //赠送陪练课
            ActivityUserMapper activityUserMapper = new ActivityUserMapper();
            activityUserMapper.setTeacherId(student.getTeacherId());
            activityUserMapper.setPaymentOrderId(studentPaymentOrder.getId());
            activityUserMapper.setUserId(studentPaymentOrder.getUserId());
            activityUserMapper.setActivityId(activity.getId());
            activityUserMapper.setActualPrice(BigDecimal.ZERO);
            activityUserMapper.setSubNoCoursePrice(BigDecimal.ZERO);
            activityUserMapper.setReturnFee(false);
            //如果是买的商品1那么赠送陪练课和训练营
            if(Objects.equals(studentPaymentOrder.getClassGroupId(),1)){
                //赠送陪练课
                activityUserMapper.setGivePracticeFlag(1);
                activityUserMapperService.copyProperty(activityUserMapper,activity,true,false);
                //赠送训练营
                TempLittleArtistTrainingCampUserRelation tempLittleArtistTrainingCamp = new TempLittleArtistTrainingCampUserRelation();
                tempLittleArtistTrainingCamp.setUserId(studentPaymentOrder.getUserId());
                tempLittleArtistTrainingCamp.setState("NOT_APPLY");
                tempLittleArtistTrainingCamp.setCreateTime(nowDate);
                tempLittleArtistTrainingCampUserRelationDao.insert(tempLittleArtistTrainingCamp);
            }
            activityUserMapperService.insert(activityUserMapper);
            //生成订单详情
            StudentPaymentOrderDetail studentPaymentOrderDetail = new StudentPaymentOrderDetail();
            studentPaymentOrderDetail.setPaymentOrderId(studentPaymentOrder.getId());
            studentPaymentOrderDetail.setType(OrderDetailTypeEnum.CLOUD_TEACHER);
            studentPaymentOrderDetail.setGoodsIdList(studentPaymentOrder.getClassGroupId().toString());
            studentPaymentOrderDetail.setPrice(studentPaymentOrder.getExpectAmount());
            studentPaymentOrderDetail.setRemitFee(studentPaymentOrder.getCouponRemitFee());
            studentPaymentOrderDetail.setTenantId(studentPaymentOrder.getTenantId());
            studentPaymentOrderDetail.setCreateTime(nowDate);
            studentPaymentOrderDetail.setUpdateTime(nowDate);
            studentPaymentOrderDetailDao.insert(studentPaymentOrderDetail);

            if(Objects.equals(studentPaymentOrder.getClassGroupId(),1)) {
                Map<Integer, String> phoneMaps = MapUtil.convertMybatisMap(teacherDao.queryPhoneByIds(userId.toString()));
                String baseApiUrl = sysConfigDao.findConfigValue(SysConfigService.BASE_API_URL);
                StringBuffer pushUrl = new StringBuffer(baseApiUrl).append("/#/artistRegistration");
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.GOOD_HABITS_TRAINING_CAMP_EXPERIENCE_QUALIFICATION_SMS, phoneMaps,
                        null, 0, "", null, HttpUtil.getSortUrl(pushUrl.toString()));

                StringBuffer notifyUrl = new StringBuffer("8?").append(baseApiUrl).append("/#/artistRegistration");
                Map<Integer, String> userIdMaps = new HashMap<>(1);
                userIdMaps.put(userId, userId.toString());
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.GOOD_HABITS_TRAINING_CAMP_EXPERIENCE_QUALIFICATION_PUSH, userIdMaps,
                        null, 0, notifyUrl.toString(), "STUDENT");
            }
        }
        // 插入交易明细
        sysUserCashAccountDetailService.saveSysUserCashAccountDetail(studentPaymentOrder, "直播购买云教练");
        try {
            contractService.transferProduceContract(userId, null,null);
        } catch (Exception e) {
            logger.error("产品协议生成失败", e);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public boolean orderCallback(StudentPaymentOrder studentPaymentOrder) {
        //查询原定的是否已处理
        StudentPaymentOrder orignStudentPaymentOrder = studentPaymentOrderService.lockOrder(studentPaymentOrder.getId());
        if (orignStudentPaymentOrder == null) {
            return false;
        }
        if (orignStudentPaymentOrder.getStatus() != DealStatusEnum.ING) {
            return false;
        }
        Integer userId = studentPaymentOrder.getUserId();
        Date nowDate = new Date();
        // 更新订单信息
        studentPaymentOrder.setUpdateTime(nowDate);
        studentPaymentOrderService.update(studentPaymentOrder);

        if (studentPaymentOrder.getStatus() == DealStatusEnum.CLOSE || studentPaymentOrder.getStatus() == DealStatusEnum.FAILED) {
            //退还优惠券和余额
            studentPaymentOrderService.returnBalanceAndCoupon(studentPaymentOrder, "购买会员支付失败");
            if(Objects.nonNull(studentPaymentOrder.getActivityId())){
                //还原库存
                liveGoodsService.addGoodsStock(1,null);
            }
            return true;
        }

        // 支付成功
        if (studentPaymentOrder.getStatus() == DealStatusEnum.SUCCESS) {
            //是否通过活动购买的团练宝
            if(Objects.nonNull(studentPaymentOrder.getActivityId())){
//                Student student = studentService.get(userId);
                VipGroupActivity activity = vipGroupActivityDao.get(Integer.parseInt(studentPaymentOrder.getActivityId()));
                //保存团练宝数据
                CloudTeacherOrder cloudTeacherOrder = new CloudTeacherOrder();
                cloudTeacherOrder.setOrderId(studentPaymentOrder.getId());
                cloudTeacherOrder.setLevel(1);
                cloudTeacherOrder.setStatus(1);
                cloudTeacherOrder.setType(activity.getPeriodEnum());
                cloudTeacherOrder.setTime(studentPaymentOrder.getActivityBuyNum());
                cloudTeacherOrder.setStudentId(studentPaymentOrder.getUserId());
                cloudTeacherOrder.setOrganId(studentPaymentOrder.getOrganId());
                cloudTeacherOrder.setAmount(studentPaymentOrder.getExpectAmount());
                cloudTeacherOrderService.save(cloudTeacherOrder,tenantConfigService.autoActivationFlag(cloudTeacherOrder.getTenantId()));
                //赠送陪练课
//                ActivityUserMapper activityUserMapper = new ActivityUserMapper();
//                activityUserMapper.setTeacherId(student.getTeacherId());
//                activityUserMapper.setPaymentOrderId(studentPaymentOrder.getId());
//                activityUserMapper.setUserId(studentPaymentOrder.getUserId());
//                activityUserMapper.setActivityId(activity.getId());
//                activityUserMapper.setActualPrice(BigDecimal.ZERO);
//                activityUserMapper.setGivePracticeFlag(1);
//                activityUserMapper.setReturnFee(false);
//                activityUserMapperDao.insert(activityUserMapper);
                //赠送训练营
//                TempLittleArtistTrainingCampUserRelation tempLittleArtistTrainingCamp = new TempLittleArtistTrainingCampUserRelation();
//                tempLittleArtistTrainingCamp.setUserId(studentPaymentOrder.getUserId());
//                tempLittleArtistTrainingCamp.setState("NOT_APPLY");
//                tempLittleArtistTrainingCamp.setCreateTime(nowDate);
//                tempLittleArtistTrainingCampUserRelationDao.insert(tempLittleArtistTrainingCamp);
                //生成订单详情
//                StudentPaymentOrderDetail studentPaymentOrderDetail = new StudentPaymentOrderDetail();
//                studentPaymentOrderDetail.setPaymentOrderId(studentPaymentOrder.getId());
//                studentPaymentOrderDetail.setType(OrderDetailTypeEnum.CLOUD_TEACHER);
//                studentPaymentOrderDetail.setGoodsIdList("1");
//                studentPaymentOrderDetail.setPrice(studentPaymentOrder.getExpectAmount());
//                studentPaymentOrderDetail.setTenantId(studentPaymentOrder.getTenantId());
//                studentPaymentOrderDetail.setCreateTime(nowDate);
//                studentPaymentOrderDetail.setUpdateTime(nowDate);
//                studentPaymentOrderDetailDao.insert(studentPaymentOrderDetail);
                //赠送优惠券
//                Integer giveCouponId = activity.getGiveCouponId();
//                Integer giveCouponNum = activity.getGiveCouponNum();
//                if(Objects.nonNull(giveCouponId) && Objects.nonNull(giveCouponNum)){
//                    sysCouponCodeService.exchangeCoupon(userId,giveCouponId,
//                            studentPaymentOrder.getId(),giveCouponNum,2,null);
//                }
                Map<Integer, String> phoneMaps = MapUtil.convertMybatisMap(teacherDao.queryPhoneByIds(userId.toString()));
                String baseApiUrl = sysConfigDao.findConfigValue(SysConfigService.BASE_API_URL);
                StringBuffer pushUrl = new StringBuffer(baseApiUrl).append("/#/artistRegistration");
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.GOOD_HABITS_TRAINING_CAMP_EXPERIENCE_QUALIFICATION_SMS,phoneMaps,
                        null,0,"",null, HttpUtil.getSortUrl(pushUrl.toString()));

                StringBuffer notifyUrl = new StringBuffer("8?").append(baseApiUrl).append("/#/artistRegistration");
                Map<Integer, String> userIdMaps = new HashMap<>(1);
                userIdMaps.put(userId, userId.toString());
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.GOOD_HABITS_TRAINING_CAMP_EXPERIENCE_QUALIFICATION_PUSH,userIdMaps,
                        null,0,notifyUrl.toString(),"STUDENT");
            }else {
                //齐齐哈尔购买成功默认激活
                // 活动时间:
                // 1. 2022年2月8日上线预热
                // 2. 2022年2月15日开始销售
                // 3. 暂无结束时间，长期有效
                //查询redis证明是活动购买
                RBucket<Object> cache = redissonClient.getBucket(BUY_2_QQHE_LOCK + studentPaymentOrder.getOrderNo());
                //查询活动时间
                String activityDateStr = sysConfigDao.findConfigValue("qqhe_2022_buy_member_activity");
                //获取活动时间
                Date activityDate = DateUtil.stringToDate(activityDateStr, DateUtil.EXPANDED_DATE_TIME_FORMAT);
                SysUser sysUser = teacherDao.getUser(userId);
                logger.info("orderCallback >>> member param organId {}   orderTime {} activityDate {}  cache {}", sysUser.getOrganId(), studentPaymentOrder.getCreateTime(), activityDate, cache.isExists());
                //分部编号59 并且下单时间大于等于activityDateStr  todo 并且redis能查询到的就算齐齐哈尔活动购买的
                if (sysUser.getOrganId() == 59 && studentPaymentOrder.getCreateTime().after(activityDate) && cache.isExists()) {
                    //齐齐哈尔会员活动
                    Student student = studentService.get(userId);
                    qqheMemberActivity(studentPaymentOrder, student, sysUser, cache);
                    //删除标记
                    cache.delete();
                } else {
                    if(StringUtils.isNotEmpty(studentPaymentOrder.getMusicGroupId())){
                        CloudCoachPaymentProgram cloudCoachPaymentProgram = cloudCoachPaymentProgramService.get(Long.parseLong(studentPaymentOrder.getMusicGroupId()));
                        StudentCloudCoachPaymentDetails coachPaymentDetails = studentCloudCoachPaymentDetailsService.findByUserId(cloudCoachPaymentProgram.getId(), studentPaymentOrder.getUserId());
                        //保存团练宝数据
                        CloudTeacherOrder cloudTeacherOrder = new CloudTeacherOrder();
                        cloudTeacherOrder.setOrderId(studentPaymentOrder.getId());
                        cloudTeacherOrder.setLevel(cloudCoachPaymentProgram.getMemberRankSettingId());
                        cloudTeacherOrder.setStatus(1);
                        cloudTeacherOrder.setType(cloudCoachPaymentProgram.getPeriod());
                        cloudTeacherOrder.setTime(cloudCoachPaymentProgram.getMemberNum().intValue());
                        cloudTeacherOrder.setStudentId(coachPaymentDetails.getUserId());
                        cloudTeacherOrder.setOrganId(studentPaymentOrder.getOrganId());
                        cloudTeacherOrder.setAmount(studentPaymentOrder.getExpectAmount());
                        cloudTeacherOrderService.save(cloudTeacherOrder,cloudCoachPaymentProgram.getAutoActivationFlag());

                        //修改缴费状态
                        coachPaymentDetails.setPaymentStatus(1);
                        coachPaymentDetails.setPaymentOrderId(studentPaymentOrder.getId());
                        studentCloudCoachPaymentDetailsService.update(coachPaymentDetails);
                        //修改实际缴费人数
                        cloudCoachPaymentProgram.setPaymentUserNum(cloudCoachPaymentProgram.getPaymentUserNum() + 1);
                        cloudCoachPaymentProgramService.update(cloudCoachPaymentProgram);
                    }else {
                        CloudTeacherOrder cloudTeacherOrder = cloudTeacherOrderService.queryByOrderId(studentPaymentOrder.getId());
                        if (cloudTeacherOrder == null) {
                            throw new BizException("该云教练订单不存在");
                        }
                        if(cloudTeacherOrder.getStatus() == 2){
                            throw new BizException("该云教练订单已经生效");
                        }
                        if(cloudTeacherOrder.getStatus() == 1){
                            throw new BizException("该云教练订单已经支付");
                        }
                        cloudTeacherOrderService.save(cloudTeacherOrder,true);
                    }
                }
            }
            // 插入交易明细
            sysUserCashAccountDetailService.saveSysUserCashAccountDetail(studentPaymentOrder, "购买会员");
            try {
                contractService.transferProduceContract(userId, null, CourseViewTypeEnum.MEMBER_FEE);
            } catch (Exception e) {
                logger.error("产品协议生成失败", e);
            }
        }
        return true;
    }

    //齐齐哈尔会员活动
    private void qqheMemberActivity(StudentPaymentOrder studentPaymentOrder, Student student, SysUser sysUser, RBucket<Object> cache) {
        Map<String, Object> cacheMap = (Map<String, Object>) cache.get();
        BigDecimal totalMonth = (BigDecimal) cacheMap.get("totalMonth");
        //写cloud order
        LocalDate now = LocalDate.now();
        CloudTeacherOrder cto = new CloudTeacherOrder();
        cto.setStatus(2);
        cto.setOrganId(sysUser.getOrganId());
        cto.setStudentId(sysUser.getId());
        cto.setType(PeriodEnum.MONTH);
        cto.setLevel(1);
        cto.setTime(totalMonth.intValue());
        cto.setAmount(studentPaymentOrder.getActualAmount().add(studentPaymentOrder.getBalancePaymentAmount()));
        cto.setStartTime(now.toDate());
        cto.setEndTime(DateUtil.addDays(now.plusMonths(totalMonth.intValue()).toDate(),1));
        cto.setOrderId(studentPaymentOrder.getId());
        cto.setCreateTime(new Date());
        cloudTeacherOrderService.insert(cto);
        //修改student 查询学生现在的会员过期没，如果过期了就按现在时间来，如果没过期就在结束时间上叠加
        logger.info("orderCallback >>> member MembershipStartTime {} now {}", student.getMembershipStartTime(), now);
        if (Objects.nonNull(student.getMembershipStartTime())
                && Objects.nonNull(student.getMembershipEndTime())
                && student.getMembershipEndTime().getTime() >= now.toDate().getTime()) {
            student.setMembershipEndTime(DateUtil.addMonths(student.getMembershipEndTime(), cto.getTime()));
        } else {
            student.setMembershipStartTime(cto.getStartTime());
            student.setMembershipEndTime(cto.getEndTime());
        }
        student.setMemberRankSettingId(1);
        studentService.update(student);
        //发送激活信息
        Map<Integer, String> userPhones = new HashMap<>();
        userPhones.put(sysUser.getId(), sysUser.getPhone());
        sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.CLOUD_TEACHER_ORDER_SUCCESS, userPhones, null, 0, null, null);
    }
}
