package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.VideoLessonGroupDao;
import com.yonge.cooleshow.biz.dal.dto.UserAccountRecordDto;
import com.yonge.cooleshow.biz.dal.dto.req.OrderReq;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.dao.VideoLessonPurchaseRecordDao;
import com.yonge.cooleshow.biz.dal.enums.AccountBizTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.GoodTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.InOrOutEnum;
import com.yonge.cooleshow.biz.dal.service.SysConfigService;
import com.yonge.cooleshow.biz.dal.service.UserAccountService;
import com.yonge.cooleshow.biz.dal.service.VideoLessonPurchaseRecordService;
import com.yonge.cooleshow.biz.dal.vo.UserOrderDetailVo;
import com.yonge.cooleshow.biz.dal.vo.res.OrderCreateRes;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.exception.BizException;
import com.yonge.toolset.utils.obj.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * VideoLessonPurchaseRecordService服务实现类
 *
 * @author yzp
 * @version v1.0
 * @date 2022-03-26 00:01:38
 **/
@Service
public class VideoLessonPurchaseRecordServiceImpl extends ServiceImpl<VideoLessonPurchaseRecordDao, VideoLessonPurchaseRecord> implements VideoLessonPurchaseRecordService {

    private final static Logger log = LoggerFactory.getLogger(VideoLessonPurchaseRecordServiceImpl.class);

    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private VideoLessonPurchaseRecordDao videoLessonPurchaseRecordDao;
    @Autowired
    private VideoLessonGroupDao videoLessonGroupDao;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private SysConfigService sysConfigService;

    public VideoLessonPurchaseRecordDao getDao() {
        return videoLessonPurchaseRecordDao;
    }

    /**
     * @Description: 购买视频课
     * @Author: cy
     * @Date: 2022/4/24
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<OrderCreateRes> buyVideoCourse(OrderReq.OrderReqInfo orderReqInfo) {
        log.info("buyVideoCourse  param:{}", JSON.toJSONString(orderReqInfo));
        Long studentId = orderReqInfo.getUserId();
        String orderNo = orderReqInfo.getOrderNo();

        //校验学生信息
        getSysUser(studentId);

        ObjectMapper objectMapper = new ObjectMapper();
        VideoLessonPurchaseRecord purchaseRecord = objectMapper.convertValue(orderReqInfo.getBizContent(), VideoLessonPurchaseRecord.class);

        //校验视频课信息
        Long groupId = purchaseRecord.getVideoLessonGroupId();
        VideoLessonGroup lessonGroup = videoLessonGroupDao.selectById(groupId);
        if (lessonGroup == null) {
            throw new BizException("课程组不存在!");
        }

        //校验课程是否购买
        VideoLessonPurchaseRecord isAlreadyBuy= videoLessonPurchaseRecordDao.selectOne(Wrappers.<VideoLessonPurchaseRecord>lambdaQuery()
                .eq(VideoLessonPurchaseRecord::getStudentId, studentId)
                .eq(VideoLessonPurchaseRecord::getVideoLessonGroupId, groupId));
        if (!ObjectUtil.isEmpty(isAlreadyBuy)){
            throw new BizException("已购买过该课程");
        }

        purchaseRecord.setOrderNo(orderNo);
        purchaseRecord.setStudentId(studentId);
        purchaseRecord.setOrderStatus(0);
        purchaseRecord.setOriginalPrice(lessonGroup.getLessonPrice());//原价
        purchaseRecord.setExpectPrice(lessonGroup.getLessonPrice());//预计价格
        videoLessonPurchaseRecordDao.insert(purchaseRecord);

        OrderCreateRes orderCreateRes = new OrderCreateRes();
        orderCreateRes.setRes(true);
        orderCreateRes.setMerchId(lessonGroup.getTeacherId());
        orderCreateRes.setBizId(orderReqInfo.getCouponId());
        orderCreateRes.setOriginalPrice(lessonGroup.getLessonPrice());//原价
        orderCreateRes.setExpectPrice(lessonGroup.getLessonPrice());//预计价格
        orderCreateRes.setActualPrice(purchaseRecord.getPayMoney());//实际价格
        orderCreateRes.setGoodNum(lessonGroup.getLessonCount());
        orderCreateRes.setGoodType(GoodTypeEnum.VIDEO);
        HttpResponseResult<OrderCreateRes> httpResponseResult = new HttpResponseResult<>();
        httpResponseResult.setData(orderCreateRes);
        log.info("buyVideoCourse  return {}", httpResponseResult);
        return httpResponseResult;
    }

    /**
     * @Description: 购买视频课-成功-回调
     * @Author: cy
     * @Date: 2022/4/24
     */
    @Transactional(rollbackFor = Exception.class)
    public void buyVideoCourseSuccess(UserOrderDetailVo orderParam) {
        log.info("buyVideoCourseSuccess  param:{}", JSON.toJSONString(orderParam));
        String orderNo = orderParam.getOrderNo();

        VideoLessonPurchaseRecord purchaseRecord = videoLessonPurchaseRecordDao.selectOne(Wrappers.<VideoLessonPurchaseRecord>lambdaQuery()
                .eq(VideoLessonPurchaseRecord::getOrderNo, orderNo));
        if (purchaseRecord == null) {
            throw new BizException("课程组购买记录不存在!");
        }

        //支付状态改为1
        videoLessonPurchaseRecordDao.updateStatus(orderNo);

        //查询直播课服务费
        String videoServiceRateStr = sysConfigService.findConfigValue(SysConfigConstant.VIDEO_LESSON_SERVICE_FEE);
        BigDecimal liveServiceRate = new BigDecimal(videoServiceRateStr).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);

