package com.ruoyi.utils.lakala;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.lkl.laop.sdk.Config;
import com.lkl.laop.sdk.LKLSDK;
import com.lkl.laop.sdk.exception.SDKException;
import com.lkl.laop.sdk.request.V3CcssCounterOrderCreateRequest;
import com.lkl.laop.sdk.request.model.V3CcssOrderSceneFieldInfo;
import com.ruoyi.response.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class LakalaUtil {

    //拉卡拉开放平台进行配置开通
    @Value("${lalkla.appId}")
    private String appId;

    //商户号
    @Value("${lalkla.merchantNo}")
    private String merchantNo;

    //商户证书序列号,和商户私钥对应
    @Value("${lalkla.serialNo}")
    private String serialNo;

    //商户私钥地址,用于请求签名
    @Value("${lalkla.priKeyPath}")
    private String priKeyPath;

    //拉卡拉公钥证书地址,用于验签（测试证书为：lkl-apigw-v2.cer）
    @Value("${lalkla.lklCerPath}")
    private String lklCerPath;

    //拉卡拉支付平台证书地址2(用于拉卡拉通知验签，证书与lklCerPath)一致，测试证书为：lkl-apigw-v2.cer）
    @Value("${lalkla.lklNotifyCerPath}")
    private String lklNotifyCerPath;

    //拉卡拉开放平台服务地址
    @Value("${lalkla.serverUrl}")
    private String serverUrl;

    //如果需要密文传输请申请拉卡拉SM4密钥
    @Value("${lalkla.sm4Key}")
    private String sm4Key;


//    //支付回调地址
//    @Value("${lalkla.appId}")
//    private static final String notifyUrl = "http://yutongbo.natapp1.cc/api/goeasy/lakalaNotifyUrl";

    /**
     * 初始化配置
     *
     * @throws SDKException
     */
    public void doInit() {
        //初始化配置(全局只需配置一次)
        try {
            LKLSDK.init(new Config(appId, serialNo, priKeyPath, lklCerPath, lklNotifyCerPath, sm4Key, serverUrl));
        } catch (SDKException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 聚合收银台创建订单
     *
     * @return
     */
    public ResponseData ccssCounterOrderTospecialCreate(String orderNo, BigDecimal payPrice, Long objectId, String notifyUrl) {
        doInit();
        //创建订单请求参数
        V3CcssCounterOrderCreateRequest request = new V3CcssCounterOrderCreateRequest();

        //商户订单号
        request.setOutOrderNo(orderNo);

        //是否支持多次发起订单 0 不支持 1 支持
        request.setSupportRepeatPay(1);

        //银联商户号
        request.setMerchantNo(merchantNo);

        //订单支付金额 单位:分
        request.setTotalAmount(payPrice.multiply(new BigDecimal(100)).longValue());

        //支付有效期 一天
        request.setOrderEfficientTime(DateUtil.format(DateUtil.offsetDay(new Date(), 1), "yyyyMMddHHmmss"));

        //回调地址
        request.setNotifyUrl(notifyUrl);

        //支付类型
//        req.setCounterParam("{\"pay_mode\":\"ALIPAY\"}");

//        req.setBusiTypeParam("[{\"busi_type\":\"UPCARD\",\"params\":{\"crd_flg\":\"CRDFLG_D|CRDFLG_C|CRDFLG_OTH\"}},{\"busi_type\":\"SCPAY\",\"params\":{\"pay_mode\":\"WECHAT\",\"crd_flg\":\"CRDFLG_D\"}}]");

        //	订单标题，在使用收银台扫码支付时必输入，交易时送往账户端
        request.setOrderInfo("DD画图支付");

        List<String> sgnInfos = new ArrayList<>();

        sgnInfos.add("1");

        request.setSgnInfo(sgnInfos);


        V3CcssOrderSceneFieldInfo.HbFqSceneInfo hbFqSceneInfo = new V3CcssOrderSceneFieldInfo.HbFqSceneInfo();

        hbFqSceneInfo.setHbFqNum("3");

        hbFqSceneInfo.setHbFqSellerPercent("0");

        //3. 发送请求
        String response = null;
        try {
            response = LKLSDK.httpPost(request);
        } catch (SDKException e) {
            log.error("调用拉卡拉支付接口异常", e);
            throw new RuntimeException(e);
        }

        //4. 响应
        System.out.println(response);

        Map map = JSONObject.parseObject(response, Map.class);
        if ("000000".equals(map.get("code"))) {
            map.put("orderId", objectId);
            return ResponseData.success(map);
        } else {
            log.error("调用拉卡拉支付接口异常,返回结果:{}", response);
            return ResponseData.error(map.get("msg").toString());
        }
    }

    public static void main(String[] args) {

        //拉卡拉开放平台进行配置开通
        String appId = "OP00000003";
        //商户号
        String merchantNo = "822290059430BBV";
        //商户证书序列号,和商户私钥对应
        String serialNo = "00dfba8194c41b84cf";
        //商户私钥地址,用于请求签名
        String priKeyPath = "D:/OP00000003_private_key.pem";
        //拉卡拉公钥证书地址,用于验签（测试证书为：lkl-apigw-v2.cer）
        String lklCerPath = "D:/lkl-apigw-v2.cer";
        //拉卡拉支付平台证书地址2(用于拉卡拉通知验签，证书与lklCerPath)一致，测试证书为：lkl-apigw-v2.cer）
        String lklNotifyCerPath = "D:/lkl-apigw-v2.cer";
        //拉卡拉开放平台服务地址
        String serverUrl = "https://test.wsmsd.cn/sit";
        //如果需要密文传输请申请拉卡拉SM4密钥
        String sm4Key = "0I4M0kmwFrNUU8hZ9AFpfA==";
        //支付回调地址
        String notifyUrl = "http://yutongbo.natapp1.cc/api/goeasy/lakalaNotifyUrl";
        //初始化配置(全局只需配置一次)
        try {
            LKLSDK.init(new Config(appId, serialNo, priKeyPath, lklCerPath, lklNotifyCerPath, sm4Key, serverUrl));
        } catch (SDKException e) {
            throw new RuntimeException(e);
        }

        //创建订单请求参数
        V3CcssCounterOrderCreateRequest request = new V3CcssCounterOrderCreateRequest();

        //商户订单号
        request.setOutOrderNo("HT" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));

        //银联商户号
        request.setMerchantNo(merchantNo);

        //订单支付金额 单位:分
        request.setTotalAmount(1L);

        //支付有效期 一天
        request.setOrderEfficientTime(DateUtil.format(DateUtil.offsetDay(new Date(), 1), "yyyyMMddHHmmss"));

        //回调地址
        request.setNotifyUrl(notifyUrl);

        //支付类型
//        req.setCounterParam("{\"pay_mode\":\"ALIPAY\"}");

//        req.setBusiTypeParam("[{\"busi_type\":\"UPCARD\",\"params\":{\"crd_flg\":\"CRDFLG_D|CRDFLG_C|CRDFLG_OTH\"}},{\"busi_type\":\"SCPAY\",\"params\":{\"pay_mode\":\"WECHAT\",\"crd_flg\":\"CRDFLG_D\"}}]");

        //	订单标题，在使用收银台扫码支付时必输入，交易时送往账户端
        request.setOrderInfo("DD画图支付");

        List<String> sgnInfos = new ArrayList<>();

        sgnInfos.add("1");

        request.setSgnInfo(sgnInfos);


        V3CcssOrderSceneFieldInfo.HbFqSceneInfo hbFqSceneInfo = new V3CcssOrderSceneFieldInfo.HbFqSceneInfo();

        hbFqSceneInfo.setHbFqNum("3");

        hbFqSceneInfo.setHbFqSellerPercent("0");

        //3. 发送请求
        String response = null;
        try {
            response = LKLSDK.httpPost(request);
        } catch (SDKException e) {
            log.error("调用拉卡拉支付接口异常", e);
            throw new RuntimeException(e);
        }

        //4. 响应
        System.out.println(response);

    }
}
