package cn.com.poc.thirdparty.resource.demand.pay.service.impl;

import cn.com.poc.common.utils.BlContext;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.support.security.oauth.entity.UserBaseEntity;
import cn.com.poc.thirdparty.resource.demand.ai.route.DgtoolsApiRoute;
import cn.com.poc.thirdparty.resource.demand.dgTools.DgtoolsAbstractHttpClient;
import cn.com.poc.thirdparty.resource.demand.dgTools.constants.Channel;
import cn.com.poc.thirdparty.resource.demand.dgTools.constants.CurrencyEnum;
import cn.com.poc.thirdparty.resource.demand.dgTools.constants.Scence;
import cn.com.poc.thirdparty.resource.demand.dgTools.constants.TradeType;
import cn.com.poc.thirdparty.resource.demand.dgTools.request.PayRequest;
import cn.com.poc.thirdparty.resource.demand.dgTools.result.PayResult;
import cn.com.poc.thirdparty.resource.demand.dgTools.service.AuthorizationService;
import cn.com.poc.thirdparty.resource.demand.member.service.DemandAuthService;
import cn.com.poc.thirdparty.resource.demand.pay.dto.WxH5PayDto;
import cn.com.poc.thirdparty.resource.demand.pay.dto.WxMiniPayDto;
import cn.com.poc.thirdparty.resource.demand.pay.dto.WxNativePayDto;
import cn.com.poc.thirdparty.resource.demand.pay.entity.DgtoolsPayOrderEntity;
import cn.com.poc.thirdparty.resource.demand.pay.service.DgtoolsPayLogService;
import cn.com.poc.thirdparty.resource.demand.pay.service.DgtoolsPayOrderService;
import cn.com.poc.thirdparty.resource.demand.pay.service.PayService;
import cn.com.yict.framemax.core.config.Config;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.core.service.impl.BaseServiceImpl;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Roger Wu
 */
