package com.zhongzheng.modules.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zhongzheng.common.core.redis.RedisCache;
import com.zhongzheng.common.core.redis.RedisLockEntity;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.base.service.IProfileTpService;
import com.zhongzheng.modules.base.service.IShoppingCartService;
import com.zhongzheng.modules.goods.domain.Goods;
import com.zhongzheng.modules.goods.service.IGoodsService;
import com.zhongzheng.modules.grade.bo.ClassGradeQueryBo;
import com.zhongzheng.modules.grade.bo.ClassGradeUserTempQueryBo;
import com.zhongzheng.modules.grade.domain.*;
import com.zhongzheng.modules.grade.service.IClassGradeGoodsService;
import com.zhongzheng.modules.grade.service.IClassGradeService;
import com.zhongzheng.modules.grade.service.IClassGradeUserService;
import com.zhongzheng.modules.grade.service.IClassGradeUserTempService;
import com.zhongzheng.modules.grade.vo.ClassGradeUserTempVo;
import com.zhongzheng.modules.grade.vo.ClassGradeVo;
import com.zhongzheng.modules.inform.service.IInformRemindService;
import com.zhongzheng.modules.inform.service.IInformUserService;
import com.zhongzheng.modules.order.bo.*;
import com.zhongzheng.modules.order.domain.Order;
import com.zhongzheng.modules.order.domain.OrderGoods;
import com.zhongzheng.modules.order.mapper.OrderMapper;
import com.zhongzheng.modules.order.service.IOrderBusinessService;
import com.zhongzheng.modules.order.service.IOrderGoodsService;
import com.zhongzheng.modules.order.service.IOrderService;
import com.zhongzheng.modules.order.vo.OrderGoodsVo;
import com.zhongzheng.modules.order.vo.OrderListVo;
import com.zhongzheng.modules.order.vo.OrderVo;
import com.zhongzheng.modules.user.service.IUserService;
import com.zhongzheng.modules.user.vo.UserVo;
import com.zhongzheng.modules.wx.service.IWxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-08
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    private IOrderGoodsService iOrderGoodsService;

    @Autowired
    private IOrderBusinessService iOrderBusinessService;
    @Autowired
    private IGoodsService iGoodsService;
    @Autowired
    private IClassGradeService iClassGradeService;
    @Autowired
    private IClassGradeUserTempService iClassGradeUserTempService;
    @Autowired
    private IClassGradeUserService iClassGradeUserService;
    @Autowired
    private IClassGradeGoodsService iClassGradeGoodsService;

    @Autowired
    private IInformRemindService informRemindService;

    @Autowired
    private IProfileTpService iProfileTpService;

    @Autowired
    private IWxPayService iWxPayService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IShoppingCartService iShoppingCartService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private com.zhongzheng.modules.alisms.service.IAliSmsService IAliSmsService;

    @Autowired
    private IInformUserService iInformUserService;

    @Override
    public OrderVo queryById(Long orderId){
        Order db = this.baseMapper.selectById(orderId);
        return BeanUtil.toBean(db, OrderVo.class);
    }

    @Override
    public List<OrderVo> queryList(OrderQueryBo bo) {
        LambdaQueryWrapper<Order> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getOrderSn()), Order::getOrderSn, bo.getOrderSn());
        lqw.eq(bo.getUserId() != null, Order::getUserId, bo.getUserId());
        lqw.eq(bo.getOrderPrice() != null, Order::getOrderPrice, bo.getOrderPrice());
        lqw.eq(StrUtil.isNotBlank(bo.getOrderGeneral()), Order::getOrderGeneral, bo.getOrderGeneral());
        lqw.in(bo.getOrderStatus() != null, Order::getOrderStatus, bo.getOrderStatus());
        lqw.eq(bo.getPayTime() != null, Order::getPayTime, bo.getPayTime());
        lqw.eq(bo.getPayType() != null, Order::getPayType, bo.getPayType());
        lqw.eq(StrUtil.isNotBlank(bo.getTransid()), Order::getTransid, bo.getTransid());
        lqw.eq(bo.getCancelTime() != null, Order::getCancelTime, bo.getCancelTime());
        lqw.eq(bo.getFinishTime() != null, Order::getFinishTime, bo.getFinishTime());
        lqw.eq(bo.getOrderType() != null, Order::getOrderType, bo.getOrderType());
        lqw.eq(bo.getPayPrice() != null, Order::getPayPrice, bo.getPayPrice());
        lqw.eq(bo.getChargingType() != null, Order::getChargingType, bo.getChargingType());
        lqw.eq(bo.getOrderFrom() != null, Order::getOrderFrom, bo.getOrderFrom());
        return entity2Vo(this.list(lqw));
    }

    @Override
    public List<OrderListVo> selectList(OrderQueryBo bo) {
        List<OrderListVo> orderListVos = orderMapper.selectList(bo);
        return orderListVos;
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<OrderVo> entity2Vo(Collection<Order> collection) {
        List<OrderVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, OrderVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<Order> page = (Page<Order>)collection;
            Page<OrderVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(OrderAddBo bo) {
        Order add = BeanUtil.toBean(bo, Order.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        return this.save(add);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> placeOrder(OrderAddBo bo) {


        return null;
    }

    /**
     * 业务员平台下单
     * @param bo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized Map<String, Object> placePlatOrder(OrderAddBo bo) {
        List<OrderGoodsAddBo> goodsList = bo.getGoodsList();
        if(goodsList==null||goodsList.size()<1){
            throw new CustomException("商品列表为空");
        }
        Order add = BeanUtil.toBean(bo, Order.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        add.setOrderType(Order.CONSUME_ORDER);
        add.setCreateUsername(bo.getCreateBy());//
        //生成订单号
        String out_trade_no = DateUtils.getDateOrderSn();

        //生成业务
      /*  OrderBusinessAddBo orderBusinessAddBo = bo.getOrderBusiness();
        orderBusinessAddBo.setOrderSn(out_trade_no);
        iOrderBusinessService.insertByAddBo(orderBusinessAddBo);*/

        //生成学员
     /*   OrderStudentInfoAddBo orderStudentInfoAddBo = bo.getOrderStudent();
        orderStudentInfoAddBo.setOrderSn(out_trade_no);
        iOrderStudentInfoService.insertByAddBo(orderStudentInfoAddBo);*/


        BigDecimal totalPrice = new BigDecimal(0);
        BigDecimal payPrice = new BigDecimal(0);
        //生成订单
        for (OrderGoodsAddBo g : goodsList) {
            //订单商品
            Goods goods = iGoodsService.getOne(new LambdaQueryWrapper<Goods>().eq(Goods::getGoodsId,g.getGoodsId()));
            if(goods.getGoodsStatus()!=1){
                throw new CustomException("商品尚未上架");
            }
            OrderGoods orderGoods = BeanUtil.toBean(g, OrderGoods.class);
            orderGoods.setOrderSn(out_trade_no);
            if(g.getGoodsInputData()!=null){
                orderGoods.setGoodsInputData(JSON.toJSONString(g.getGoodsInputData()));
            }
            //赋值业务信息
            orderGoods.setBusinessOwner(bo.getOrderBusiness().getBusinessOwner());
            orderGoods.setDept(bo.getOrderBusiness().getDept());
            orderGoods.setSource(bo.getOrderBusiness().getSource());
            orderGoods.setSchool(bo.getOrderBusiness().getSchool());

            //收货公司信息
            orderGoods.setAddress(bo.getOrderStudent().getAddress());
            orderGoods.setCompany(bo.getOrderStudent().getCompany());
            //成交价
            orderGoods.setGoodsRealPrice(goods.getStandPrice());

            orderGoods.setCreateTime(DateUtils.getNowTime());
            orderGoods.setUpdateTime(DateUtils.getNowTime());
            boolean orderGoodsRs = iOrderGoodsService.save(orderGoods);
            //订单价格不计算优惠
            totalPrice = totalPrice.add(g.getGoodsPrice());
            //暂不计算优惠券
            payPrice = payPrice.add(g.getGoodsPrice());

            boolean canRepeatBuy = false;
            //视频商品安排班级
            if(goods.getGoodsType()==1&&orderGoodsRs){
                Long gradeId = null;
                if(g.getGoodsInputData()!=null){
                    gradeId = g.getGoodsInputData().getGradeId();
                }
                //判断是否购买历史班级都过期
                canRepeatBuy =this.canBuyRepeatGoods(g.getGoodsId(),bo.getUserId());
                String requestId = IdUtil.simpleUUID();
                RedisLockEntity redisLockEntity = new RedisLockEntity();
                redisLockEntity.setLockKey(RedisLockEntity.KEY_LOCK_GRADE);
                redisLockEntity.setRequestId(requestId);
                if(redisCache.lock(redisLockEntity)){
                    arrangeGrade(goods.getGoodsName(),goods.getGoodsId(),orderGoods.getOrderGoodsId(),gradeId,add.getUserId(),out_trade_no);
                    redisCache.unlockLua(redisLockEntity);
                }

            }
            if(!canRepeatBuy){
                this.checkBuyGoods(g.getGoodsId(),bo.getUserId());
            }
        }

        add.setOrderSn(out_trade_no);
        add.setOrderFrom(Order.FROM_PLAT);
        add.setPayPrice(payPrice);
        add.setOrderPrice(totalPrice);

        this.save(add);
        Map<String, Object> result = new HashMap<>();
        result.put("oderId",add.getOrderId());
        result.put("orderSn",out_trade_no);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> placeSmallOrder(OrderAddBo bo) {
        List<OrderGoodsAddBo> goodsList = bo.getGoodsList();
        if(goodsList==null||goodsList.size()<1){
            throw new CustomException("商品列表为空");
        }
        Order add = BeanUtil.toBean(bo, Order.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());


        //生成订单号
        String out_trade_no = DateUtils.getDateOrderSn();
        BigDecimal totalPrice = new BigDecimal(0);
        BigDecimal payPrice = new BigDecimal(0);
        String body = "中正祥粤云-";
        //生成订单
        for (OrderGoodsAddBo g : goodsList) {
            //订单商品
            Goods goods = iGoodsService.getOne(new LambdaQueryWrapper<Goods>().eq(Goods::getGoodsId,g.getGoodsId()));
            if(goods.getGoodsStatus()!=1){
                throw new CustomException("商品尚未上架");
            }
            body = "中正祥粤云-"+goods.getGoodsName();
            OrderGoods orderGoods = BeanUtil.toBean(g, OrderGoods.class);
            orderGoods.setOrderSn(out_trade_no);
            if(g.getGoodsInputData()!=null){
                orderGoods.setGoodsInputData(JSON.toJSONString(g.getGoodsInputData()));
            }
            //赋值业务信息
           /* orderGoods.setBusinessOwner(bo.getOrderBusiness().getBusinessOwner());
            orderGoods.setDept(bo.getOrderBusiness().getDept());
            orderGoods.setSource(bo.getOrderBusiness().getSource());
            orderGoods.setSchool(bo.getOrderBusiness().getSchool());*/

            //收货公司信息
           /* orderGoods.setAddress(bo.getOrderStudent().getAddress());
            orderGoods.setCompany(bo.getOrderStudent().getCompany());*/
            //成交价
            orderGoods.setGoodsRealPrice(goods.getStandPrice());
            orderGoods.setGoodsPrice(goods.getStandPrice());
            orderGoods.setCreateTime(DateUtils.getNowTime());
            orderGoods.setUpdateTime(DateUtils.getNowTime());
            boolean orderGoodsRs = iOrderGoodsService.save(orderGoods);
            //订单价格不计算优惠
            totalPrice = totalPrice.add(goods.getStandPrice());
            //暂不计算优惠券
            payPrice = payPrice.add(goods.getStandPrice());


            boolean canRepeatBuy = false;
            //视频商品安排班级
            if(goods.getGoodsType()==1&&orderGoodsRs){
                Long gradeId = null;
                if(g.getGoodsInputData()!=null){
                    gradeId = g.getGoodsInputData().getGradeId();
                }
                //判断是否购买历史班级都过期
                canRepeatBuy =this.canBuyRepeatGoods(g.getGoodsId(),bo.getUserId());
                String requestId = IdUtil.simpleUUID();
                RedisLockEntity redisLockEntity = new RedisLockEntity();
                redisLockEntity.setLockKey(RedisLockEntity.KEY_LOCK_GRADE);
                redisLockEntity.setRequestId(requestId);
                if(redisCache.lock(redisLockEntity)){
                    arrangeGrade(goods.getGoodsName(),goods.getGoodsId(),orderGoods.getOrderGoodsId(),gradeId,add.getUserId(),out_trade_no);
                    redisCache.unlockLua(redisLockEntity);
                }
            }
            if(!canRepeatBuy){
                this.checkBuyGoods(g.getGoodsId(),bo.getUserId());
            }
            iShoppingCartService.deleteByGoodsId(g.getGoodsId(),bo.getUserId());
        }

        add.setOrderSn(out_trade_no);
        add.setOrderFrom(Order.FROM_SMALL);
        add.setPayPrice(payPrice);
        add.setOrderPrice(totalPrice);
        this.save(add);
        Map<String, Object> result = new HashMap<>();
        result.put("oderId",add.getOrderId());
        result.put("orderSn",out_trade_no);
        UserVo userVo = iUserService.queryById(add.getUserId());
        String price = "1";
        Map<String, String> payResult =  iWxPayService.payment(out_trade_no,userVo.getOpenId(),body,price);
        payResult.put("orderSn",out_trade_no);
        return payResult;
    }

    @Override
    public Map<String, String> resumeSmallOrder(OrderAddBo bo) {
        if(bo.getOrderSn()==null){
            throw new CustomException("订单数据错误");
        }
        Order order = this.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderSn, bo.getOrderSn()));
        String body = "";
        if(order!=null&&order.getOrderStatus()==0){
            Map<String,Object> map = new HashMap<>();
            map.put("order_sn",bo.getOrderSn());
            List<OrderGoods> goodsList = iOrderGoodsService.listByMap(map);
            for (OrderGoods g : goodsList) {
                Goods goods = iGoodsService.getOne(new LambdaQueryWrapper<Goods>().eq(Goods::getGoodsId,g.getGoodsId()));
                if(goods.getGoodsStatus()!=1){
                    throw new CustomException("商品尚未上架");
                }
                body = "中正祥粤云-"+goods.getGoodsName();
                break;
            }
        }else{
            throw new CustomException("无法继续支付");
        }
        UserVo userVo = iUserService.queryById(bo.getUserId());
        String price = "1";
        Map<String, String> payResult =  iWxPayService.payment(bo.getOrderSn(),userVo.getOpenId(),body,price);
        payResult.put("orderSn",bo.getOrderSn());
        return payResult;
    }



    @Override
    public Boolean updateByEditBo(OrderEditBo bo) {
        Order update = BeanUtil.toBean(bo, Order.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());

        if(update.getOrderStatus()==-1){
            update.setCancelTime(DateUtils.getNowTime());
            //手动关闭订单
            OrderVo orderVo = this.queryById(bo.getOrderId());
            //关闭锁定班级
            LambdaQueryWrapper<ClassGradeUserTemp> lqwLock = new LambdaQueryWrapper<>();
            lqwLock.eq(ClassGradeUserTemp::getOrderSn,orderVo.getOrderSn());
            ClassGradeUserTemp classGradeUserTemp = iClassGradeUserTempService.getOne(lqwLock);
            if(classGradeUserTemp!=null){
                classGradeUserTemp.setStatus(ClassGradeUserTemp.STATUS_CLOSE);
                classGradeUserTemp.setUpdateTime(DateUtils.getNowTime());
                iClassGradeUserTempService.updateById(classGradeUserTemp);//关闭锁定状态
            }
        }
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Order entity){
        //TODO 做一些数据校验,如唯一约束

    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    public List<OrderListVo> selectListApp(OrderQueryBo bo) {
        List<OrderListVo> orderListVos = orderMapper.selectListApp(bo);
        for (OrderListVo orderListVo : orderListVos) {
            OrderGoodsQueryBo orderGoodsQueryBo = new OrderGoodsQueryBo();
            orderGoodsQueryBo.setOrderSn(orderListVo.getOrderSn());
            List<OrderGoodsVo> list = iOrderGoodsService.selectList(orderGoodsQueryBo);
            BigDecimal totalPrice = new BigDecimal("0");
            for (OrderGoodsVo orderGoodsVo : list) {
                if (orderGoodsVo.getGoodsRealPrice() != null) {
                    totalPrice = totalPrice.add(orderGoodsVo.getGoodsRealPrice());
                }
            }
            orderListVo.setOrderGoodsList(list);
            orderListVo.setTotalPrice(totalPrice);
        }
        return orderListVos;
    }

    //检查是否允许重复购买商品
    public boolean canBuyRepeatGoods(Long goodsId,Long userId){
        //判断是否还有未过期的班级
        ClassGradeQueryBo bo = new ClassGradeQueryBo();
        bo.setUserId(userId);
        bo.setGoodsId(goodsId);
        bo.setPastDue(1L);
        List<ClassGradeVo> list = iClassGradeService.queryList(bo);
        if(list!=null&&list.size()>0){
            throw new CustomException("包含购买商品班级尚未过期");
        }
        //判断是否有锁定的班级
        ClassGradeUserTempQueryBo gradeUserTempQueryBo = new ClassGradeUserTempQueryBo();
        gradeUserTempQueryBo.setUserId(userId);
        gradeUserTempQueryBo.setGoodsId(goodsId);
        gradeUserTempQueryBo.setStatus(ClassGradeUserTemp.STATUS_LOCK);
        List<ClassGradeUserTempVo> list1 = iClassGradeUserTempService.queryList(gradeUserTempQueryBo);
        if(list1!=null&&list1.size()>0){
            throw new CustomException("待支付包含购买商品班级尚未过期");
        }
        return true;
    }


    //检查是否购买过商品
    public boolean checkBuyGoods(Long goodsId,Long userId){
        OrderGoodsQueryBo bo = new OrderGoodsQueryBo();
        bo.setUserId(userId);
        bo.setGoodsId(goodsId);
        Long num = iOrderGoodsService.getBuyGoodsHistory(bo);
        if(num.longValue()>0){
            throw new CustomException("无法重复购买商品");
        }
        return false;
    }

    /**
     * 加入班级
     * @param orderGoodsId
     * @param gradeId
     * @return
     */
    public boolean arrangeGrade(String goodsName,Long goodsId,Long orderGoodsId,Long gradeId,Long userId,String orderSn){
        //查询该学员有没有有效期内同商品班级 有就不允许添加
       /* Integer classNum = baseMapper.selectUserClass(goodsId,userId);
        if (classNum > 0){
            throw new CustomException("该学员已在此商品有效期内的班级，无法加入新的有效期班级，请查看该学员此商品下的班级");
        }*/
        //指定班级
        if(gradeId!=null&&gradeId>0){
            ClassGradeVo classGradeVo = iClassGradeService.queryById(gradeId);
            if(classGradeVo==null){
                throw new CustomException("班级不存在");
            }
            if(classGradeVo.getStatus()!=1){
                throw new CustomException("班级已失效");
            }
            ClassGradeGoods gradeGoods = iClassGradeGoodsService.getOne(new LambdaQueryWrapper<ClassGradeGoods>().eq(ClassGradeGoods::getGradeId,gradeId)
            .eq(ClassGradeGoods::getGoodsId,goodsId));
            if(gradeGoods==null){
                throw new CustomException("该班级不支持该商品使用");
            }
            LambdaQueryWrapper<ClassGradeUser> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ClassGradeUser::getGradeId,gradeId);
            lqw.eq(ClassGradeUser::getStatus,1);
            int studentNum = iClassGradeUserService.count(lqw);
            //临时锁定的班级学员数量
            LambdaQueryWrapper<ClassGradeUserTemp> lqwLock = new LambdaQueryWrapper<>();
            lqwLock.eq(ClassGradeUserTemp::getGradeId,gradeId);
            lqwLock.eq(ClassGradeUserTemp::getStatus,1);
            int locakStudentNum = iClassGradeUserTempService.count(lqwLock);
            //预留0空位避免超人数
            if((classGradeVo.getStudentUpper()-studentNum-locakStudentNum)>0){
                //班级还有剩位,直接锁定班级
                return lockGrade(orderGoodsId,gradeId,userId,goodsId,orderSn);
            }
        }else {
            //无指定班级
            ClassGradeQueryBo bo = new ClassGradeQueryBo();
            bo.setGoodsId(goodsId);
            bo.setPastDue(1L);
            bo.setStatus(new ArrayList<Integer>(Arrays.asList(1)));
            List<ClassGradeVo> classGradeVoList =  iClassGradeService.queryList(bo);
            for(int i = 0; i < classGradeVoList.size(); i++){
                ClassGradeVo classGradeVo = classGradeVoList.get(i);
                //临时锁定的班级学员数量
                LambdaQueryWrapper<ClassGradeUserTemp> lqwLock = new LambdaQueryWrapper<>();
                lqwLock.eq(ClassGradeUserTemp::getGradeId,gradeId);
                lqwLock.eq(ClassGradeUserTemp::getStatus,1);
                int locakStudentNum = iClassGradeUserTempService.count(lqwLock);
                //预留0空位避免超人数
                if((classGradeVo.getStudentUpper()-classGradeVo.getStudentNum()-locakStudentNum)>0){
                    //有空位则进入班级
                    gradeId = classGradeVo.getGradeId();
                    //班级还有剩位,直接锁定班级
                    return lockGrade(orderGoodsId,gradeId,userId,goodsId,orderSn);
                }
            }
        }
        //创建新班级
        ClassGrade classGrade = new ClassGrade();
        classGrade.setStudentUpper(ClassGrade.INIT_UPPER); //上限300
        classGrade.setCreateTime(DateUtils.getNowTime());
        classGrade.setUpdateTime(DateUtils.getNowTime());
        classGrade.setStatus(1);
        String gradeCode = ServletUtils.getEncoded("BJ");
        classGrade.setGradeCode(gradeCode);
        classGrade.setClassName(goodsName+gradeCode);
        boolean save = iClassGradeService.save(classGrade);
        //绑定班级商品
        ClassGradeGoods classGradeGoods = new ClassGradeGoods();
        classGradeGoods.setGradeId(classGrade.getGradeId());
        classGradeGoods.setGoodsId(goodsId);
        classGradeGoods.setCreateTime(DateUtils.getNowTime());
        classGradeGoods.setUpdateTime(DateUtils.getNowTime());
        iClassGradeGoodsService.save(classGradeGoods);
        //锁定班级
        lockGrade(orderGoodsId,classGrade.getGradeId(),userId,goodsId,orderSn);
        return true;
    }

    /**
     * 锁定班级
     * @param orderGoodsId
     * @param gradeId
     * @param userId
     * @param goodsId
     * @param orderSn
     * @return
     */
    public boolean lockGrade(Long orderGoodsId,Long gradeId,Long userId,Long goodsId,String orderSn){
        //锁定班级
        ClassGradeUserTemp classGradeUserTemp = new ClassGradeUserTemp();
        classGradeUserTemp.setUserId(userId);
        classGradeUserTemp.setGradeId(gradeId);
        classGradeUserTemp.setStatus(ClassGradeUserTemp.STATUS_LOCK);
        classGradeUserTemp.setFromType(1);
        classGradeUserTemp.setGoodsId(goodsId);
        classGradeUserTemp.setOrderSn(orderSn);
        classGradeUserTemp.setCreateTime(DateUtils.getNowTime());
        classGradeUserTemp.setUpdateTime(DateUtils.getNowTime());
        iClassGradeUserTempService.save(classGradeUserTemp);
        //更新订单绑定班级ID
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderGoodsId(orderGoodsId);
        orderGoods.setGradeId(gradeId);
        orderGoods.setUpdateTime(DateUtils.getNowTime());
        iOrderGoodsService.updateById(orderGoods);
        return true;
    }

    @Override
    public boolean joinGrade(Long orderGoodsId,Long gradeId,Long userId){
        //进入班级
        ClassGradeUser classGradeUser = new ClassGradeUser();
        classGradeUser.setUserId(userId);
        classGradeUser.setGradeId(gradeId);
        classGradeUser.setStatus(1);
        //    classGradeUser.setCreateBy(SecurityUtils.getUsername());
        classGradeUser.setCreateBy("sys"); //系统分班
        classGradeUser.setFromType(1);
        classGradeUser.setOrderGoodsId(orderGoodsId);
        classGradeUser.setCreateTime(DateUtils.getNowTime());
        classGradeUser.setUpdateTime(DateUtils.getNowTime());
        iClassGradeUserService.save(classGradeUser);
        return true;
    }
}
