package com.hai.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.MD5Util;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.security.DesUtil;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.HttpsUtils;

import com.hai.common.utils.WxUtils;
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.*;

/**
 * 汇联通会员卡业务接口【贵州高速工会卡】
 */
public class HuiLianTongUnionCardConfig {

    /**
     * 根据手机号查询工会卡
     * @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);
    }

    /**
    * @Author Sum1Dream
    * @name submitSms.java
    * @Description // 请求汇联通短信接口
    * @Date 10:08 上午 2022/1/13
    * @Param [java.lang.String]
    * @return com.alibaba.fastjson.JSONObject
    */
    public static JSONObject submitSms(String mobile , String sms) throws Exception {
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("smsTypeCode", "NOTIFY_SMS");
        dataMap.put("senderId", "905c602647a74ad895d586364cb307a2");
        dataMap.put("channelCode", "HiSen");
        dataMap.put("mobile", mobile);
        dataMap.put("sms", sms);
        return request("hltsms/submitSms", 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, "");
        }

    }

    /**
    * @Author Sum1Dream
    * @name TCheckEMsgUnionCardVipRights.java
    * @Description // 会员体系接口
    * @Date 11:29 上午 2021/11/24
    * @Param [java.lang.String]
    * @return com.alibaba.fastjson.JSONObject
    */
    public static JSONObject checkEMsgUnionCardVipRights(String phone) {
        try {
            Map<String , String> map = new HashMap<>();
            map.put("phone" , phone);
            // 签名码
            String signCode = CommonSysConst.getSysConfig().getHltMembershipLevelSignCode();
            map.put("appId", signCode);

            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("phone" , phone);
            dataMap.put("appId", signCode);
            // Md5加密
            dataMap.put("sign", WxUtils.generateSignature(map, "chg;l;l23e2!~%^&22ovndfgf*@11212ouower=@=HSG!Business#Controller!" , WXPayConstants.SignType.MD5));
            return requestMembership("etcextra/checkEMsgUnionCardVipRights" , 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);
        System.out.println("工会卡支付请求参数" + JSON.toJSONString(dataMap));
        return request("qtk/deposit", dataMap);
    }

    /**
     * 支付
     * @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");
        dataMap.put("businessType", businessType);
        dataMap.put("instCode", instCode);
        dataMap.put("goodsDesc", goodsDesc);
        dataMap.put("tranDesc", tranDesc);
        System.out.println("工会卡支付请求参数" + JSON.toJSONString(dataMap));
        return request("qtk/consumption", dataMap);
    }

    /**
     * 退款
     * @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");
        return request("qtk/refund", dataMap);
    }


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

        Map<String,Object> map = new LinkedHashMap<>();
        map.put("accessCode", CommonSysConst.getSysConfig().getHuiLianTongUnionCardAccessCode());
        map.put("requestId", new Date().getTime());
        map.put("method", method);

        // 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());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getHuiLianTongUnionCardUrl(), JSON.toJSONString(map));
    }

    private static JSONObject requestMembership(String method,Map<String,Object> param) throws Exception {
        // 签名码
        String signCode = CommonSysConst.getSysConfig().getHltMembershipLevelSignCode();

        Map<String,Object> map = new LinkedHashMap<>();
        map.put("accessCode", CommonSysConst.getSysConfig().getHltMembershipLevelAccessCode());
        map.put("requestId", new Date().getTime());
        map.put("method", method);

        // 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());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getHuiLianTongUnionCardUrl(), JSON.toJSONString(map));
    }

    /**
     * 解析响应的参数
     * @param param 参数
     * @return
     */
    public static JSONObject resolveResponse(String param) {
        String data = param.replace("\\n", "");
        String decodeData = DesUtil.decode(CommonSysConst.getSysConfig().getHuiLianTongUnionCardSignCode(), data, Charset.forName("UTF-8"));
        return JSONObject.parseObject(decodeData);
    }

    /**
     * 解析响应的参数
     * @param param 参数
     * @return
     */
    public static JSONObject resolveResponseMembership(String param) {
        String data = param.replace("\\n", "");
        String decodeData = DesUtil.decode(CommonSysConst.getSysConfig().getHltMembershipLevelSignCode(), data, Charset.forName("UTF-8"));
        return JSONObject.parseObject(decodeData);
    }


    /**
     * @Author Sum1Dream
     * @name submitSms.java
     * @Description // 同步加油券订单
     * @Date 10:08 上午 2022/1/13
     * @Param [java.lang.String]
     * @return com.alibaba.fastjson.JSONObject
     */
    public static JSONObject syncPayOrder(Map<String, Object> map) throws Exception {
        return request("fuelCoupons/syncPayOrder", map);
    }

    public static void main(String[] args) {

        String data = "Gbkl57c3fEBg+E3HfPuQ55SDLVyAf2Ys3VN1cifAfXIoT1gnbFR0NaiH/z1OIZZiuqlFwDLLu6mt\\nuTcVJuO1hhr5QW09U1uIfz1mQwCBwvx4/PKxXQ7rR7/rnbvnsMxRupCMjc1vBdq902CiXq8RZVEq\\n8LrnkFZ9R+9IokVEc5nGG7XvKCmikEH80xtkvw0EwuPl1mEGp92uUbpxTahhwy5M9SAnIBZIjN5D\\nxi3F4tZ0kOhiuNNTO/CECE9sWZfO".replace("\\n", "");
        String decodeData = DesUtil.decode("F8E91A3C", data, Charset.forName("UTF-8"));
        JSONObject.parseObject(decodeData);

    }

}
