package lingtao.net.util;


import com.alibaba.fastjson.JSONObject;
import lingtao.net.vo.HuaFangPriceRequstVo;
import lingtao.net.vo.HuaFangPriceResultVo;
import lingtao.net.vo.HuaFangTokenVo;
import okhttp3.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class HuaFangPriceUtil {


    private static final String userName = "001008";

    private static final String password = "lt666888";


    public static String getToken() {
        String token = "";
        LocalDateTime currentTime = LocalDateTime.now();
        String templateName = "HUAFANG_TOKEN";

        if (!RedisUtil.exists(templateName)) {
            Map<String, String> params = new HashMap<>();
            params.put("userName", userName);
            params.put("password", password);

            String tokenString = HttpUtils.sendPostRequest("http://ds.gw.chenghuiyin.com/ordering/api/User/GetToken", JSONObject.toJSONString(params));
            System.out.println("获取token返回:" + tokenString);
            HuaFangTokenVo huaFangTokenVo = JSONObject.parseObject(tokenString, HuaFangTokenVo.class);
            RedisUtil.set(templateName, huaFangTokenVo.getAccessToken(), huaFangTokenVo.getExpiresIn() - 50);
        }
        Object tokenObj = RedisUtil.get(templateName);
        if (tokenObj != null) {
            token = tokenObj.toString();
        }
        System.out.println("获取token:" + token);
        return token;
    }

    public static HuaFangPriceResultVo getPrice(HuaFangPriceRequstVo params) {
        Map<String, String> heards = new HashMap<>();
        heards.put("Authorization", "Bearer " + getToken());
        String resultText = HttpUtils.sendPostRequest("http://ds.quote.chenghuiyin.com/api/app/price/calc-price", JSONObject.toJSONString(params), heards);
        HuaFangPriceResultVo result = JSONObject.parseObject(resultText, HuaFangPriceResultVo.class);
        return result;
    }
}
