package com.wteam.framework.modules.pay.serviceimpl;

import com.egzosn.pay.common.bean.PayOrder;
import com.egzosn.pay.common.bean.RefundOrder;
import com.egzosn.pay.common.bean.RefundResult;
import com.egzosn.pay.wx.v3.bean.WxTransactionType;
import com.wteam.framework.common.enums.ResultCode;
import com.wteam.framework.common.exception.ServiceException;
import com.wteam.framework.common.utils.SpringContextUtil;
import com.wteam.framework.common.vo.ResultMessage;
import com.wteam.framework.modules.book.entity.OrderInfo;
import com.wteam.framework.modules.book.service.OrderInfoService;
import com.wteam.framework.modules.pay.entity.dto.PayParam;
import com.wteam.framework.modules.pay.entity.enums.PaymentClientEnum;
import com.wteam.framework.modules.pay.entity.enums.PaymentMethodEnum;
import com.wteam.framework.modules.pay.entity.vo.OrderStatusEnum;
import com.wteam.framework.modules.pay.service.Payment;
import com.wteam.framework.modules.system.service.SettingService;
import com.wteam.framework.modules.user.entity.User;
import com.wteam.framework.modules.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

/**
 * 收银台工具
 *
 * @author Chopper
 * @since 2020-12-19 09:25
 */
@Component
@Slf4j
public class CashierSupport {
//    /**
//     * 收银台
//     */
//    @Autowired
//    private List<CashierExecute> cashierExecuteList;
    /**
     * 配置
     */
    @Autowired
    private SettingService settingService;

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private UserMapper userMapper;


    /**
     * 支付
     *
     * @param paymentMethodEnum 支付渠道枚举
     * @return 支付消息
     */
    public ResultMessage<Object> payment(PaymentMethodEnum paymentMethodEnum, PaymentClientEnum paymentClientEnum,
                                         HttpServletRequest request, HttpServletResponse response,
                                         String sn) {
        if (paymentClientEnum == null || paymentMethodEnum == null) {
            throw new ServiceException(ResultCode.PAY_NOT_SUPPORT);
        }
        //获取支付插件
        Payment payment = (Payment) SpringContextUtil.getBean(paymentMethodEnum.getPlugin());
        log.info("支付请求：客户端：{},支付类型：{},请求订单号：{}", paymentClientEnum.name(), paymentMethodEnum.name(), sn);
        //支付方式调用
        switch (paymentClientEnum) {
            case JSAPI:
                return payment.jsapiPay(request, sn, paymentMethodEnum);
            default:
                return null;
        }
    }

//    /**
//     * 支付 支持的支付方式
//     *
//     * @param client 客户端类型
//     * @return 支持的支付方式
//     */
//    public List<String> support(String client) {
//
//        ClientTypeEnum clientTypeEnum;
//        try {
//            clientTypeEnum = ClientTypeEnum.valueOf(client);
//        } catch (IllegalArgumentException e) {
//            throw new ServiceException(ResultCode.PAY_CLIENT_TYPE_ERROR);
//        }
//        //支付方式 循环获取
//        Setting setting = settingService.get(SettingEnum.PAYMENT_SUPPORT.name());
//        PaymentSupportSetting paymentSupportSetting = JSONUtil.toBean(setting.getSettingValue(), PaymentSupportSetting.class);
//        for (PaymentSupportItem paymentSupportItem : paymentSupportSetting.getPaymentSupportItems()) {
//            if (paymentSupportItem.getClient().equals(clientTypeEnum.name())) {
//                return paymentSupportItem.getSupports();
//            }
//        }
//        throw new ServiceException(ResultCode.PAY_NOT_SUPPORT);
//    }
//

    /**
     * 支付回调
     *
     * @param paymentMethodEnum 支付渠道枚举
     * @return 回调消息
     */
    public String callback(PaymentMethodEnum paymentMethodEnum,
                           HttpServletRequest request) {

        log.info("支付回调：支付类型：{}", paymentMethodEnum.name());

        //获取支付插件
        Payment payment = (Payment) SpringContextUtil.getBean(paymentMethodEnum.getPlugin());
        return payment.callBack(request);
    }

    /**
     * 支付通知
     *
     * @param paymentMethodEnum 支付渠道
     */
    public void notify(PaymentMethodEnum paymentMethodEnum,
                       HttpServletRequest request) {

        log.info("支付异步通知：支付类型：{}", paymentMethodEnum.name());

        //获取支付插件
        Payment payment = (Payment) SpringContextUtil.getBean(paymentMethodEnum.getPlugin());
        payment.notify(request);
    }
//
//    /**
//     * 用户提现
//     *
//     * @param paymentMethodEnum   支付渠道
//     * @param memberWithdrawApply 用户提现申请
//     */
//    public boolean transfer(PaymentMethodEnum paymentMethodEnum, MemberWithdrawApply memberWithdrawApply) {
//        Payment payment = (Payment) SpringContextUtil.getBean(paymentMethodEnum.getPlugin());
//        return payment.transfer(memberWithdrawApply);
//    }
//

    /**
     * 获取收银台参数
     *
     * @param sn 订单号
     * @return 收银台参数
     */
    public PayOrder cashierParam(String sn, PaymentMethodEnum paymentMethodEnum) {
        OrderInfo orderInfo = orderInfoService.query().eq("id", sn).one();
        //如果订单不需要付款，则抛出异常，直接返回
        if (orderInfo.getOrderPrice() <= 0 || OrderStatusEnum.PAID.name().equals(orderInfo.getOrderState())) {
            throw new ServiceException(ResultCode.PAY_UN_WANTED);
        }
        WxTransactionType transactionType = WxTransactionType.valueOf(paymentMethodEnum.paymentMethod());
        PayOrder order = new PayOrder("开通会员", orderInfo.getPhoneNumber(), BigDecimal.valueOf(orderInfo.getOrderPrice()), sn, transactionType);
        User user = userMapper.selectById(orderInfo.getUserId());
        order.setOpenid(user.getOpenId());
        return order;
    }


    /**
     * 支付结果
     *
     * @param payParam
     * @return
     */
    public Boolean paymentResult(PayParam payParam) {
//        //查询数据库
//        Boolean flag =orderInfoService.paymentResult(payParam);
//        if (flag == false) {
//            //TODO 未支付，调取查单接口 获取支付插件
//            String plugin = PaymentMethodEnum.valueOf(payParam.getOrderType()).getPlugin();
//            Payment payment = (Payment) SpringContextUtil.getBean(plugin);
//        }
//        //TODO 延时修改数据库
//        return flag;
        return true;
    }


    /**
     * 退款参数封装
     *
     * @param paymentMethodEnum 支付渠道枚举
     * @param request
     * @param sn
     * @return 退款消息
     */
    public RefundResult refund(PaymentMethodEnum paymentMethodEnum, HttpServletRequest request, String sn) {
        if (paymentMethodEnum == null) {
            throw new ServiceException(ResultCode.PAY_NOT_SUPPORT);
        }
        //获取支付插件
        Payment payment = (Payment) SpringContextUtil.getBean(paymentMethodEnum.getPlugin());
        log.info("支付请求：支付类型：{},请求订单号：{}", paymentMethodEnum.name(), sn);
        //退款插件调用
        return payment.refund(paymentMethodEnum, request, sn);
    }
}
