/**
 * cljpay.com
 * Copyright (C) 2015-2023 All Rights Reserved.
 */package com.jeequan.jeepay.thirdparty.service.zw.uils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.device.PayOrderInfo4Device;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.DateKit;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.thirdparty.service.zw.model.request.*;
import com.jeequan.jeepay.thirdparty.service.zw.model.response.BaseResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author yangjun
 * @version SmartLinkAllServiceImpl.java, v 0.1 2023-02-20 10:07 yangjun
 */
@Service
@Slf4j
@AllArgsConstructor
public class SmartLinkUtil {
    /**
     * 请求智网接口
     *
     * @param url
     * @param param
     * @param resultClass
     * @param <T>
     * @return
     */
    private static <T> T doRequestZw(String url, Object param, Class<T> resultClass) {
        JSONObject paramJson = JSONObject.parseObject(JSONObject.toJSONString(param));
//        paramJson.put("md5key", generateSign(paramJson));
        log.info("doRequestZw >> 准备请求智网接口, url={}, param={}", url, paramJson.toJSONString());
        long currentTime = DateKit.currentTimeMillis();
        String responseStr;
        try {
            responseStr = HttpUtil.post(url, paramJson.toJSONString());
            log.info("doRequestZw >> 智网接口响应, 耗时={}ms, url={}, param={}, response={}", DateKit.currentTimeMillis() - currentTime, url, paramJson, responseStr);
            return JSONObject.parseObject(responseStr, resultClass);
        } catch (Exception e) {
            log.error("doRequestZw >> 请求智网接口失败, url={}, param={}", url, paramJson, e);
            throw new BizException("请求智网接口失败");
        }
    }

    private static String generateSign(Map<String, Object> params) {
        if (params == null) {
            return null;
        } else {
            StringBuffer content = new StringBuffer();
            List<String> keys = new ArrayList(params.keySet());
            Collections.sort(keys);

            for (int i = 0; i < keys.size(); ++i) {
                String key = keys.get(i);
                String value = params.get(key) == null ? "" : params.get(key).toString();
                content.append((i == 0 ? "" : "&") + key + "=" + value);
            }
            return JeepayKit.md5(content.toString(), "UTF-8").toUpperCase();
        }
    }

    public BaseResponse soundPayMsg(PayMsgRequest payMsgRequest) {
        return doRequestZw(ZwConstants.ZW_URL_HOST + ZwConstants.ZW_PAY_SPEAKER, payMsgRequest, BaseResponse.class);
    }

    public static BaseResponse soundNotifyMsg(NotifyMsgRequest notifyMsgRequest) {
        return doRequestZw(ZwConstants.ZW_URL_HOST + ZwConstants.ZW_4G_PAY_SPEAKER, notifyMsgRequest, BaseResponse.class);
    }

    public static BaseResponse cloudPrint(PrintRequest printRequest) {
        return doRequestZw(ZwConstants.ZW_URL_HOST + ZwConstants.ZW_CLOUD_PRINT, printRequest, BaseResponse.class);
    }

    public static BaseResponse updatePayParam(UpdatePayParamRequest updatePayParamRequest) {
        return doRequestZw(ZwConstants.ZW_URL_HOST + ZwConstants.ZW_UPDATE_PAY_PARAM, updatePayParamRequest, BaseResponse.class);
    }

    /** 生成小票 **/
    public static List<PrintPdRequest> getPrintPd(PayOrderInfo4Device payOrderInfo) {
        List<PrintPdRequest> printPdRequests = new ArrayList<>();
        PrintPdRequest printPdRequest = new PrintPdRequest();
        printPdRequest.setTp("3");
        printPdRequests.add(printPdRequest);

        printPdRequest = new PrintPdRequest();
        printPdRequest.setTp("1");
        printPdRequest.setCv("支付凭证");
        printPdRequest.setAl("1");
        printPdRequest.setFs("3");
        printPdRequest.setTb("1");
        printPdRequests.add(printPdRequest);

        printPdRequest = new PrintPdRequest();
        printPdRequest.setTp("4");
        printPdRequests.add(printPdRequest);

        printPdRequest = new PrintPdRequest();
        printPdRequest.setTp("1");
        printPdRequest.setCv("门店名称：" + payOrderInfo.getStoreName());
        printPdRequests.add(printPdRequest);

        printPdRequest = new PrintPdRequest();
        printPdRequest.setTp("1");
        printPdRequest.setCv("订 单 号：" + payOrderInfo.getPayOrderId());
        printPdRequests.add(printPdRequest);

//        printPdRequest = new PrintPdRequest();
//        printPdRequest.setTp("1");
//        printPdRequest.setCv("商户单号：" + payOrderInfo.getMchOrderNo());
//        printPdRequests.add(printPdRequest);

//        printPdRequest = new PrintPdRequest();
//        printPdRequest.setTp("1");
//        printPdRequest.setCv("支付状态：" + CS.PAY_STATE_MAP.get(bizRes.getState()));
//        printPdRequests.add(printPdRequest);

        printPdRequest = new PrintPdRequest();
        printPdRequest.setTp("1");
        printPdRequest.setCv("支付方式：" + CS.PAY_WAY_CODE_TYPE_MAP.get(payOrderInfo.getWayCodeType()));
        printPdRequests.add(printPdRequest);

        printPdRequest = new PrintPdRequest();
        printPdRequest.setTp("1");
        printPdRequest.setCv("下单时间：" + DateUtil.format(payOrderInfo.getCreatedAt(), DatePattern.NORM_DATETIME_PATTERN));
        printPdRequests.add(printPdRequest);

        printPdRequest = new PrintPdRequest();
        printPdRequest.setTp("4");
        printPdRequests.add(printPdRequest);

//        printPdRequest = new PrintPdRequest();
//        printPdRequest.setTp("1");
//        printPdRequest.setCv("完成时间：" + CljDateUtil.conversionTime(bizRes.getSuccessTime().toString()));
//        printPdRequests.add(printPdRequest);

        printPdRequest = new PrintPdRequest();
        printPdRequest.setTp("1");
        printPdRequest.setCv("交易金额：" + AmountUtil.convertCent2Dollar(payOrderInfo.getAmount().toString()));
        printPdRequests.add(printPdRequest);

        return printPdRequests;
    }
}