package com.thinkgem.jeesite.modules.pay.service;

import com.alibaba.fastjson.JSONObject;
import com.thinkgem.jeesite.common.baseBean.Request;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.constant.ComCode;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.modules.commonError.MyException;
import com.thinkgem.jeesite.modules.pay.dao.PayApiDao;
import com.thinkgem.jeesite.modules.pay.entity.BenefitEntity;
import com.thinkgem.jeesite.modules.pay.entity.OrderEntity;
import com.thinkgem.jeesite.modules.pay.entity.RateEntity;
import com.thinkgem.jeesite.modules.pay.entity.UserRateEntity;
import com.thinkgem.jeesite.modules.pay.juhezhong.dto.ApiQuickPayDto;
import com.thinkgem.jeesite.modules.pay.juhezhong.dto.MerchantDto;
import com.thinkgem.jeesite.modules.pay.juhezhong.dto.QuickDto;
import com.thinkgem.jeesite.modules.pay.juhezhong.service.JuHeZhongPayService;
import com.thinkgem.jeesite.modules.user.bean.JuHeZhongPayRequest;
import com.thinkgem.jeesite.modules.user.entity.CardEntity;
import com.thinkgem.jeesite.modules.user.entity.UserEntity;
import com.thinkgem.jeesite.modules.user.service.UserApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 支付相关
 */
@Service
@Transactional(readOnly = true)
public class PayApiService {
    @Autowired
    private PayApiDao payDao;
    @Autowired
    private UserApiService userService;
    @Autowired
    private JuHeZhongPayService juHeZhongPayService;

    @Transactional(readOnly = false)
    public void quickPay(JuHeZhongPayRequest request) throws MyException, Exception {
        // 1. 根据入参获取用户详情信息，包括支付卡片信息
        UserEntity userEntity = userService.getUserInfo(new Request(request.getSubMerchantCode()));
        userEntity = userService.getUserDetailInfo(userEntity);
        userEntity.getUserDetail().setCard(userService.getCardInfo(request));
        // 2. 创建支付订单信息，并保存
        String code = IdGen.randomBase62(64);
        String payNo = ComCode.YYYYMMDDHHMM.format(new Date()) + IdGen.randomBase62(8); // 订单号
        String payCode = IdGen.randomBase62(64);
        OrderEntity orderEntity = new OrderEntity(code, request.getSubMerchantCode(), payNo, payCode, request.getPayChannel(), "1", request.getAmount(), request.getSubject(), "", String.valueOf("D".equalsIgnoreCase(userEntity.getUserDetail().getCard().getCardType()) ? 5 : ("C".equalsIgnoreCase(userEntity.getUserDetail().getCard().getCardType()) ? 6 : 0)), request.getCardCode());
        payDao.saveOrderInfo(orderEntity);
        // 3. 创建分润信息，并保存
        Map<String, String> userBenefits = getUserBenefit(userEntity, request);
        for (String key : userBenefits.keySet()) {
            String benefitCode = IdGen.randomBase62(64);
            BenefitEntity benefitEntity = new BenefitEntity(benefitCode, request.getSubMerchantCode(), code, request.getPayChannel(), "0", "A", userBenefits.get(key), "");
            payDao.saveBenefitInfo(benefitEntity);
        }
        // 4. JuHeZhong支付
        quickPayJuHeZhongPay(userEntity, orderEntity, request);
    }

    /*
     * 以下为类内使用方法
     */