        //查询组信息
        VideoLessonGroup lessonGroup = videoLessonGroupDao.selectById(purchaseRecord.getVideoLessonGroupId());

        //记录流水
        BigDecimal payMoney = purchaseRecord.getPayMoney();//学生支付金额
        UserAccountRecordDto userAccountRecord = new UserAccountRecordDto();
        userAccountRecord.setUserId(lessonGroup.getTeacherId());
        //扣除手续费后所得金额
        userAccountRecord.setTransAmount(payMoney.subtract(payMoney.multiply(liveServiceRate)).setScale(2, RoundingMode.HALF_UP));
        userAccountRecord.setInOrOut(InOrOutEnum.IN);
        userAccountRecord.setBizType(AccountBizTypeEnum.VIDEO);
        userAccountRecord.setBizId(lessonGroup.getTeacherId());
        userAccountRecord.setBizName(lessonGroup.getLessonName());
        userAccountRecord.setOrderNo(orderNo);
        userAccountService.accountChange(userAccountRecord);
        log.info("buyVideoCourseSuccess ok");
    }

    /**
     * @Description: 购买视频课-失败-回调
     * @Author: cy
     * @Date: 2022/4/24
     */
    @Transactional(rollbackFor = Exception.class)
    public void buyVideoCourseFailed(UserOrderDetailVo orderParam) {
        String orderNo = orderParam.getOrderNo();

        VideoLessonPurchaseRecord videoGroup = videoLessonPurchaseRecordDao.selectOne(Wrappers.<VideoLessonPurchaseRecord>lambdaQuery()
                .eq(VideoLessonPurchaseRecord::getOrderNo, orderNo));
        if (videoGroup == null) {
            throw new BizException("课程组不存在!");
        }

        //删除video_lesson_purchase_record数据
        videoLessonPurchaseRecordDao.delete(Wrappers.<VideoLessonPurchaseRecord>lambdaQuery()
                .eq(VideoLessonPurchaseRecord::getOrderNo, orderNo));
        log.info("buyVideoCourseFailed ok");
    }

    /**
     * 获取用户信息
     */
    private SysUser getSysUser(Long userId) {
        return Optional.ofNullable(userId)
                .map(sysUserFeignService::queryUserById)
                .orElseThrow(() -> new BizException("用户不存在"));
    }
}