package com.bohuikeji.delivery.backstage.constants;

import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountPay;
import com.bohuikeji.delivery.backstage.pay.*;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.entity.sys.SysError;
import com.bohuikeji.frame.module.admin.entity.vo.AliReturnPayVo;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.wxpay.WXPayUtil;
import com.bohuikeji.frame.module.admin.wxpayv3.WxPayV3Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * 支付参数整理
 */
@Slf4j
public class payConst {
    @Autowired
    ITCourierPayService courierPayService;
    @Autowired
    ITCustomerPayService customerPayService;
    @Autowired
    ITStoreWalletPayService storeWalletPayService;
    @Autowired
    ITRewardPayService rewardPayService;
    @Autowired
    ITwalletDetailService twalletDetailService;
    @Autowired
    ITGiveDetailService giveDetailService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    ITPayService payService;

    /**
     * 业务、优惠支付生成预支付订单参数处理
     * @return
     */
    public static String getway(String type) {
        String payWay;
        switch (type){
            case "APP":
                payWay="微信";break;
            case "JSAPI":
                payWay="微信";break;
            case "alipay":
                payWay="支付宝APP";break;
            case "aliClient":
                payWay="支付宝APPLET";break;
            case "baidu":
                payWay="百度";break;
            case "douyin":
                payWay="抖音";break;
            case "kuaiShou":
                payWay="快手";break;
            default:
                return null;
        }
        return payWay;
    }


    /**
     * 各支付平台返回预支付记录
     * @param type
     * @param payNum
     * @param openId
     * @param orderPrice
     * @param request
     * @return
     * @throws Exception
     */
    public static JSONObject getObject(String type, String payNum,String openId, BigDecimal orderPrice, HttpServletRequest request)throws Exception {
        JSONObject object= new JSONObject();
        String prepayId;
        switch (type){
            case "APP":
                prepayId = WxPayV3Util.V3cusAppPay("v3/pay/transactions/app",payNum,new BigDecimal(WXPayUtil.changeToFen(orderPrice)),"业务订单支付",request);
                object = JSONObject.parseObject(WxPayV3Util.WxAppTuneUp(prepayId).toString());break;
            case "JSAPI":
                prepayId = WxPayV3Util.V3JsapiPay("v3/pay/transactions/jsapi",payNum,new BigDecimal(WXPayUtil.changeToFen(orderPrice)),openId,"业务订单支付",request);
                object = JSONObject.parseObject(WxPayV3Util.WxTuneUp(prepayId).toString());break;
            case "alipay":
                String rs = AliPay.aliAppPay(payNum, orderPrice.setScale(2,BigDecimal.ROUND_DOWN).stripTrailingZeros().toPlainString());
                object.put("alipay",rs);break;
            case "aliClient":
                BigDecimal aliOrderPrice = orderPrice;
                object = AliPay.alipayClient(payNum, aliOrderPrice.setScale(2,BigDecimal.ROUND_DOWN).stripTrailingZeros().toPlainString(),openId);break;
            case "baidu":
                object.put("baidu",BaiduPay.getBaiDuOrderInfo(payNum,payNum,orderPrice));break;
            case "douyin":
                object = BytePay.getByteOrderInfo(payNum,orderPrice);break;
            case "kuaiShou":
                object = KuaiShouPay.kuaishouOrder(payNum,orderPrice,openId);break;
            default:
                return null;
        }
        return object;
    }

    /**
     * 各支付平台返回预支付记录
     * @param type
     * @param payNum
     * @param openId
     * @param orderPrice
     * @param request
     * @return
     * @throws Exception
     */
    public static JSONObject getAliObject(String type,String channelType,String payNum,String openId, BigDecimal orderPrice, HttpServletRequest request)throws Exception {
        JSONObject object;
        switch (type){
            case "aliClient":
                log.info("####################支付小程序名称：{}",channelType);
                BigDecimal aliOrderPrice = orderPrice;
                object = AliPayV2.alipayClient(payNum,channelType,aliOrderPrice.setScale(2,BigDecimal.ROUND_DOWN).stripTrailingZeros().toPlainString(),openId);break;
            default:
                return null;
        }
        return object;
    }

