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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
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.modules.goods.domain.Goods;
import com.zhongzheng.modules.goods.service.IGoodsService;
import com.zhongzheng.modules.grade.domain.ClassGradeUser;
import com.zhongzheng.modules.grade.service.IClassGradeUserService;
import com.zhongzheng.modules.order.bo.OrderGoodsQueryBo;
import com.zhongzheng.modules.order.bo.OrderGoodsRefundAddBo;
import com.zhongzheng.modules.order.bo.OrderGoodsRefundEditBo;
import com.zhongzheng.modules.order.bo.OrderGoodsRefundQueryBo;
import com.zhongzheng.modules.order.domain.Order;
import com.zhongzheng.modules.order.domain.OrderGoods;
import com.zhongzheng.modules.order.domain.OrderGoodsRefund;
import com.zhongzheng.modules.order.mapper.OrderGoodsRefundMapper;
import com.zhongzheng.modules.order.service.IOrderGoodsRefundService;
import com.zhongzheng.modules.order.service.IOrderGoodsService;
import com.zhongzheng.modules.order.service.IOrderService;
import com.zhongzheng.modules.order.vo.OrderGoodsRefundVo;
import com.zhongzheng.modules.order.vo.OrderGoodsVo;
import com.zhongzheng.modules.user.bo.UserExamRecordQueryBo;
import com.zhongzheng.modules.user.bo.UserStudyRecordQueryBo;
import com.zhongzheng.modules.user.domain.User;
import com.zhongzheng.modules.user.service.IUserExamRecordService;
import com.zhongzheng.modules.user.service.IUserStudyRecordService;
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 java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单商品退款Service业务层处理
 *
 * @author hjl
 * @date 2022-01-04
 */
@Service
public class OrderGoodsRefundServiceImpl extends ServiceImpl<OrderGoodsRefundMapper, OrderGoodsRefund> implements IOrderGoodsRefundService {

    @Autowired
    private IOrderGoodsService iOrderGoodsService;
    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private IGoodsService iGoodsService;
    @Autowired
    private IWxPayService iWxPayService;
    @Autowired
    private IClassGradeUserService iClassGradeUserService;
    @Autowired
    private IUserExamRecordService iUserExamRecordService;
    @Autowired
    private IUserStudyRecordService iUserStudyRecordService;

    @Override
    public OrderGoodsRefundVo queryById(Long refundId){
        OrderGoodsRefund db = this.baseMapper.selectById(refundId);
        return BeanUtil.toBean(db, OrderGoodsRefundVo.class);
    }

