package com.liquidnet.service.dragon.channel.wepay.strategy.impl;

import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.channel.wepay.strategy.IWepayStrategy;
import com.liquidnet.service.dragon.channel.wepay.util.WepayUtil;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import com.liquidnet.service.dragon.utils.PayWepayUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;

import java.util.SortedMap;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: AbstractWepayStrategy
 * @Package com.liquidnet.service.dragon.channel.wepay.strategy.impl
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/7/11 11:56
 */
@Slf4j
public abstract class AbstractWepayStrategy implements IWepayStrategy {
    @Value("${liquidnet.dragon.wepay.parentKey}")
    private String parentKey;

    @Override
    public ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto) {

        try {
            //构造请求参数
            SortedMap<String, Object> parameters = this.buildRequestParamMap(dragonPayBaseReqDto);
            //生成签名
            String sign = WepayUtil.getSign(parameters,parentKey);
            parameters.put("sign", sign);
            //构造支付请求xml
            String data = WepayUtil.mapToXml(parameters);

            HttpPost httpost = new HttpPost(this.getRequestUrl());
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = PayWepayUtils.getInstance().getHttpClient().execute(httpost);
            HttpEntity entity = response.getEntity();
            //接受到返回信息
            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            log.info("dragonPay:wepay:wap response json: {} ",jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 构造请求参数
     * @return
     */
    abstract SortedMap<String, Object> buildRequestParamMap(DragonPayBaseReqDto dragonPayBaseReqDto);

    /**
     * 构造返回参数
     */
    abstract DragonPayBaseRespDto buildResponseDto();

    protected abstract String getRequestUrl();
}
