package com.tzy.framework.pay.service;

import com.alibaba.fastjson.JSONObject;
import com.tzy.base.dto.DictBaseDto;
import com.tzy.base.service.SysBaseService;
import com.tzy.common.exception.ServiceException;
import com.tzy.common.utils.StringUtils;
import com.tzy.common.utils.http.HttpClientUtil;
import com.tzy.framework.pay.config.PayConfig;
import com.tzy.framework.pay.dto.PaymentInfoResponseDto;
import com.tzy.framework.pay.dto.PaymentRequestDto;
import com.tzy.framework.pay.dto.RefundRequestDto;
import com.tzy.framework.pay.dto.ResultMap;
import com.tzy.framework.pay.service.*;
import com.tzy.framework.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service("paymentBaseConfigService")
public class PaymentBaseService {

    public static final String NEW_PAY_MODAL = "new_pay_modal";
    @Autowired
    protected SysBaseService sysBaseService;
    @Autowired
    protected HmPayService hmPayService;
    @Autowired
    protected QmPayService qmPayService;
    @Autowired
    protected QmH5PayService qmH5PayService;
    @Autowired
    protected WxPayService wxPayService;
    @Autowired
    protected AlipayService alipayApiService;
    @Autowired
    protected BfPayService bfPayService;
    @Autowired
    protected RedisUtils redisUtils;
    @Autowired
    protected PayConfig payConfig;
    @Autowired
    protected HfPayService hfPayService;
    @Autowired
    protected BaoFooPayService baoFooPayService;
    @Autowired
    protected BaoFooBankPayService baoFooBankPayService;
    @Autowired
    protected BankService bankService;
    @Autowired
    protected BofooAgreementService bofooAgreementService;
    @Autowired
    protected BaofooRechargePayService baofooRechargePayService;
    @Autowired
    protected Qme1PayService qme1PayService;
    @Value("${pay.recharge.readPay:http://localhost:8082/p1/readPay}")
    protected String readPayUrl;
    @Value("${pay.recharge.confirmPay:http://localhost:8082/p1/confirmPay}")
    protected String confirmPayUrl;
    @Value("${pay.server.refund:http://localhost:8082/p1/v2/refund}")
    protected String refundUrl;
    @Value("${pay.server.refundQuery:http://localhost:8082/p1/v2/refundQuery}")
    protected String refundQueryUrl;
    @Value("${pay.server.query:http://localhost:8082/p1/query}")
    protected String queryUrl;

    public JSONObject initPayConfig(String payWay){
        return JSONObject.parseObject(sysBaseService.getAppMenuByCode(payWay));
    }
    /**
     * 判断是否是在新支付模块中指定的通道
     * @param payway
     * @throws Exception
     */
    public void isNewPayModal(String payway) throws Exception{
        List<DictBaseDto> dictBaseDtos = sysBaseService.selectDictData(NEW_PAY_MODAL, "all");
        if(null == dictBaseDtos || dictBaseDtos.isEmpty()){
            dictBaseDtos = sysBaseService.selectDictData(NEW_PAY_MODAL,payway);
        }
        if(null == dictBaseDtos || dictBaseDtos.size() == 0){
            throw new Exception("不是新支付模块！");
        }
    }
    /**
     * 新模块退款
     * @param refundRequestDto
     * @return
     */
    public ResultMap refundPost(RefundRequestDto refundRequestDto) throws Exception {
        //
        isNewPayModal(refundRequestDto.getPayWay());
        String jsonString = JSONObject.toJSONString(refundRequestDto);
        String retStr = post(refundUrl,jsonString);
        log.info(" `new 调用退款接口>>>{} 返回结果>>>{} ",refundUrl,retStr);
        if(StringUtils.isEmpty(retStr)){
            return ResultMap.error();
        }else{
            try{
                ResultMap resultMap = JSONObject.parseObject(retStr, ResultMap.class);
                return resultMap;
            }catch (Exception e){
                e.printStackTrace();
                return ResultMap.error();
            }
        }
    }

    /**
     * 新模块查询支付
     * @param paymentRequestDto
     * @return
     */
    public PaymentInfoResponseDto queryPost(PaymentRequestDto paymentRequestDto) throws Exception {
        isNewPayModal(paymentRequestDto.getPayWay());
        String jsonString = JSONObject.toJSONString(paymentRequestDto);
        String retStr = post(queryUrl,jsonString);
        log.info(" `new 调用查询接口>>>{} 返回结果>>>{} ",queryUrl,retStr);
        if(StringUtils.isEmpty(retStr)){
            return PaymentInfoResponseDto.error(1,"查询失败");
        }else{
            try {
                JSONObject jsonObject = JSONObject.parseObject(retStr);
                PaymentInfoResponseDto resultMap = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("data")), PaymentInfoResponseDto.class);
                if(null == resultMap){
                    throw new Exception("查询失败");
                }
                resultMap.setSuccess(jsonObject.getBoolean("success"));
                log.info(" `new 调用查询接口>>>{} 返回结果>>>{} ",resultMap,jsonObject.get("data"));
                return resultMap;
            }catch (Exception e){
                throw new Exception("查询失败");
            }
        }
    }

    private String post(String url, String jsonString) {
        Map<String,String > header = new HashMap<>();
        header.put("Content-Type","application/json");
        String retStr = "";
        if(url.startsWith("https:")){
            retStr = HttpClientUtil.httpsRequest(url, HttpClientUtil.POST, jsonString, header);
        }else{
            retStr = HttpClientUtil.httpRequest(url,HttpClientUtil.POST, jsonString,header);
        }
        return retStr;
    }


}