    /**
     * 百度、抖音、快手 支付渠道选择
     * 根据回调的支付状态选择支付渠道（此为支付成功后回调的业务处理）
     * @param jsonObject
     * @return
     */
    public static String getAllPayChannel(JSONObject jsonObject) {
        String payChannel=null;
        //百度支付渠道选择
        if(jsonObject.getInteger("payType") != null){
            switch (jsonObject.getInteger("payType")){
                case 1087:
                    payChannel = "百度-支付宝";break;
                case 1108:
                    payChannel = "百度钱包";break;
                case 1117:
                    payChannel = "百度-微信";break;
                case 1124:
                    payChannel = "百度-花呗";break;
                case 10001:
                    payChannel = "银联对公支付";break;
                case 10002:
                    payChannel = "银联对私支付";break;
                case 10003:
                    payChannel = "汇付天下";break;
                case 10004:
                    payChannel = "百度闪付";break;
                default:
                    return null;
            }
        }//抖音支付渠道选择
        if(jsonObject.getInteger("way") != null){
            switch (jsonObject.getInteger("way")){
                case 1:
                    payChannel = "抖音-微信";break;
                case 2:
                    payChannel = "抖音-支付宝";break;
                default:
                    return null;
            }
        }//快手支付渠道选择
        if(StringUtils.isNotBlank(jsonObject.getString("channel"))){
            switch (jsonObject.getString("channel")){
                case "WECHAT":
                    payChannel = "快手-微信";break;
                case "ALIPAY":
                    payChannel = "快手-支付宝";break;
                default:
                    return null;
            }
        }
        return payChannel;
    }

    /**
     * 百度、抖音、快手 支付渠道选择
     * 根据回调的支付状态选择支付渠道（此为支付成功后回调的业务处理）
     * @param jsonObject
     * @return
     */
    public static String getPayNum(JSONObject jsonObject,AliReturnPayVo req) {
        String payNum=null;
        //微信支付：支付单号
        if(jsonObject !=null && jsonObject.getString("trade_type")!=null){
            payNum=jsonObject.getString("out_trade_no");
        }//支付宝支付：支付单号
        if(req != null){
            payNum = req.getOut_trade_no();
        }//百度支付：支付单号
        if(jsonObject !=null && jsonObject.getInteger("payType")!=null){
            payNum = jsonObject.getString("tpOrderId");
        }//抖音支付：支付单号
        if(jsonObject !=null && jsonObject.getString("msg") != null){
            log.info("抖音小程序支付回调参数@@：[{}]", jsonObject);
            JSONObject msgjson= JSONObject.parseObject(jsonObject.getString("msg"));
            payNum = msgjson.getString("cp_orderno");
        }//快手支付：支付单号
        if(jsonObject !=null && jsonObject.getJSONObject("data")!=null){
            log.info("快手小程序支付回调参数@@：[{}]", jsonObject);
            JSONObject msgjson= jsonObject.getJSONObject("data");
            payNum = msgjson.getString("out_order_no");
        }
        log.error("平台回调的支付单号：[{}]",payNum);
        return payNum;
    }

    /**
     * 微信、支付宝 支付回调监听判断
     */
    public static void getString(TPay pay, TCourierPay tCourierPay, TCustomerPay tCustomerPay, TRewardPay rewardPay, TStoreWalletPay walletPay, TDiscountPay discountPay, JSONObject jsonObject, AliReturnPayVo req) {
        if(tCourierPay == null && tCustomerPay == null && pay == null && rewardPay ==null && walletPay==null){
            SysError.saveError("支付回调处理失败，订单：{0}丢失，系统未找到记录",jsonObject==null? req.getOut_trade_no():jsonObject);return;
        }
        if(tCourierPay != null && "已支付".equals(tCourierPay.getPayStatus())){
            log.error("【入驻缴费】该支付记录已支付，不可以重复提交支付,订单记录表：[{}]",tCourierPay.getPayNum());return;
        }
        if(tCustomerPay != null && "已支付".equals(tCustomerPay.getPayStatus())){
            log.error("【客户钱包充值】该支付记录已支付，不可以重复提交支付,订单记录表：[{}]",tCustomerPay.getPayNum());return;
        }
        if(pay != null && "已支付".equals(pay.getPayStatus())){
            log.error("【订单支付】该支付记录已支付，不可以重复提交支付,订单记录表：[{}]",pay.getPayNum());return;
        }
        if(rewardPay != null && "已支付".equals(rewardPay.getPayStatus())){
            log.error("【打赏支付】该支付记录已支付，不可以重复提交支付,订单记录表：[{}]",rewardPay.getPayNum());return;
        }
        if(walletPay != null && "已支付".equals(walletPay.getPayStatus())){
            log.error("【门店钱包充值】该支付记录已支付，不可以重复提交支付,订单记录表：[{}]",rewardPay.getPayNum());return;
        }
        if(discountPay != null && "已支付".equals(discountPay.getPayStatus())){
            log.error("【购买优惠充值】该支付记录已支付，不可以重复提交支付,订单记录表：[{}]",discountPay.getPayNum());return;
        }
        log.error("进入支付订单查重判断");
        //payConst.getTest(pay,tCourierPay,tCustomerPay,rewardPay,walletPay,jsonObject,req);
    }

}
