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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.SecurityUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.bank.domain.QuestionBusiness;
import com.zhongzheng.modules.goods.domain.Goods;
import com.zhongzheng.modules.goods.service.IGoodsService;
import com.zhongzheng.modules.grade.domain.ClassGrade;
import com.zhongzheng.modules.grade.domain.ClassGradeSys;
import com.zhongzheng.modules.grade.domain.ClassGradeUser;
import com.zhongzheng.modules.grade.service.IClassGradeService;
import com.zhongzheng.modules.grade.service.IClassGradeUserService;
import com.zhongzheng.modules.grade.vo.ClassGradeVo;
import com.zhongzheng.modules.order.bo.*;
import com.zhongzheng.modules.order.domain.Order;
import com.zhongzheng.modules.order.domain.OrderBusiness;
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.OrderListVo;
import com.zhongzheng.modules.order.vo.OrderVo;
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 IClassGradeUserService iClassGradeUserService;


    @Autowired
    private OrderMapper orderMapper;

    @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.eq(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) {
        return orderMapper.selectList(bo);
    }

    /**
    * 实体类转化成视图对象
    *
    * @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 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);

        //生成订单号
        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);
        //生成订单
        Collection<OrderGoods> coll = new HashSet<>();
        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.setCreateTime(DateUtils.getNowTime());
            orderGoods.setUpdateTime(DateUtils.getNowTime());
            coll.add(orderGoods);
            //订单价格不计算优惠
            totalPrice = totalPrice.add(g.getGoodsPrice());
            //暂不计算优惠券
            payPrice = payPrice.add(g.getGoodsPrice());
            //视频商品安排班级
            if(goods.getGoodsType()==1){
                if(g.getGoodsInputData().getGradeId()!=null){

                }
            }
        }
        iOrderGoodsService.saveBatch(coll);

        add.setOrderSn(out_trade_no);
        add.setOrderFrom(1);
        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
    public Boolean updateByEditBo(OrderEditBo bo) {
        Order update = BeanUtil.toBean(bo, Order.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        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);
    }


    /**
     * 加入班级
     * @param orderGoodsId
     * @param gradeId
     * @return
     */
    public boolean checkGrade(String goodsName,Long orderGoodsId,Long gradeId,Long userId){
        //指定班级
        if(gradeId!=null){
            ClassGradeVo classGradeVo = iClassGradeService.queryById(gradeId);
            if(classGradeVo==null){
                throw new CustomException("班级不存在");
            }
            LambdaQueryWrapper<ClassGradeUser> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ClassGradeUser::getGradeId,gradeId);
            lqw.eq(ClassGradeUser::getStatus,1);
            int studentNum = iClassGradeUserService.count(lqw);
            if(classGradeVo.getStudentUpper()>studentNum){
                //班级还有剩位,直接加入班级
                return joinGrade(orderGoodsId,gradeId,userId);
            }
        }else {
            //无指定班级

        }
        //创建新班级
        ClassGrade classGrade = new ClassGrade();
        classGrade.setStudentUpper(ClassGrade.INIT_UPPER); //上限300
        classGrade.setCreateTime(DateUtils.getNowTime());
        classGrade.setUpdateTime(DateUtils.getNowTime());
        String gradeCode = ServletUtils.getEncoded("BJ");
        classGrade.setGradeCode(gradeCode);
        classGrade.setClassName(goodsName+gradeCode);
        boolean save = iClassGradeService.save(classGrade);
        //加入班级
        joinGrade(orderGoodsId,classGrade.getGradeId(),userId);
        return false;
    }

    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.setFromType(1);
        classGradeUser.setOrderGoodsId(orderGoodsId);
        iClassGradeUserService.save(classGradeUser);
        //更新订单绑定班级ID
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderGoodsId(orderGoodsId);
        orderGoods.setGradeId(gradeId);
        iOrderGoodsService.updateById(orderGoods);
        return true;
    }
}
