package com.ym.mec.biz.service.impl;


import com.ym.mec.biz.dal.entity.SysAccount;
import com.ym.mec.biz.service.PayService;
import com.ym.mec.biz.service.StudentPaymentOrderService;
import com.ym.mec.biz.service.SysAccountService;
import com.ym.mec.thirdparty.union.UnionPay;
import com.ym.mec.thirdparty.union.UnionPayFeignService;
import com.ym.mec.thirdparty.yqpay.YqPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 支付服务类
 */
@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private UnionPayFeignService unionPayFeignService;
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private SysAccountService sysAccountService;


    /**
     * 返回订单提交数据
     *
     * @param amount       金额
     * @param orderNo      订单编号
     * @param notifyUrl    异步通知地址
     * @param returnUrl    支付返回地址
     * @param orderSubject 订单标题
     * @param orderBody    订单内容
     * @return
     * @throws Exception
     */
    public Map getPayMap(BigDecimal amount, String orderNo, String notifyUrl, String returnUrl, String orderSubject, String orderBody) throws Exception {
        //支付通道决策
        SysAccount routingAccount = getRoutingAccount(amount);
        HashMap<String, Object> unionPay = new HashMap<>();
        String type = "YQPAY";
        Map payMap;
//        if (routingAccount != null) {
//            //易乾支付
//            payMap = YqPayUtil.getPayMap(amount, orderNo, notifyUrl, returnUrl, orderSubject, orderBody, routingAccount.getMerNo());
//        } else {
//            type = "UNIONPAY";
//            payMap = UnionPay.getPayMap(amount, orderNo, notifyUrl, returnUrl, orderSubject);
//        }
        type = "UNIONPAY";
        payMap = UnionPay.getPayMap(amount, orderNo, notifyUrl, returnUrl, orderSubject);
        unionPay.put("orderNo", orderNo);
        unionPay.put("type", type);
        unionPay.put("payMap", payMap);
        return unionPay;
    }

    public Map<String, Object> query(String orderNo) throws Exception {
        return new UnionPay(unionPayFeignService).query(orderNo);
    }


    private SysAccount getRoutingAccount(BigDecimal money) {
        SysAccount routingAccount = null;
        int payOrderNums = studentPaymentOrderService.findPayOrderNum(); //获取支付中和成功的订单数
        //分佣账户（1、每10笔，前四笔收入私户)
        int rem = (payOrderNums + 1) % 10;
        if (rem > 0 && rem <= 5) { //私人账户
            routingAccount = sysAccountService.getPerAccount(money);
        }

        //临时全返回双乾
        routingAccount = sysAccountService.getPerAccount(money);

        return routingAccount;
    }

}
