package com.hc.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.hc.business.dto.ZccmClassCourseDto;
import com.hc.business.dto.ZccmUserCourseDto;
import com.hc.business.mapper.*;
import com.hc.business.model.*;
import com.hc.business.service.AliPayService;
import com.hc.core.utils.constants.OrderConstants;
import com.hc.core.utils.pay.browser.alipay.bean.AliPayBean;
import com.hc.core.utils.pay.browser.alipay.processor.AliPayProcessor;
import com.hc.core.utils.pay.browser.alipay.bean.AliPayRefundBean;
import com.hc.core.utils.status.CourseFlagEnum;
import com.hc.core.utils.status.OrdersFlagEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 10696
 */

@Service
@Slf4j
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private AliPayProcessor aliPayProcessor;

    @Autowired
    private ZccmOrdersMapper ordersMapper;

    @Autowired
    private ZccmOrderUserLogMapper orderUserLogMapper;

    @Autowired
    private ZccmUserCourseMapper userCourseMapper;

    @Autowired
    private ZccmClassCourseMapper classCourseMapper;

    @Autowired
    private ZccmUserStatusMapper userStatusMapper;

    @Autowired
    private ZccmUserRefundHistoryMapper userRefundHistoryMapper;

    @Autowired
    private ZccmUserAdviseMapper userAdviseMapper;

    @Autowired
    private ZccmUserMapper userMapper;

    @Override
    public Map<String, String> alipay(AliPayBean aliPayBean) throws AlipayApiException {
        Map<String, String> map = new HashMap<>(2);
        String pay = aliPayProcessor.pay(aliPayBean);
        map.put("aliPay", pay);
        return map;
    }

    @Override
    public void returnNotifyUrlInfo(String outTradeNo, String tradeNo, String tradeStatus) {
        //判断交易状态

        String trade = "TRADE_SUCCESS";
        if (!trade.equals(tradeStatus)) {
            throw new RuntimeException("交易出错，支付回调失败");
        }

        //修改订单状态
        ZccmOrders orders = ordersMapper.queryByOrderNo(outTradeNo);
        orders.setTradeNo(tradeNo);
        orders.setOrderStatus(OrdersFlagEnum.ORDERS_FLAG_PAID.getCode());
        ordersMapper.updateByPrimaryKeySelective(orders);

        //查询订单中的用户
        Integer ordersId = orders.getOrdersId();
        Integer classId = orders.getClassId();
        List<ZccmOrderUserLog> orderUserLogs =
                orderUserLogMapper.queryByOrderId(ordersId);
        List<ZccmClassCourseDto> classCourseDtoList =
                classCourseMapper.queryByClassId(classId, CourseFlagEnum.COURSE_REQUIRE_CODE.getCode());

        if (CollectionUtils.isEmpty(orderUserLogs)) {
            if (CollectionUtils.isEmpty(classCourseDtoList)) {
                return;
            }
            return;
        }
        createUserAdvise(orderUserLogs);
        createUserCourse(classId, orderUserLogs, classCourseDtoList);
    }

    private void createUserAdvise(List<ZccmOrderUserLog> orderUserLogs) {
        orderUserLogs.forEach(orderUserLog -> {
            ZccmUserAdvise userAdvise = new ZccmUserAdvise();
            userAdvise.setAdviceType(1);
            userAdvise.setCreateTime(System.currentTimeMillis());
            userAdvise.setAdvise("报名成功,欢迎您的加入。");
            userAdvise.setUserId(orderUserLog.getReUserId());
            userAdvise.setTitle("报名成功");
            userAdviseMapper.insert(userAdvise);
        });
    }

    @Override
    public Map<String, String> refund(AliPayRefundBean aliPayRefundBean) throws AlipayApiException {

        String refund = aliPayProcessor.refund(aliPayRefundBean);
        JSONObject jsonObject = JSON.parseObject(refund);
        String code = (String) jsonObject.get("code");
        String outTradeNo = (String) jsonObject.get("out_trade_no");

        if (!OrderConstants.ORDER_REFUND.equals(code)) {
            throw new RuntimeException("交易出错,退款失败");
        }

        //修改订单状态
        ZccmOrders orders = ordersMapper.queryByOrderNo(outTradeNo);
        orders.setOrderStatus(OrdersFlagEnum.ORDERS_FLAG_REFUNDED.getCode());
        ordersMapper.updateByPrimaryKeySelective(orders);

        //修改退款状态
        ZccmUserRefundHistory userRefundHistory
                = userRefundHistoryMapper.queryByOrderNo(outTradeNo);
        userRefundHistory.setDoneTime(System.currentTimeMillis());
        userRefundHistoryMapper.updateByPrimaryKeySelective(userRefundHistory);

        //删除用户已选课程
        Integer classId = orders.getClassId();
        Integer userId = orders.getUserId();
        List<ZccmUserCourse> userCourses =
                userCourseMapper.selectUserCourseListByParam(userId, classId);
        userCourses.forEach(userCourse -> userCourseMapper.delete(userCourse));

        Map<String, String> map = new HashMap<>(2);
        map.put("refund", refund);
        return map;
    }

    private void createUserCourse(Integer classId,
                                  List<ZccmOrderUserLog> orderUserLogs,
                                  List<ZccmClassCourseDto> classCourseDtoList) {
        orderUserLogs.forEach(orderUserLog -> {
            Integer reUserId = orderUserLog.getReUserId();
            Integer ordersId = orderUserLog.getOrderId();
            //开用户状态
            List<ZccmUserStatus> userStatuses =
                    userStatusMapper.queryByClassIdAndUserId(classId, reUserId);
            if (CollectionUtils.isEmpty(userStatuses)) {
                ZccmUserStatus userStatus = new ZccmUserStatus();
                userStatus.setClassId(classId);
                userStatus.setOrderId(ordersId);
                userStatus.setUserId(reUserId);
                userStatus.setStatus(OrdersFlagEnum.ORDERS_FLAG_PAID.getCode());
                userStatusMapper.insert(userStatus);
            }
            //课程
            classCourseDtoList.forEach(classCourseDto -> {
                Integer courseId = classCourseDto.getCourseId();
                //是否已开
                List<ZccmUserCourseDto> userCourses
                        = userCourseMapper.selectUserCourseProgress(reUserId, classId, courseId);
                if (CollectionUtils.isEmpty(userCourses)) {
                    //开课
                    ZccmUserCourse userCourse = new ZccmUserCourse();
                    userCourse.setClassId(classId);
                    userCourse.setCourseId(courseId);
                    userCourse.setUserId(reUserId);
                    userCourse.setCoursePercent(0.00);
                    userCourseMapper.insert(userCourse);
                }
            });
        });
    }


}