package com.hfkj.service.hlt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.pay.util.MD5Util;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.DesUtil;
import com.hfkj.common.utils.HttpsUtils;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 汇联通会员卡业务接口【贵州高速工会卡】
 * @author hurui
 */
public class HuiLianTongUnionCardService {
    private static Logger log = LoggerFactory.getLogger(HuiLianTongUnionCardService.class);
    private static final String HLT_CARD_REQUEST_URL= "http://hltgz.com:4010/api/v2/execute.json";
    private static final String HLT_CARD_ACCESS_CODE= "6FCAE1470CEF465988351BB65ABAA8AE";
    private static final String HLT_CARD_SIGN_CODE = "F8E91A3C";

    /**
     * 根据手机号查询工会卡
     * @param phone
     * @return
     * @throws Exception
     */
    public static JSONObject queryCardByMobile(String phone) throws Exception {
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("userMobile", phone);
        return request("qgk/queryCardByMobile", dataMap);
    }

    /**
     * 查询卡信息
     * @param cardNo 工会卡号
     * @return
     * @throws Exception
     */
    public static JSONObject queryCardInfo(String cardNo) throws Exception {
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("cardNo", cardNo);
        return request("qgk/queryCardInfo", dataMap);
    }

    /**
     * 查询余额
     * @param cardNo 工会卡号
     * @return
     * @throws Exception
     */
    public static JSONObject queryBalance(String cardNo) throws Exception {
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("cardType", "ghk");
        dataMap.put("cardNo", cardNo);
        return request("qtk/queryBalance", dataMap);
    }

