package com.sqx.modules.orders.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.entity.UserVip;
import com.sqx.modules.app.entity.VipDetails;
import com.sqx.modules.app.service.*;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.course.dao.CourseDao;
import com.sqx.modules.course.dao.CourseDetailsDao;
import com.sqx.modules.course.dao.CourseUserDao;
import com.sqx.modules.course.entity.Course;
import com.sqx.modules.course.entity.CourseDetails;
import com.sqx.modules.course.entity.CourseUser;
import com.sqx.modules.course.service.CourseDetailsService;
import com.sqx.modules.course.service.CourseUserService;
import com.sqx.modules.invite.service.InviteMoneyService;
import com.sqx.modules.invite.service.InviteService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.service.DyService;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.utils.AliPayOrderUtil;
import com.sqx.modules.utils.TimeCompleteUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
    @Autowired
    private WxService wxService;
    @Autowired
    private AliPayController aliPayController;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private CourseUserDao courseUserDao;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private CourseUserService courseUserService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private VipDetailsService vipDetailsService;
    @Autowired
    private CourseDetailsService courseDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserService userService;
    @Autowired
    private InviteService inviteService;
    @Autowired
    private InviteMoneyService inviteMoneyService;
    @Autowired
    private DyService dyService;
    @Autowired
    private CourseDetailsDao courseDetailsDao;

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);


    @Override
    public Orders selectOrdersByCourseIdAndUserId(Long userId, Long courseId) {
        return baseMapper.selectOrdersByCourseIdAndUserId(userId, courseId);
    }


    @Override
    public Result insertOrders(Orders orders) {
        //如果订单的种类是短剧
        if (orders.getOrdersType() == 1) {
            if (StrUtil.isNotEmpty(orders.getCourseDetailsIds())) {
                List<Long> courseDetailsIdList = JSONUtil.parseArray(orders.getCourseDetailsIds()).toList(Long.class);
                List<CourseUser> courseUserList = new ArrayList<>();
                courseDetailsIdList.parallelStream().forEach(courseDetailsId -> {
                    //将短剧加入到我的列表
                    CourseUser courseUser = new CourseUser();
                    //设置短剧id
                    courseUser.setCourseId(orders.getCourseId());
                    courseUser.setCourseDetailsId(courseDetailsId);
                    courseUser.setClassify(2);
                    //设置用户id
                    courseUser.setUserId(orders.getUserId());
                    //设置订单id
                    courseUser.setOrderId(orders.getOrdersId());
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    courseUser.setCreateTime(df.format(new Date()));
                    courseUserList.add(courseUser);
                });
                //加入我的列表
                courseUserService.saveBatch(courseUserList);
                return Result.success("短剧订单处理完成！");
            }
            //将短剧加入到我的列表
            CourseUser courseUser = new CourseUser();
            //设置短剧id
            courseUser.setCourseId(orders.getCourseId());
            courseUser.setCourseDetailsId(orders.getCourseDetailsId());
            if (courseUser.getCourseDetailsId() != null) {
                courseUser.setClassify(2);
            } else {
                courseUser.setClassify(1);
            }
            //设置用户id
            courseUser.setUserId(orders.getUserId());
            //设置订单id
            courseUser.setOrderId(orders.getOrdersId());
            //加入我的列表
            courseUserService.insertCourseUser(courseUser);
            return Result.success("短剧订单处理完成！");
        } else {
            //订单的种类是会员
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //查询用户是否成为过会员
            UserVip userVip = userVipService.selectUserVipByUserId(orders.getUserId());
            if (userVip != null) {
                //日历
                Calendar cal = Calendar.getInstance();
                //会员没有到期
                if (userVip.getIsVip().equals(2)) {
                    try {
                        //将会员到期时间设置在日历表中
                        cal.setTime(sdf.parse(userVip.getEndTime()));
                        //判断续费会员的时间
                        if (orders.getVipNameType() == 0) {
                            //一个月
                            cal.add(Calendar.MONTH, 1);
                        } else if (orders.getVipNameType() == 1) {
                            //一季度
                            cal.add(Calendar.MONTH, 3);
                        } else if (orders.getVipNameType() == 2) {
                            //一年
                            cal.add(Calendar.YEAR, 1);
                        }
                        userVip.setIsVip(2);
                        //更新会员的开通时间
                        userVip.setCreateTime(sdf.format(new Date()));
                        //更新会员的到期时间
                        userVip.setEndTime(sdf.format(cal.getTime()));
                        //更新会员信息
                        userVip.setVipType(2);
                        userVipService.updateById(userVip);
                        return Result.success().put("data", "未到期会员续费成功！");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    //会员到期了
                    //将现在的时间设置在日历中
                    cal.setTime(new Date());
                    //判断续费会员的时间
                    if (orders.getVipNameType() == 0) {
                        //一个月
                        cal.add(Calendar.MONTH, 1);
                    } else if (orders.getVipNameType() == 1) {
                        //一季度
                        cal.add(Calendar.MONTH, 3);
                    } else if (orders.getVipNameType() == 2) {
                        //-年
                        cal.add(Calendar.YEAR, 1);
                    }
                    userVip.setIsVip(2);
                    //更新会员的开通时间
                    userVip.setCreateTime(sdf.format(new Date()));
                    //更新会员的到期时间
                    userVip.setEndTime(sdf.format(cal.getTime()));
                    //更新会员信息
                    userVip.setVipType(2);
                    userVipService.updateById(userVip);
                    return Result.success().put("data", "到期会员续费成功！");
                }
            } else {
                //不是会员开通会员
                //创建会员对象
                userVip = new UserVip();
                //设置开通的用户id
                userVip.setUserId(orders.getUserId());
                //设置开通时间
                userVip.setCreateTime(sdf.format(new Date()));
                //日历
                Calendar cal = Calendar.getInstance();
                //判断开通的会员类型
                if (orders.getVipNameType() == 0) {
                    //-月
                    cal.add(Calendar.MONTH, 1);
                } else if (orders.getVipNameType() == 1) {
                    //一季
                    cal.add(Calendar.MONTH, 3);
                } else if (orders.getVipNameType() == 2) {
                    //一年
                    cal.add(Calendar.YEAR, 1);
                }
                userVip.setIsVip(2);
                //设置到期时间
                userVip.setEndTime(sdf.format(cal.getTime()));
                //注册会员信息
                userVip.setVipType(2);
                userVipService.save(userVip);
                return Result.success().put("data", "到期会员续费成功！");
            }
        }
        return Result.success("订单处理完成！");
    }

    /**
     * 生成商品订单信息
     *
     * @param courseId
     * @param userId
     * @return
     */
    @Override
    public Result insertCourseOrders(Long courseId, Long courseDetailsId, Long userId) {
        log.info("生成商品订单信息接口入参为：{},{}", courseId, userId);
//        reentrantReadWriteLock.writeLock().lock();
        try {
            CourseDetails courseDetail = courseDetailsService.getById(courseDetailsId);
            if (courseDetail != null && courseDetail.getIsPrice().equals(2)) {
                return Result.success().put("status", 1);
            }
            CourseUser courseUser1 = courseUserDao.selectCourseUser(courseId, userId);
            if (courseUser1 != null) {
                return Result.success().put("status", 1);
            }
            QueryWrapper<CourseUser> courseUserQueryWrapper = new QueryWrapper<>();
            courseUserQueryWrapper.eq("user_id", userId);
            courseUserQueryWrapper.eq("course_id", courseId);
            courseUserQueryWrapper.eq("course_details_id", courseDetailsId);
            courseUserQueryWrapper.eq("classify", 2);
            //加入我的列表
            int count1 = courseUserService.count(courseUserQueryWrapper);
            if (count1 > 0) {
                return Result.success().put("status", 1);
            }
            //返回的类型
            Map<String, Object> result = new HashMap<>();
            //查询会员信息
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if (courseId == null) {
                return Result.error("短剧的id不能为空");
            }

            //订单模板对象
            Orders orders = new Orders();
            //根据短剧id去查询短剧相关信息 来填充订单模板
            QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", 0);
            //短剧必须是未删除的
            queryWrapper.eq("course_id", courseId);
            Course course = courseDao.selectOne(queryWrapper);
            if (course == null) {
                return Result.error("系统繁忙，请刷新后重试！");
            }
            //设置订单编号
            orders.setOrdersNo(AliPayOrderUtil.createOrderId());
            //设置用户id
            orders.setUserId(userId);
            //设置短剧id
            orders.setCourseId(courseId);
            orders.setCourseDetailsId(courseDetailsId);

            // 金币和金额的比例
            String value = commonInfoService.findOne(914).getValue();
            BigDecimal v = new BigDecimal(value);
            if (courseDetailsId != null) {
                CourseDetails courseDetails = courseDetailsService.getById(courseDetailsId);
                orders.setPayMoney(courseDetails.getPrice());
                orders.setPayDiamond(courseDetails.getPrice().multiply(v));
            } else {
                if (course.getPrice() == null || NumberUtil.isLessOrEqual(course.getPrice(), BigDecimal.ZERO)) {
                    return Result.error("该剧暂不支持整剧购买方式！");
                }
                orders.setPayMoney(course.getPrice());
                orders.setPayDiamond(course.getPrice().multiply(v));
            }
//            BigDecimal payDiamond = orders.getPayMoney().multiply(new BigDecimal(commonInfoService.findOne(892).getValue()));
//            orders.setPayDiamond(payDiamond);
            //设置支付状态
            orders.setStatus(0);
            //设置订单创建时间
            orders.setCreateTime(df.format(new Date()));
            //设置订单种类
            orders.setOrdersType(1);

            //不是会员或会员过期直接生成订单直接生成订单
            int count = baseMapper.insert(orders);
            result.put("flag", 2);
            result.put("orders", orders);
            if (count > 0) {
                return Result.success("生成订单成功！").put("data", result);
            } else {
                return Result.error("生成订单失败！");
            }

        } catch (Exception e) {
            log.error("生成商品订单错误！！！" + e.getMessage());
        }
//        finally {
//            reentrantReadWriteLock.writeLock().unlock();
//        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    /**
     * 生成商品订单信息(购买10集)
     *
     * @param courseId
     * @param userId
     * @return
     */
    @Override
    public Result insertCourseOrdersLimit10(Long courseId, Long userId) {
        log.info("生成商品订单信息接口入参为：{},{}", courseId, userId);
        reentrantReadWriteLock.writeLock().lock();
        try {
            /*CourseUser courseUser1 = courseUserDao.selectCourseUser(courseId, userId);
            if(courseUser1!=null){
                return Result.error("您已经购买过了，请不要重复点击！");
            }*/
            //返回的类型
            Map<String, Object> result = new HashMap<>();
            //查询会员信息
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if (courseId == null) {
                return Result.error("短剧的id不能为空");
            }

            //订单模板对象
            Orders orders = new Orders();
            //根据短剧id去查询短剧相关信息 来填充订单模板
            QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", 0);
            //短剧必须是未删除的
            queryWrapper.eq("course_id", courseId);
            Course course = courseDao.selectOne(queryWrapper);
            if (course == null) {
                return Result.error("系统繁忙，请刷新后重试！");
            }
            if (course.getWholesalePrice() == null) {
                return Result.error("该剧暂不支持10集购买方式！");
            }
            if (NumberUtil.isLessOrEqual(course.getWholesalePrice(), BigDecimal.ZERO)) {
                return Result.error("该剧暂不支持10集购买方式！");
            }
            //是否以购买全集
            Integer isBuyAllCount = courseUserDao.selectCount(Wrappers.<CourseUser>lambdaQuery().eq(CourseUser::getCourseId, courseId).eq(CourseUser::getCourseUserId, userId).eq(CourseUser::getClassify, 1));
            if (isBuyAllCount != null && isBuyAllCount > 0) {
                return Result.error("您已经购买过全集，请不要重复购买！");
            }
            List<CourseUser> courseUserList = courseUserDao.selectList(Wrappers.<CourseUser>lambdaQuery()
                    .select(CourseUser::getCourseDetailsId)
                    .eq(CourseUser::getCourseId, courseId)
                    .eq(CourseUser::getUserId, userId)
                    .eq(CourseUser::getClassify, 2)
                    .orderByAsc(CourseUser::getCourseDetailsId)
            );
            // 已购买剧集
            List<Long> courseDetailsIdList = courseUserList.stream().map(CourseUser::getCourseDetailsId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            LambdaQueryWrapper<CourseDetails> wrapper = Wrappers.<CourseDetails>lambdaQuery();
            wrapper.eq(CourseDetails::getCourseId, courseId);
            wrapper.eq(CourseDetails::getIsPrice, 1);
            wrapper.select(CourseDetails::getCourseDetailsId);
            wrapper.orderByAsc(CourseDetails::getSort);
            List<CourseDetails> courseDetailsList = courseDetailsDao.selectList(wrapper);
            if (CollUtil.isEmpty(courseDetailsList)) {
                return Result.error("该剧的视频资源不存在！");
            }
            List<Long> allIds = courseDetailsList.stream().map(CourseDetails::getCourseDetailsId).distinct().collect(Collectors.toList());
            allIds.removeAll(courseDetailsIdList);
            // 需要购买的剧集id集合（没有权限的10集）
            List<Long> buyCourseDetailsIdList = allIds.stream().filter(Objects::nonNull).limit(10).collect(Collectors.toList());
            if (CollUtil.isEmpty(buyCourseDetailsIdList)) {
                return Result.error("没有需要购买的剧集！");
            }
            //设置订单编号
            orders.setOrdersNo(AliPayOrderUtil.createOrderId());
            //设置用户id
            orders.setUserId(userId);
            //设置短剧id
            orders.setCourseId(courseId);
            orders.setCourseDetailsId(null);
            orders.setCourseDetailsIds(JSONUtil.parseArray(buyCourseDetailsIdList).toString());

            // 金币和金额的比例
            String value = commonInfoService.findOne(914).getValue();
            BigDecimal v = new BigDecimal(value);

            orders.setPayMoney(course.getWholesalePrice());
            orders.setPayDiamond(course.getWholesalePrice().multiply(v));
//            BigDecimal payDiamond = orders.getPayMoney().multiply(new BigDecimal(commonInfoService.findOne(892).getValue()));
//            orders.setPayDiamond(payDiamond);
            //设置支付状态
            orders.setStatus(0);
            //设置订单创建时间
            orders.setCreateTime(df.format(new Date()));
            //设置订单种类
            orders.setOrdersType(1);

            //不是会员或会员过期直接生成订单直接生成订单
            int count = baseMapper.insert(orders);
            result.put("flag", 2);
            result.put("orders", orders);
            if (count > 0) {
                return Result.success("生成订单成功！").put("data", result);
            } else {
                return Result.error("生成订单失败！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成商品订单错误！！！" + e.getMessage());
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    /**
     * 生成会员订单
     *
     * @param vipDetailsId 会员详情id
     * @param userId
     * @return
     */
    @Override
    public Result insertVipOrders(Long vipDetailsId, Long userId) {
        VipDetails vipDetails = vipDetailsService.getById(vipDetailsId);
        //创建订单返回对象
        Orders orders = new Orders();
        //设置订单编号
        orders.setOrdersNo(AliPayOrderUtil.createOrderId());
        //设置支付金币
        orders.setPayMoney(vipDetails.getMoney());
        orders.setPayDiamond(vipDetails.getPayDiamond());
        //设置订单类型
        orders.setOrdersType(2);
        //设置要开通的会员类型
        orders.setVipNameType(vipDetails.getVipNameType());
        //设置支付状态
        orders.setStatus(0);
        //设置用户id
        orders.setUserId(userId);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置创建时间
        orders.setCreateTime(df.format(new Date()));
        //插入到订单表中
        baseMapper.insert(orders);
        return Result.success().put("data", orders);
    }


    @Override
    public Result payMoney(Long ordersId) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            Orders orders = baseMapper.selectById(ordersId);
            if (orders == null || !orders.getStatus().equals(0)) {
                return Result.error("订单错误，请刷新后重试！");
            }
            if (orders.getOrdersType() == 1) {
                int count = 0;
                if (orders.getCourseDetailsId() != null) {
                    count = courseUserDao.selectCount(new QueryWrapper<CourseUser>()
                            .eq("user_id", orders.getUserId())
                            .eq("classify", 2)
                            .eq("course_id", orders.getCourseId())
                            .eq(orders.getCourseDetailsId() != null, "course_details_id", orders.getCourseDetailsId()));
                } else if (orders.getCourseDetailsIds() != null) {
                    List<Long> courseDetailsIds = JSONUtil.parseArray(orders.getCourseDetailsIds()).toList(Long.class);
                    count = courseUserDao.selectCount(new QueryWrapper<CourseUser>()
                            .eq("user_id", orders.getUserId())
                            .eq("course_id", orders.getCourseId())
                            .in("course_details_id", courseDetailsIds));
                } else {
                    count = courseUserDao.selectCount(new QueryWrapper<CourseUser>()
                            .eq("user_id", orders.getUserId())
                            .eq("classify", 1)
                            .eq("course_id", orders.getCourseId()));
                }
                if (count > 0) {
                    return Result.error("您已购买，请不要重复点击");
                }
            }
            UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            if (userMoney.getMoney().doubleValue() < orders.getPayDiamond().doubleValue()) {
                return Result.error("账户不足，请充值！");
            }
            //UserEntity userEntity = userService.selectUserById(orders.getUserId());
            userMoneyService.updateMoney(2, orders.getUserId(), orders.getPayDiamond().doubleValue());
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(orders.getPayDiamond());
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setContent("金币支付订单");
            userMoneyDetails.setTitle("下单成功，订单号：" + orders.getOrdersNo());
            userMoneyDetails.setType(2);
            // ✅
            userMoneyDetails.setClassify(3);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetails.setMoneyType(2);
            userMoneyDetailsService.save(userMoneyDetails);
            orders.setPayWay(6);
            orders.setDiamond(1);
            orders.setStatus(1);
            orders.setPayTime(DateUtils.format(new Date()));


            // 金币支付不给佣金
//            UserEntity byUser = userService.queryByInvitationCode(userEntity.getInviterCode());
//            Map map = inviteService.updateInvite(byUser, DateUtils.format(new Date()), userEntity.getUserId(), orders.getPayMoney());
//            Object oneUserId = map.get("oneUserId");
//            if (oneUserId != null) {
//                orders.setOneUserId(Long.parseLong(String.valueOf(oneUserId)));
//                orders.setOneMoney(new BigDecimal(String.valueOf(map.get("oneMoney"))));
//            }
//            Object twoUserId = map.get("twoUserId");
//            if (twoUserId != null) {
//                orders.setTwoUserId(Long.parseLong(String.valueOf(twoUserId)));
//                orders.setTwoMoney(new BigDecimal(String.valueOf(map.get("twoMoney"))));
//            }
//            Object sysUserId = map.get("sysUserId");
//            if (sysUserId != null) {
//                orders.setSysUserId(Long.parseLong(String.valueOf(sysUserId)));
//                orders.setQdMoney(new BigDecimal(String.valueOf(map.get("qdMoney"))));
//            }
            baseMapper.updateById(orders);
            insertOrders(orders);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("金币支付订单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.success();
    }

    @Override
    public Result refundOrder(Long ordersId, String refundContent) {
        Orders bean = baseMapper.selectById(ordersId);
        if (!bean.getStatus().equals(1)) {
            return Result.error("订单未支付或已退款！");
        }
        bean.setRefundContent(refundContent);
        if (bean.getPayWay() == 1 || bean.getPayWay() == 2 || bean.getPayWay() == 3) {
            boolean refund = wxService.refund(bean);
            if (!refund) {
                return Result.error("退款失败！");
            }
        } else if (bean.getPayWay() == 4 || bean.getPayWay() == 5) {
            String code = aliPayController.alipayRefund(bean);
            if (StringUtils.isNotBlank(code)) {
                JSONObject jsonObject = JSON.parseObject(code);
                JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                String code1 = alipay_trade_refund_response.getString("code");
                if (!"10000".equals(code1)) {
                    return Result.error("退款失败！");
                }
            } else {
                return Result.error("退款失败！");
            }
        } else if (bean.getPayWay() == 7) {
            boolean refund = dyService.refund(bean);
            if (!refund) {
                return Result.error("退款失败！");
            }
        } else {
            userMoneyService.updateMoney(1, bean.getUserId(), bean.getPayMoney().doubleValue());
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(bean.getPayMoney());
            userMoneyDetails.setUserId(bean.getUserId());
            userMoneyDetails.setContent("订单:" + bean.getOrdersNo());
            userMoneyDetails.setTitle("订单退款：" + bean.getPayMoney());
            userMoneyDetails.setType(1);
            // ✅
            userMoneyDetails.setClassify(9);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetails.setMoneyType(1);
            userMoneyDetailsService.save(userMoneyDetails);
        }
        bean.setStatus(2);
        baseMapper.updateById(bean);
        if (bean.getOrdersType() == 1) {
            CourseUser courseUser = courseUserDao.selectOne(new QueryWrapper<CourseUser>().eq("order_id", bean.getOrdersId()));
            if (courseUser != null) {
                courseUserDao.deleteById(courseUser.getCourseUserId());
            }
        } else {
            UserVip userVip = userVipService.selectUserVipByUserId(bean.getUserId());
            if (userVip != null) {
                //判断用户开通的会员是否到期
                if (userVip.getIsVip() != null && userVip.getIsVip() == 2) {
                    int month = 0;
                    //0会月/1季度/2年
                    if (bean.getVipNameType() == 0) {
                        month = 1;
                    } else if (bean.getVipNameType() == 1) {
                        month = 3;
                    } else {
                        month = 12;
                    }
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(DateUtils.stringToDate(userVip.getEndTime(), DateUtils.DATE_TIME_PATTERN));
                    calendar.add(Calendar.MONTH, -month);
                    if (calendar.getTime().getTime() > System.currentTimeMillis()) {
                        //判断时间是否大于当前时间 如果大于 则改
                        userVip.setEndTime(DateUtils.format(calendar.getTime()));
                    } else {
                        //否则设置为当前时间 并且会员改为过期
                        userVip.setEndTime(DateUtils.format(new Date()));
                        userVip.setIsVip(1);
                        courseUserDao.deleteCourseUserByVipUser(bean.getUserId());
                    }
                    userVipService.updateById(userVip);
                }
            }

        }
        return Result.success("退款成功！");
    }

    @Override
    public Result selectOrders(Integer page, Integer limit, String ordersNo, Integer status, Long userId, Long courseId,
                               Integer flag, String time, String userName, Integer ordersType, String startTime, String endTime,
                               Long sysUserId, String qdCode, String sysUserName) {
        PageHelper.startPage(page, limit);

        List<Orders> orders = baseMapper.selectOrdersByOrdersNo(ordersNo, status, userId, courseId,
                flag, time, userName, ordersType, TimeCompleteUtils.completeStartTime(startTime), TimeCompleteUtils.completeEndTime(endTime), sysUserId, qdCode, sysUserName);
        PageInfo<Orders> pageInfo = new PageInfo<>(orders);

        return Result.success().put("data", PageUtils.page(pageInfo));
    }

    @Override
    public Result selectOrderByUserId(Integer page, Integer limit, Long userId) {
        PageHelper.startPage(page, limit);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("orders_type", 1);
        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("create_time");
        List<Orders> list = baseMapper.selectList(queryWrapper);
        PageInfo<Orders> pageInfo = new PageInfo<>(list);
        List<Orders> bean = pageInfo.getList();
        if (bean != null && bean.size() > 0) {
            for (int i = 0; bean.size() > i; i++) {
                bean.get(i).setCourse(courseDao.selectById(bean.get(i).getCourseId()));
            }
        }
        return Result.success().put("data", PageUtils.page(pageInfo, true));
    }

    @Override
    public Result deleteOrders(String ids) {
        String[] split = ids.split(",");
        baseMapper.deleteOrders(split);
        return Result.success();
    }


    @Override
    public Orders selectOrderById(Long orderId) {
        return baseMapper.selectById(orderId);
    }

    @Override
    public Orders selectOrderByOrdersNo(String ordersNo) {
        return baseMapper.selectOne(new QueryWrapper<Orders>().eq("orders_no", ordersNo));
    }

    @Override
    public Orders selectOrderByTradeNo(String tradeNo) {
        return baseMapper.selectOne(new QueryWrapper<Orders>().eq("trade_no", tradeNo));
    }

    @Override
    public Double statisticsIncomeMoney(String time, Integer flag, Integer ordersType) {
        return baseMapper.statisticsIncomeMoney(time, flag, ordersType);
    }

    @Override
    public Result selectOrdersMoneyList(Integer page, Integer limit, Integer flag, String time) {
        PageHelper.startPage(page,limit);
        return Result.success().put("data", PageUtils.page(new PageInfo<>(baseMapper.selectOrdersMoneyList( flag, time)),true));
    }


    @Override
    public Integer selectOrdersCount(Integer status, Integer ordersType, Integer flag, String time, Long sysUserId) {
        return baseMapper.selectOrdersCount(status, ordersType, flag, time, sysUserId);
    }

    @Override
    public Double selectOrdersMoney(Integer status, Integer ordersType, Integer flag, String time, Long courseId, Long sysUserId) {
        return baseMapper.selectOrdersMoney(status, ordersType, flag, time, courseId, sysUserId);
    }

    @Override
    public Double selectFenXiaoMoney(Integer type, Long sysUserId, Integer flag, String time) {
        return baseMapper.selectFenXiaoMoney(type, sysUserId, flag, time);
    }


    @Override
    public Integer selectOrdersCountStatisticsByYear(Integer flag, String time, Integer status) {
        return baseMapper.selectOrdersCountStatisticsByYear(flag, time, status);
    }

    @Override
    public Integer selectOrdersCountStatisticsByDay(Long userId, Integer limit) {
        Integer count = baseMapper.selectOrdersCountStatisticsByDay(userId);
        if (count == null) {
            return 0;
        }

        if (count <= limit) {
            return count;
        }

        return limit;
    }

    @Override
    public Orders selectOrdersByDay(Long userId) {
        return baseMapper.selectOrdersByDay(userId);
    }


    @Override
    public Integer countOrderNum(Long userId, String time) {
        return baseMapper.countOrderNum(userId, time);
    }
}
