package com.younike.system.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.younike.common.network.HttpClientUtils;
import com.younike.common.utils.integral.MyStringUtil;
import com.younike.system.domain.FamilyParam;
import com.younike.system.service.CoinService;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *优金豆连接外部接口
 */
@Service
public class CoinServiceImpl implements CoinService {

    private Log log = LogFactory.getLog(this.getClass());

    @Value("${award.domainName}")
    private String domainName;
    @Value("${award.appId}")
    private String appId;
    @Value("${award.secret_key}")
    private String secretKey;
    @Value("${award.youxianxin.merchant_number}")
    private String merchantNumber;

    /**
     * 查询会员积分和家庭积分 路径后缀
     */
    private static final String USER_INTEGRAL_PATH_SUFFIX = "/store-award/api/family/getUserIntegral";
    /* 解绑家庭成员 路径后缀 */
    private static final String upDownIntegralPathSuffix = "/store-award/api/family/upDownIntegral";

    /**
     * 根据手机号查询优金豆数量
     * @param phone
     * @return
     */
    @Override
    public String getCoin(String phone) {
        FamilyParam familyParam = new FamilyParam();
        familyParam.setPhone(phone);
        String url = domainName + USER_INTEGRAL_PATH_SUFFIX;
        JSONObject jsonObject = this.requestAward(url, familyParam);
        // 解析返回结果
        String jsonCode = jsonObject.getString("code");
        String jsonMsg = jsonObject.getString("msg");
        if ("200".equals(jsonCode)) {
            String jsonResult = jsonObject.getString("result");
            LinkedHashMap linkedHashMap = JSONArray.parseObject(jsonResult, LinkedHashMap.class);
            if (!linkedHashMap.isEmpty()) {
                if (linkedHashMap.containsKey("member")) {
                   return linkedHashMap.get("member").toString();
                }

            }
        } else {
            log.error("调用 award接口 获取 当前会员积分和家庭积分失败，失败信息：" + jsonMsg);

        }
        return "0";
    }

    /**
     * 新增/扣除 优金豆（积分）
     * @param param
     * @return
     */
    @Override
    public String increasePoints(FamilyParam param) {
        String integralId = "";
        param.setMerchantId(merchantNumber); // 设置 商户号，写死 优鲜信商户号
        String url = domainName + upDownIntegralPathSuffix;
        JSONObject jsonObject = this.requestAward(url, param);
        // 解析返回结果
        String jsonCode = jsonObject.getString("code");
        String jsonMsg = jsonObject.getString("msg");
        if ("200".equals(jsonCode)) {
            String jsonResult = jsonObject.getString("result");
            FamilyParam familyParam = JSONArray.parseObject(jsonResult, FamilyParam.class);
            if (familyParam != null) {
                integralId = familyParam.getIntegralId();
            } else {
                log.error("调用 award接口 新增/扣除 优金豆返回为空，返回信息" + jsonMsg);
            }
        } else {
            log.error("调用 award接口 新增/扣除 优金豆失败，失败信息：" + jsonMsg);
        }
        return jsonCode;
    }

    /**
     * 2021-8-28 Another 根据 路径、参数 请求 award接口
     * @param url 请求url
     * @param param 参数
     * @return
     */
    private JSONObject requestAward(String url, FamilyParam param) {
        // 获取 award 验签参数
        Map<String, String> map = new HashMap<>();
        String timestamp = String.valueOf(System.currentTimeMillis());
        map.put("appId", appId);
        map.put("timestamp", timestamp);

        // 获取 签名
        Map<String, String> params = new HashMap<>();
        params.put("appId", appId);
        params.put("secretKey", secretKey);
        params.put("time_stamp", timestamp);
        String paramStr = MyStringUtil.mapSort(params).toString();
        String sign = DigestUtils.md5DigestAsHex((secretKey + paramStr + secretKey).getBytes());
        map.put("sign", sign);

        String result = HttpClientUtils.postJson(url, param, map);

        // 解析返回结果
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }
}