    @Override
    public List<OrderGoodsRefundVo> queryList(OrderGoodsRefundQueryBo bo) {
        LambdaQueryWrapper<OrderGoodsRefund> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getRefundSn()), OrderGoodsRefund::getRefundSn, bo.getRefundSn());
        lqw.eq(bo.getUserId() != null, OrderGoodsRefund::getUserId, bo.getUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getOrderSn()), OrderGoodsRefund::getOrderSn, bo.getOrderSn());
        lqw.eq(bo.getGoodsId() != null, OrderGoodsRefund::getGoodsId, bo.getGoodsId());
        lqw.eq(bo.getRefundFee() != null, OrderGoodsRefund::getRefundFee, bo.getRefundFee());
        lqw.eq(bo.getStatus() != null, OrderGoodsRefund::getStatus, bo.getStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getWxpayRefundId()), OrderGoodsRefund::getWxpayRefundId, bo.getWxpayRefundId());
        return entity2Vo(this.list(lqw));
    }

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

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

    @Override
    public Boolean placeRefundSmallOrder(OrderGoodsRefundAddBo bo) {
        OrderGoods orderGoods = iOrderGoodsService.getOne(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderSn,bo.getOrderSn())
                .eq(OrderGoods::getGoodsId, bo.getGoodsId()));
        if(Validator.isEmpty(orderGoods)){
            throw new CustomException("订单商品数据错误");
        }
        if(orderGoods.getPayStatus()!=3){
            throw new CustomException("订单商品尚未完全收费");
        }
        if(orderGoods.getRefundStatus()==2){
            throw new CustomException("订单商品已退款");
        }
        if(orderGoods.getRefundStatus()!=0){
            throw new CustomException("订单商品目前无法退款");
        }
        //订单商品
        Order order = iOrderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderSn,bo.getOrderSn()));
        if(order.getStatus()==0){
            throw new CustomException("订单无效");
        }
        if(order.getOrderFrom()!=2){
            throw new CustomException("不支持非小程序订单退款");
        }
        //订单商品
        Goods goods = iGoodsService.getOne(new LambdaQueryWrapper<Goods>().eq(Goods::getGoodsId,bo.getGoodsId()));
        if(goods.getGoodsType()==1){
            //视频商品
            UserStudyRecordQueryBo userStudyRecordQueryBo = new UserStudyRecordQueryBo();
            userStudyRecordQueryBo.setGoodsId(goods.getGoodsId());
            userStudyRecordQueryBo.setUserId(order.getUserId());
            Long userSeeTime = iUserStudyRecordService.getUserSeeTime(userStudyRecordQueryBo);
            if(userSeeTime.longValue()>=(30*60)){ //超30分钟不满足退款
                throw new CustomException("不满足退款");
            }
        }
        if(goods.getGoodsType()==2){
            //题库商品
            UserExamRecordQueryBo userExamRecordQueryBo = new UserExamRecordQueryBo();
            userExamRecordQueryBo.setGoodsId(goods.getGoodsId());
            userExamRecordQueryBo.setUserId(order.getUserId());
            Long doQuestionNum = iUserExamRecordService.getUserDoQuestionNum(userExamRecordQueryBo);
            if(doQuestionNum.longValue()>=30){ //超30道题不满足退款
                throw new CustomException("不满足退款");
            }
        }
        OrderGoodsRefund add = getOne(new LambdaQueryWrapper<OrderGoodsRefund>().eq(OrderGoodsRefund::getGoodsId,bo.getGoodsId()).eq(OrderGoodsRefund::getOrderSn,bo.getOrderSn()));
        String out_trade_no = null;
        if(Validator.isNotEmpty(add)){
            out_trade_no = add.getRefundSn();
        }else{
            add = BeanUtil.toBean(bo, OrderGoodsRefund.class);
            validEntityBeforeSave(add);
            add.setCreateTime(DateUtils.getNowTime());
            add.setUpdateTime(DateUtils.getNowTime());
            //退款单号
             out_trade_no = DateUtils.getDateOrderSn();
            add.setRefundSn(out_trade_no);
            add.setRefundFee(orderGoods.getGoodsReceived());
            add.setUserId(order.getUserId());
            this.save(add);
        }
        Map<String, String> payResult =  iWxPayService.refund(out_trade_no,order.getTransid(),add.getRefundFee(),order.getPayPrice());
        if("OK".equals(payResult.get("return_msg"))&&Validator.isNotEmpty(payResult.get("refund_id"))){
            return refundCall(payResult.get("refund_id"),add.getRefundId(),orderGoods.getOrderGoodsId(),order,goods.getGoodsType(),orderGoods.getGradeId(),bo.getUserId(),goods.getGoodsId());
        }else{

            throw new CustomException("退款错误"+ JSON.toJSONString(payResult));
        }
    }

    public Boolean refundCall(String WxpayRefundId,Long refundId,Long orderGoodsId,Order order,Long goodsType,Long gradeId,Long userId,Long goodsId){
        OrderGoodsRefund update = new OrderGoodsRefund();
        update.setRefundId(refundId);
        update.setUpdateTime(DateUtils.getNowTime());
        update.setWxpayRefundId(WxpayRefundId);
        this.updateById(update);
        //修改订单商品退款状态
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderGoodsId(orderGoodsId);
        orderGoods.setRefundStatus(2); //已退款
        orderGoods.setPayStatus(1); //未收费
        orderGoods.setUpdateTime(DateUtils.getNowTime());
        iOrderGoodsService.updateById(orderGoods);

        OrderGoodsQueryBo bo = new OrderGoodsQueryBo();
        bo.setOrderSn(order.getOrderSn());
        List<OrderGoodsVo> orderGoodsVoList = iOrderGoodsService.selectList(bo);
        boolean allRefund = true;
        for (OrderGoodsVo g : orderGoodsVoList) {
            if(g.getRefundStatus()!=2){
                allRefund = false;
            }
        }
        //都退款
        if(allRefund){
            order.setStatus(0);
            order.setUpdateTime(DateUtils.getNowTime());
            order.setOrderStatus(Order.REFUND_FULL);
        }else {
            //部分退款
            order.setUpdateTime(DateUtils.getNowTime());
            order.setOrderStatus(Order.REFUND_PART);
        }
        iOrderService.updateById(order);
        if(goodsType==1){
            //移除班级
            ClassGradeUser classGradeUser = iClassGradeUserService.getOne(new LambdaQueryWrapper<ClassGradeUser>().eq(ClassGradeUser::getGradeId,gradeId).eq(ClassGradeUser::getUserId,order.getUserId()).eq(ClassGradeUser::getStatus,1));
            if(Validator.isNotEmpty(classGradeUser)){
                classGradeUser.setStatus(0);
                iClassGradeUserService.updateById(classGradeUser);
            }
            //清除课程所有历史
            iUserStudyRecordService.delUserCourseHistory(userId,goodsId);
        }
        if(goodsType==2){
            //删除题库历史
            iUserExamRecordService.delUserBankHistory(userId,goodsId);
        }
        return true;
    }

    @Override
    public Boolean updateByEditBo(OrderGoodsRefundEditBo bo) {
        OrderGoodsRefund update = BeanUtil.toBean(bo, OrderGoodsRefund.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        return this.updateById(update);
    }

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

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