@Service
public class PayServiceImpl extends BaseServiceImpl
        implements PayService {

    private final String acctId = Config.get("pay.config.acctId");


    private final String wxAppId = Config.get("pay.config.wxAppId");

    private Logger logger = LoggerFactory.getLogger(PayService.class);

    @Resource
    private DgtoolsAbstractHttpClient dgToolsAbstractHttpClient;

    @Resource
    private DgtoolsPayOrderService dgtoolsPayOrderService;

    @Resource
    private DgtoolsPayLogService dgtoolsPayLogService;

    @Resource
    private DemandAuthService demandAuthService;

    @Resource
    private AuthorizationService authorizationService;


    @Value("${pay.domain.callback.url}")
    private String payCallBackUrl;

    /**
     * 小程序支付
     *
     * @param wxMiniPayDto
     * @return
     * @throws Exception
     */
    @Override
    public PayResult wxMiniPay(WxMiniPayDto wxMiniPayDto) throws Exception {
//        //更新订单
//        dgtoolsPayOrderService.updatePayOrderDetailInfo(wxMiniPayDto.getPayOrderSn(),wxMiniPayDto.getDescription(),wxMiniPayDto.getRetainInformation());
        //支付操作
        PayResult payResult = doPay(wxMiniPayDto);
        //创建支付流水
        dgtoolsPayLogService.createPayLog(wxMiniPayDto.getPayOrderSn());
        return payResult;
    }

    public PayResult doPay(WxMiniPayDto wxMiniPayDto) throws Exception {

        String outTraceNo = wxMiniPayDto.getOutTraceNo();
        String payOrderSn = wxMiniPayDto.getPayOrderSn();

        String temp = null;
        if (StringUtils.isNotBlank(outTraceNo)) {
            temp = outTraceNo;
        } else if (StringUtils.isNotBlank(payOrderSn)) {
            temp = payOrderSn;
        }
        DgtoolsPayOrderEntity prePayOrderByPaySn = dgtoolsPayOrderService.findPayOrderByPaySn(temp);

        if (prePayOrderByPaySn == null) {
            throw new BusinessException("找不到该付款订单");
        }

        PayRequest payRequest = new PayRequest();
        payRequest.setChannel(Channel.Wx);
        payRequest.setScence(Scence.wx_mini_program);
        payRequest.setTradeType(TradeType.PAY);

        Integer merchantId = prePayOrderByPaySn.getMerchantId();
//        DgtoolsMerchantEntity dgtoolsMerchantEntity = dgtoolsMerchantService.getMerchantById(merchantId, CommonConstant.IsDeleted.N);
//        if (dgtoolsMerchantEntity == null) {
//            throw new BusinessException("找不到该商家信息");
//        }

//        payRequest.setAcctId(dgtoolsMerchantEntity.getAcctId());


        String openId = this.getMAGOrderOpenId(prePayOrderByPaySn);
        if (StringUtils.isNotBlank(openId)) {
//            BizWxAppInfo sceneCode = bizWxAppInfoService.getBySceneCode(MkpWxAppSceneCodeConstant.AI_MINI);
//            payRequest.setPlatformKey(sceneCode.getAppId());
//
//            payRequest.setUserIdentification(openId);
//        } else {
//            BizWxAppInfo bySceneCode = bizWxAppInfoService.getBySceneCode(MkpWxAppSceneCodeConstant.MKP_MINI);
//            if (bySceneCode == null) {
//                throw new BusinessException("找不到平台信息");
//            }
//            payRequest.setPlatformKey(bySceneCode.getAppId());
//
//            Long userId = BlContext.getCurrentUser().getUserId();
//            BizMember3rdPartyRelationEntity byMemberIdAndPlatform = bizMember3rdPartyRelationService.getByMemberIdAndPlatform(userId.intValue(), Member3rdPartyRelationEnum.WX_MINI);
//            if (byMemberIdAndPlatform == null) {
//                throw new BusinessException("找不到该用户信息");
//            }
//            payRequest.setUserIdentification(byMemberIdAndPlatform.getRelationId());
        }

        payRequest.setCurrency(CurrencyEnum.CHINA.getCurrencyCode());
        payRequest.setBizUniqueNo(prePayOrderByPaySn.getPayOrderSn());
        payRequest.setPayAmount(prePayOrderByPaySn.getNeedPayAmount());
        payRequest.setDescription(prePayOrderByPaySn.getDescription());
        payRequest.setCallBackUrl(payCallBackUrl);
        payRequest.setExpireTime(prePayOrderByPaySn.getCancelTime());


        List<Header> headers = new ArrayList<>();
        headers.add(DgtoolsApiRoute.PAY_HEADER);
        headers.add(new BasicHeader(DgtoolsApiRoute.HEADER_X_PLATFORM_AUTHORIZATION, demandAuthService.getToken()));
        PayResult payResult = dgToolsAbstractHttpClient.doRequest(DgtoolsApiRoute.DgtoolPay.DO_PAY, payRequest, headers);
        payResult.setPayOrderSn(payOrderSn);
        return payResult;
    }


    /**
     * 小程序H5支付
     *
     * @throws Exception
     */
    @Override
    public PayResult wxH5Pay(WxH5PayDto wxH5PayDto) throws Exception {
        PayResult payResult = doH5Pay(wxH5PayDto);
        //创建支付流水
        dgtoolsPayLogService.createPayLog(wxH5PayDto.getPayOrderSn());
        return payResult;
    }

    private PayResult doH5Pay(WxH5PayDto wxH5PayDto) throws Exception {
        String outTraceNo = wxH5PayDto.getOutTraceNo();
        String payOrderSn = wxH5PayDto.getPayOrderSn();

        String temp = null;
        if (StringUtils.isNotBlank(outTraceNo)) {
            temp = outTraceNo;
        } else if (StringUtils.isNotBlank(payOrderSn)) {
            temp = payOrderSn;
        }
        DgtoolsPayOrderEntity prePayOrderByPaySn = dgtoolsPayOrderService.findPayOrderByPaySn(temp);

        if (prePayOrderByPaySn == null) {
            throw new BusinessException("找不到该付款订单");
        }

        PayRequest payRequest = new PayRequest();
        payRequest.setChannel(Channel.Wx);
        payRequest.setScence(Scence.wx_h5_program);
        payRequest.setTradeType(TradeType.PAY);

        Integer merchantId = prePayOrderByPaySn.getMerchantId();
//        DgtoolsMerchantEntity dgtoolsMerchantEntity = dgtoolsMerchantService.getMerchantById(merchantId, CommonConstant.IsDeleted.N);
//        if (dgtoolsMerchantEntity == null) {
//            throw new BusinessException("找不到该商家信息");
//        }
//
//        payRequest.setAcctId(dgtoolsMerchantEntity.getAcctId());

//        BizWxAppInfo bySceneCode = bizWxAppInfoService.getBySceneCode(MkpWxAppSceneCodeConstant.MKP_MINI);
//        if (bySceneCode == null) {
//            throw new BusinessException("找不到平台信息");
//        }
//        payRequest.setPlatformKey(bySceneCode.getAppId());
//
//        Long userId = BlContext.getCurrentUser().getUserId();
//        BizMember3rdPartyRelationEntity byMemberIdAndPlatform = bizMember3rdPartyRelationService.getByMemberIdAndPlatform(userId.intValue(), Member3rdPartyRelationEnum.WX_MINI);
//        if (byMemberIdAndPlatform == null) {
//            throw new BusinessException("找不到该用户信息");
//        }
//        payRequest.setUserIdentification(byMemberIdAndPlatform.getRelationId());
//
//        payRequest.setCurrency(CurrencyEnum.CHINA.getCurrencyCode());
//        payRequest.setBizUniqueNo(prePayOrderByPaySn.getPayOrderSn());
//        payRequest.setPayAmount(prePayOrderByPaySn.getNeedPayAmount());
//        payRequest.setDescription(prePayOrderByPaySn.getDescription());
//        payRequest.setCallBackUrl(payCallBackUrl);
//        payRequest.setExpireTime(prePayOrderByPaySn.getCancelTime());
//        payRequest.setClientIP(wxH5PayDto.getClientIp());
//
//        List<Header> headers = new ArrayList<>();
//        headers.add(DgtoolsApiConstants.PAY_HEADER);
//        headers.add(new BasicHeader(DgtoolsApiConstants.HEADER_X_PLATFORM_AUTHORIZATION, demandAuthService.getToken()));
//        PayResult payResult = dgToolsAbstractHttpClient.doRequest(DgtoolsApiConstants.Pay.DO_PAY, payRequest, headers);
//        return payResult;
        return null;
    }


    @Override
    public PayResult wxNativePay(WxNativePayDto wxNativePayDto) throws Exception {
        PayResult payResult = doNativePay(wxNativePayDto);
        //创建支付流水
        dgtoolsPayLogService.createPayLog(wxNativePayDto.getPayOrderSn());
        return payResult;
    }

    private PayResult doNativePay(WxNativePayDto wxNativePayDto) throws Exception {
        String outTraceNo = wxNativePayDto.getOutTraceNo();
        String payOrderSn = wxNativePayDto.getPayOrderSn();

        String temp = null;
        if (StringUtils.isNotBlank(outTraceNo)) {
            temp = outTraceNo;
        } else if (StringUtils.isNotBlank(payOrderSn)) {
            temp = payOrderSn;
        }
        DgtoolsPayOrderEntity prePayOrderByPaySn = dgtoolsPayOrderService.findPayOrderByPaySn(temp);

        if (prePayOrderByPaySn == null) {
            throw new BusinessException("找不到该付款订单");
        }

        PayRequest payRequest = new PayRequest();
        payRequest.setChannel(Channel.Wx);
        payRequest.setScence(Scence.wx_native_program);
        payRequest.setTradeType(TradeType.PAY);

        payRequest.setAcctId(acctId);
        payRequest.setPlatformKey(wxAppId);
        UserBaseEntity currentUser = BlContext.getCurrentUser();

        payRequest.setUserIdentification(currentUser.getUserId().toString());
        payRequest.setCurrency(CurrencyEnum.CHINA.getCurrencyCode());
        payRequest.setBizUniqueNo(prePayOrderByPaySn.getPayOrderSn());
        payRequest.setPayAmount(prePayOrderByPaySn.getNeedPayAmount());
        payRequest.setDescription(prePayOrderByPaySn.getDescription());
        payRequest.setCallBackUrl(payCallBackUrl);
        payRequest.setExpireTime(prePayOrderByPaySn.getCancelTime());


        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader(DgtoolsApiRoute.HEADER_REQUEST_TOKEN, authorizationService.getApplicationToken()));
        headers.add(new BasicHeader(DgtoolsApiRoute.HEADER_X_PLATFORM_AUTHORIZATION, demandAuthService.getToken()));
        headers.add(DgtoolsApiRoute.PAY_HEADER);
        PayResult payResult = dgToolsAbstractHttpClient.doRequest(DgtoolsApiRoute.DgtoolPay.DO_PAY, payRequest, headers);
        return payResult;
    }


    @Override
    public PayResult aliPayH5(String payOrderSn) throws Exception {
        DgtoolsPayOrderEntity prePayOrderByPaySn = dgtoolsPayOrderService.findPayOrderByPaySn(payOrderSn);

        if (prePayOrderByPaySn == null) {
            throw new BusinessException("找不到该付款订单");
        }

        PayRequest payRequest = new PayRequest();
        payRequest.setChannel(Channel.Ali);
        payRequest.setScence(Scence.ali_h5_program);
        payRequest.setTradeType(TradeType.PAY);

        payRequest.setAcctId(acctId);
        payRequest.setPlatformKey("");
        UserBaseEntity currentUser = BlContext.getCurrentUser();

        payRequest.setUserIdentification(currentUser.getUserId().toString());
        payRequest.setCurrency(CurrencyEnum.CHINA.getCurrencyCode());
        payRequest.setBizUniqueNo(prePayOrderByPaySn.getPayOrderSn());
        payRequest.setPayAmount(prePayOrderByPaySn.getNeedPayAmount());
        payRequest.setDescription(prePayOrderByPaySn.getDescription());
        payRequest.setCallBackUrl(payCallBackUrl);
        payRequest.setExpireTime(prePayOrderByPaySn.getCancelTime());
        payRequest.setDescription(prePayOrderByPaySn.getDescription());

        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader(DgtoolsApiRoute.HEADER_REQUEST_TOKEN, authorizationService.getApplicationToken()));
        headers.add(new BasicHeader(DgtoolsApiRoute.HEADER_X_PLATFORM_AUTHORIZATION, demandAuthService.getToken()));
        headers.add(DgtoolsApiRoute.PAY_HEADER);
        PayResult payResult = dgToolsAbstractHttpClient.doRequest(DgtoolsApiRoute.DgtoolPay.DO_PAY, payRequest, headers);
        //创建支付流水
        dgtoolsPayLogService.createPayLog(payOrderSn);
        return payResult;
    }

    private PayResult doAliPayH5(WxNativePayDto wxNativePayDto) throws Exception {
        String outTraceNo = wxNativePayDto.getOutTraceNo();
        String payOrderSn = wxNativePayDto.getPayOrderSn();

        String temp = null;
        if (StringUtils.isNotBlank(outTraceNo)) {
            temp = outTraceNo;
        } else if (StringUtils.isNotBlank(payOrderSn)) {
            temp = payOrderSn;
        }
        DgtoolsPayOrderEntity prePayOrderByPaySn = dgtoolsPayOrderService.findPayOrderByPaySn(temp);

        if (prePayOrderByPaySn == null) {
            throw new BusinessException("找不到该付款订单");
        }

        PayRequest payRequest = new PayRequest();
//        payRequest.setChannel(Channel.Ali);
//        payRequest.setScence(Scence.ali_h5_program);
//        payRequest.setTradeType(TradeType.PAY);
//
//        Integer merchantId = prePayOrderByPaySn.getMerchantId();
//        DgtoolsMerchantEntity dgtoolsMerchantEntity = dgtoolsMerchantService.getMerchantById(merchantId, MkpCommonConstant.IsDeleted.N);
//        if (dgtoolsMerchantEntity == null) {
//            throw new BusinessException("找不到该商家信息");
//        }
//
//        payRequest.setAcctId(dgtoolsMerchantEntity.getAcctId());
//
//        BizWxAppInfo bySceneCode = bizWxAppInfoService.getBySceneCode(MkpWxAppSceneCodeConstant.MKP_MINI);
//        if (bySceneCode == null) {
//            throw new BusinessException("找不到平台信息");
//        }
//        payRequest.setPlatformKey(bySceneCode.getAppId());
//
//        UserBaseEntity currentUser = BlContext.getCurrentUser();
//
//        if (OauthConstants.OauthEnum.MEMBER_DOMAIN.name().equals(currentUser.getType())) {
//            Long userId = BlContext.getCurrentUser().getUserId();
//            BizMember3rdPartyRelationEntity byMemberIdAndPlatform = bizMember3rdPartyRelationService.getByMemberIdAndPlatform(userId.intValue(), Member3rdPartyRelationEnum.WX_MINI);
//            if (byMemberIdAndPlatform == null) {
//                throw new BusinessException("找不到该用户信息");
//            }
//            payRequest.setUserIdentification(byMemberIdAndPlatform.getRelationId());
//        } else if (OauthConstants.OauthEnum.AIGC_MEMBER_DOMAIN.name().equals(currentUser.getType())) {
//            payRequest.setUserIdentification(StringUtils.substringAfterLast(currentUser.getUserAccount(), OauthConstants.TypePrefix.AIGC_MEMBER_DOMAIN));
//        } else {
//            payRequest.setUserIdentification(currentUser.getUserId().toString());
//        }
//        payRequest.setCurrency(CurrencyEnum.CHINA.getCurrencyCode());
//        payRequest.setBizUniqueNo(prePayOrderByPaySn.getPayOrderSn());
//        payRequest.setPayAmount(prePayOrderByPaySn.getNeedPayAmount());
//        payRequest.setDescription(prePayOrderByPaySn.getDescription());
//        payRequest.setCallBackUrl(payCallBackUrl);
//        payRequest.setExpireTime(prePayOrderByPaySn.getCancelTime());
//
//
//        List<Header> headers = new ArrayList<>();
//        headers.add(new BasicHeader(DgtoolsApiConstants.HEADER_X_PLATFORM_AUTHORIZATION, demandAuthService.getToken()));
//        headers.add(DgtoolsApiConstants.PAY_HEADER);
//        PayResult payResult = dgToolsAbstractHttpClient.doRequest(DgtoolsApiConstants.Pay.DO_PAY, payRequest, headers);
        return null;
    }

    @Override
    public PayResult aliPayWap(String payOrderSn) throws Exception {
        return null;
    }

    private String getMAGOrderOpenId(DgtoolsPayOrderEntity payOrderEntity) throws Exception {
        String payOrderSn = payOrderEntity.getPayOrderSn();
//        if (payOrderSn.startsWith(BizSnKeyEnum.aiGcRechargeRecordFlowNo.getSnPrefix())) {
//            Integer memberId = payOrderEntity.getMemberId();
//            AiGcMemberEntity aiGcMemberEntity = bizAiGcMemberService.get(memberId);
//            String unionId = aiGcMemberEntity.getRelationId();
//            BizMember3rdPartyRelationEntity bizMember3rdPartyRelationEntity = new BizMember3rdPartyRelationEntity();
//            bizMember3rdPartyRelationEntity.setUnionId(unionId);
//            bizMember3rdPartyRelationEntity.setRelationPlatform(Member3rdPartyRelationEnum.AIGC_WX_MINI.name());
//            bizMember3rdPartyRelationEntity.setIsDeleted(MkpCommonConstant.IsDeleted.N);
//            List<BizMember3rdPartyRelationEntity> relationEntities = bizMember3rdPartyRelationService.findByExample(bizMember3rdPartyRelationEntity);
//            if (CollectionUtils.isEmpty(relationEntities)) {
//                logger.warn("-------------获取AIGC用户OPENID失败，unionId:{}------------", unionId);
//                throw new BusinessException("获取用户信息失败，请联系管理员");
//            }
//            return relationEntities.get(0).getRelationId();
//        }
        return null;
    }


    @Override
    public PayResult aliPayNative(String payOrderSn) throws Exception {
        DgtoolsPayOrderEntity prePayOrderByPaySn = dgtoolsPayOrderService.findPayOrderByPaySn(payOrderSn);

        if (prePayOrderByPaySn == null) {
            throw new BusinessException("找不到该付款订单");
        }

        PayRequest payRequest = new PayRequest();
        payRequest.setChannel(Channel.Ali);
        payRequest.setScence(Scence.ali_h5_program);
        payRequest.setTradeType(TradeType.PAY);

        payRequest.setAcctId(acctId);
        payRequest.setPlatformKey("");
        UserBaseEntity currentUser = BlContext.getCurrentUser();

        payRequest.setUserIdentification(currentUser.getUserId().toString());
        payRequest.setCurrency(CurrencyEnum.CHINA.getCurrencyCode());
        payRequest.setBizUniqueNo(prePayOrderByPaySn.getPayOrderSn());
        payRequest.setPayAmount(prePayOrderByPaySn.getNeedPayAmount());
        payRequest.setDescription(prePayOrderByPaySn.getDescription());
        payRequest.setCallBackUrl(payCallBackUrl);
        payRequest.setExpireTime(prePayOrderByPaySn.getCancelTime());
        payRequest.setDescription(prePayOrderByPaySn.getDescription());

        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader(DgtoolsApiRoute.HEADER_REQUEST_TOKEN, authorizationService.getApplicationToken()));
        headers.add(new BasicHeader(DgtoolsApiRoute.HEADER_X_PLATFORM_AUTHORIZATION, demandAuthService.getToken()));
        headers.add(DgtoolsApiRoute.PAY_HEADER);
        PayResult payResult = dgToolsAbstractHttpClient.doRequest(DgtoolsApiRoute.DgtoolPay.DO_PAY, payRequest, headers);
        //创建支付流水
        dgtoolsPayLogService.createPayLog(payOrderSn);
        return payResult;
    }
}