    /**
     * 根据业务类型查询消费记录
     * @param businessType 业务类型  1.卖中石化加油券的，固定填sinopec_oil_code 2.其他商品或服务的，固定填hisen_consume
     * @param cardNo 工会卡号
     * @param page 页数
     * @param pageSize 每页条数
     * @param sdate 起始日期 yyyy-MM-dd格式
     * @param edate 截止日期 yyyy-MM-dd格式
     * @return
     * @throws Exception
     */
    public static JSONObject queryConsumptionRecordByBusiness(String businessType,String cardNo,Long sdate,Long edate,Integer page,Integer pageSize) throws Exception {
        try {
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("businessType", businessType);
            dataMap.put("cardNo", cardNo);
            dataMap.put("page", page);
            dataMap.put("pageSize", pageSize);
            if (sdate != null) {
                dataMap.put("sdate", DateUtil.date2String(new Date(sdate), "yyyy-MM-dd"));
            }
            if (edate != null) {
                dataMap.put("edate", DateUtil.date2String(new Date(edate), "yyyy-MM-dd"));
            }
            return request("qtk/queryConsumptionRecordByBusiness", dataMap);
        } catch (Exception e) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQUEST_TIMED_OUT, "");
        }

    }

    /**
     * @MethodName queryTransJournal
     * @Description: 查询交易记录
     * @param cardNo
     * @param tranType 
     * @return: com.alibaba.fastjson.JSONObject
     * @Author: Sum1Dream
     * @Date: 2024/8/27 上午9:40
     */
    public static JSONObject queryTransJournal(String cardNo , String tranType) throws Exception {
        try {
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("tranType", tranType);
            dataMap.put("cardNo", cardNo);
            dataMap.put("page", 1);
            dataMap.put("pageSize", 10000);
            return request("coresystem/queryTransJournal", dataMap);
        } catch (Exception e) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQUEST_TIMED_OUT, "");
        }
    }


    /**
     * 充值
     * @param orderNo 订单号
     * @param cardNo  卡号
     * @param tranAmount 支付金额
     * @param businessType 业务类型  1.卖中石化加油券的，固定填sinopec_oil_code 2.其他商品或服务的，固定填hisen_consume
     * @param tranVoucher 银行卡充值可填银行卡号；支付宝、微信充值可填相应的扣款单号；接入方也可自定义填入交易流水跟踪号，但长度不能超过50
     * @param tranDesc 交易描述
     * @return
     * @throws Exception
     */
    public static JSONObject deposit(String orderNo, String cardNo, BigDecimal tranAmount,  String businessType, String tranVoucher , String tranDesc) throws Exception {
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("orderNo", orderNo);
        dataMap.put("cardType", "ghk");
        dataMap.put("cardNo", cardNo);
        dataMap.put("tranAmount", tranAmount);
        dataMap.put("tranChannel", "HiSen");
        dataMap.put("businessType", businessType);
        dataMap.put("tranVoucher", tranVoucher);
        dataMap.put("tranDesc", tranDesc);


        log.info("============请求任务Start=============");
        log.info("汇联通充值-请求参数: " + JSON.toJSONString(dataMap));

        JSONObject returnObject = request("qtk/deposit", dataMap);

        log.info("汇联通充值-响应参数: " + returnObject.toJSONString());
        log.info("============请求任务End==============");
        return returnObject;

    }

    /**
     * 支付
     * @param orderNo 订单号
     * @param cardNo  卡号
     * @param tranAmount 支付金额
     * @param businessType 业务类型  1.卖中石化加油券的，固定填sinopec_oil_code 2.其他商品或服务的，固定填hisen_consume
     * @param instCode 消费终端号
     * @param goodsDesc 商品描述
     * @param tranDesc 交易描述
     * @return
     * @throws Exception
     */
    public static JSONObject consumption(String orderNo, String cardNo, BigDecimal tranAmount, String businessType, String instCode,String goodsDesc, String tranDesc) throws Exception {
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("orderNo", orderNo);
        dataMap.put("cardType", "ghk");
        dataMap.put("cardNo", cardNo);
        dataMap.put("checkPassword", "N");
        dataMap.put("tranAmount", tranAmount);
        dataMap.put("tranChannel", "HiSen_phg");
        dataMap.put("businessType", businessType);
        dataMap.put("instCode", instCode);
        dataMap.put("goodsDesc", goodsDesc);
        dataMap.put("tranDesc", tranDesc);
        return request("qtk/consumption", dataMap);
    }

    /**
     * 业务请求
     * @param method  接口名称
     * @param param   业务参数
     * @return
     * @throws Exception
     */
    public static JSONObject request(String method,Map<String,Object> param) throws Exception {
        // 签名码
        String signCode = HLT_CARD_SIGN_CODE;

        Map<String,Object> map = new LinkedHashMap<>();
        map.put("accessCode", HLT_CARD_ACCESS_CODE);
        map.put("requestId", System.currentTimeMillis());
        map.put("method", method);
        log.info("加密前: " + JSON.toJSONString(param));
        // DES加密
        map.put("data", DesUtil.encode(JSONObject.toJSONString(param), Charset.forName("UTF-8"),signCode).replace("\\n", ""));

        // 数据签名字符串
        String str = (MapUtils.getString(map,"accessCode")+signCode);
        str +=(MapUtils.getString(map,"requestId")+signCode) ;
        str += (MapUtils.getString(map,"method") + signCode);
        str += (MapUtils.getString(map,"data") + signCode);

        // MD5加密
        map.put("sign", MD5Util.MD5Encode(str, "UTF-8").toUpperCase());

        log.info("============请求任务Start=============");
        log.info("请求参数: " + JSON.toJSONString(map));

        JSONObject returnObject = HttpsUtils.doPost(HLT_CARD_REQUEST_URL, JSON.toJSONString(map));

        log.info("响应参数: " + returnObject.toJSONString());
        log.info("============请求任务End==============");
        return returnObject;
    }

    /**
     * 退款
     * @param refundOrderNo 退款订单号
     * @param origOrderNo   支付订单号
     * @return
     * @throws Exception
     */
    public static JSONObject refund(String refundOrderNo, String origOrderNo) throws Exception {
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("orderNo", refundOrderNo);
        dataMap.put("origOrderNo", origOrderNo);
        dataMap.put("checkPassword", "N");


        log.info("============请求任务Start=============");
        log.info("汇联通退款-请求参数: " + JSON.toJSONString(dataMap));

        JSONObject returnObject = request("qtk/refund", dataMap);

        log.info("汇联通退款-响应参数: " + returnObject.toJSONString());
        log.info("============请求任务End==============");
        return  returnObject;
    }

    /**
     * 解析响应的参数
     * @param param 参数
     * @return
     */
    public static JSONObject resolveResponse(String param) {
        String data = param.replace("\\n", "");
        String decodeData = DesUtil.decode(HLT_CARD_SIGN_CODE, data, Charset.forName("UTF-8"));
        log.info("响应data参数: " + data);

        JSONObject returnObject = JSONObject.parseObject(decodeData);

        log.info("解析响应参数: " + returnObject.toJSONString());
        return returnObject;

    }

    public static void main(String[] args) {
        // {"respMessage":"ok","data":"Gbkl57c3fEBg+E3HfPuQ580JLkHaQPyf1P7My1oYOyJSIG4i8jYxovGVk4V8Rk58mjDswB8Vpy4E\nyj/wi/UNr8TDne094+yu","sign":"47186141FD8B3FB6CCB590F58321D9C6","respCode":"0000","responseId":"1669202185936"}
        String data = "Gbkl57c3fEBg+E3HfPuQ55SDLVyAf2Ys3VN1cifAfXIoT1gnbFR0NaiH/z1OIZZiuqlFwDLLu6n4\n" +
                "VBkM8fF5jVEekFNLY57NgRfRr4BghKXdIr8hdPJnbfOO0VtjITPrrZWwMDwfYzJulYhBsNGCubov\n" +
                "9ruAA0DN0ESoH765nvlH0lI/wdIOvRE7GyTfQzzT68i5p+Qf/k7yjQk22l4KUfuUVM+jMeW95xkd\n" +
                "+gVJvWctjBC0DN3zi3CwsVgQwVmj".replace("\\n", "");
        String decodeData = DesUtil.decode(HLT_CARD_SIGN_CODE, data, Charset.forName("UTF-8"));
        System.out.println(JSONObject.parseObject(decodeData));

    }

}