    /**
     * JuHeZhong快捷支付
     *
     * @param userEntity
     * @param request
     * @throws Exception
     */
    public void quickPayJuHeZhongPay(UserEntity userEntity, OrderEntity orderEntity, JuHeZhongPayRequest request) throws Exception {
        // 快捷支付
//        ApiQuickPayDto quickPayDto = new ApiQuickPayDto();
//        quickPayDto.setMerchantId(ComCode.MERCHANT_ID);
//        quickPayDto.setOrderId(orderEntity.getPayCode()); // 将订单的支付号传给第三方平台
//        quickPayDto.setSubMchId(userEntity.getUserDetail().getCard().getSubMerchantId());//子商户号
//        quickPayDto.setAmount(Long.parseLong(request.getAmount()));
//        quickPayDto.setBody(request.getSubject());
//        quickPayDto.setType("D".equalsIgnoreCase(userEntity.getUserDetail().getCard().getCardType()) ? 5 : ("C".equalsIgnoreCase(userEntity.getUserDetail().getCard().getCardType()) ? 6 : 0));
//        quickPayDto.setAccName(userEntity.getUserDetail().getRealName());
//        quickPayDto.setAccNo(userEntity.getUserDetail().getCard().getCardNo());
//        quickPayDto.setMobile(userEntity.getUserDetail().getCard().getCardMobile());
//        quickPayDto.setIdNo(userEntity.getUserDetail().getIdCard());
//
//
//        quickPayDto.setAccName("聂换换");
//        quickPayDto.setAccNo("6217000180000770507");
//        quickPayDto.setMobile("13722537737");
//        quickPayDto.setIdNo("130434199212214429");
//        quickPayDto.setFrontUrl("");// 前台地址
//        quickPayDto.setNotifyUrl("");// 通知url
//        quickPayDto.setTimestamp(System.currentTimeMillis());
//        quickPayDto.setMerchantKey(ComCode.MERCHANT_KEY);


        QuickDto quickDto = new QuickDto();
        quickDto.setTrxType(3);
        quickDto.setMerchantId(ComCode.MERCHANT_ID);
        quickDto.setOrderId(orderEntity.getPayCode()); // 将订单的支付号传给第三方平台
        quickDto.setAmount(Long.parseLong(request.getAmount()));
        quickDto.setBankNo(userEntity.getUserDetail().getCard().getCardNo()); // 支付卡号
        quickDto.setSettleBankName(userEntity.getUserDetail().getCard().getBelongBank());
        quickDto.setSettleBankNo(userEntity.getUserDetail().getIdCard());
        quickDto.setSettleBankPhone(userEntity.getUserDetail().getCard().getCardMobile());
        quickDto.setName(userEntity.getUserDetail().getRealName());
        quickDto.setCertificateCode(userEntity.getUserDetail().getIdCard());

        quickDto.setType("D".equalsIgnoreCase(userEntity.getUserDetail().getCard().getCardType()) ? 5 : ("C".equalsIgnoreCase(userEntity.getUserDetail().getCard().getCardType()) ? 6 : 0));

        RateEntity rateEntity = new RateEntity();
        rateEntity.setUserLevel(userEntity.getLevel());
        rateEntity.setPayMethod("quick");
        rateEntity = userService.getRateByLevel(rateEntity);
        if(rateEntity!=null){
            quickDto.setUserFee(new BigDecimal(Long.parseLong(request.getAmount())*Double.valueOf(rateEntity.getRate()))); // 手续费 单位：分 ，D0 业务必传
        }else{
            quickDto.setUserFee(new BigDecimal(0));
        }
        quickDto.setFrontUrl(Global.getConfig("sys.pre.url")+"/api/pay/notifyPay");// 前台地址
        quickDto.setNotifyUrl(Global.getConfig("sys.pre.url")+"/api/pay/notifyPay");// 通知url
        quickDto.setTimestamp(System.currentTimeMillis());
        quickDto.setMerchantKey(ComCode.MERCHANT_KEY);
        JSONObject jsonObject = juHeZhongPayService.quickPay(quickDto);
        if (!"0000".equals(jsonObject.getString("code"))) {
            throw new MyException(jsonObject.getString("msg"));
        }
    }

    public Map<String, String> getUserBenefit(UserEntity userEntity, JuHeZhongPayRequest request) {
        Map<String, String> userBenefit = new HashMap<>();
        String[] pathIds = (userEntity.getRecommendedPath() + userEntity.getId() + ",").split(",");
        // 获取三级的会员
        List<UserRateEntity> pathCDEUsers = payDao.getCDEUsers(pathIds);
        int countLevelC = 0;
        // 判断上级有几个黄金会员（C）
        for (UserRateEntity entity : pathCDEUsers) {
            // 不考虑该用户本身
            if (entity.getUserCode().equals(userEntity.getCode())) {
                continue;
            }
            if ("C".equals(entity.getUserLevel())) {
                countLevelC++;
            }
        }
        double minRate = 1;
        int levelCPosition = 0;
        for (UserRateEntity entity : pathCDEUsers) {
            levelCPosition++;
            minRate = minRate >= Double.parseDouble(entity.getRate()) ? Double.parseDouble(entity.getRate()) : minRate;
            if (entity.getUserCode().equals(userEntity.getCode())) {
                continue;
            }
            // 只有黄金会员（C）以上才分润
            if ("C".equals(entity.getUserLevel())) {
                double percent = countLevelC == 1 ? 1d : (levelCPosition == 2 ? 0.95 : 0.05);
                userBenefit.put(entity.getUserCode(), String.valueOf((minRate - Double.parseDouble(entity.getRate())) > 0 ? (minRate - Double.parseDouble(entity.getRate())) * Double.parseDouble(request.getAmount()) * percent : "0"));
            }
        }
        // 获取顶级管理员
        List<UserRateEntity> pathSABUsers = payDao.getSABUsers(pathIds);
        for (UserRateEntity entity : pathSABUsers) {
            userBenefit.put(entity.getUserCode(), String.valueOf((minRate - Double.parseDouble(entity.getRate())) * Double.parseDouble(request.getAmount())));
            minRate = Double.valueOf(entity.getRate());
        }
        return userBenefit;
    }

    /**
     * 回调
     * @param orderEntity
     * @return
     * @throws Exception
     */
    public OrderEntity notifyPay(OrderEntity orderEntity) throws Exception {
        QuickDto dto = new QuickDto();
        dto.setOrderId(orderEntity.getPayNo());
        dto.setMerchantId(ComCode.MERCHANT_ID);
        dto.setMerchantKey(ComCode.MERCHANT_KEY);
        JSONObject jsonObject = juHeZhongPayService.query(dto);

        // 支付成功
        if("0000".equals(jsonObject.get("code"))){
            orderEntity.setPayStatus("2");
            payDao.updateOrderStatus(orderEntity);
        }else if("0001".equals(jsonObject.get("code"))){ // 支付失败
            orderEntity.setPayStatus("4");
            payDao.updateOrderStatus(orderEntity);
        }
        orderEntity = payDao.getOrder(orderEntity);
        return orderEntity;
    }

}
