package com.zehong.web.controller.gasuserthirdinterface;

import com.alibaba.fastjson.JSONObject;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.http.HttpClientUtils;
import com.zehong.common.utils.http.HttpUtils;
import com.zehong.common.utils.sign.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zehong
 * 居民用气量第三方查询
 */
@RestController
@RequestMapping("/gas/use")
public class GasUseThirdController {

    /**
     * 日志
     */
    private static final Logger log = LoggerFactory.getLogger(GasUseThirdController.class);

    @Value("${thirdGasUse.qinUrl}")
    private String qinUrl;

    @Value("${thirdGasUse.jinKa.appId}")
    private String appId;

    @Value("${thirdGasUse.jinKa.tenantId}")
    private String tenantId;

    @Value("${thirdGasUse.jinKa.loginUrl}")
    private String loginUrl;

    @Value("${thirdGasUse.jinKa.accessKeyId}")
    private String accessKeyId;

    @Value("${thirdGasUse.jinKa.accessKeySecret}")
    private String accessKeySecret;

    @Value("${thirdGasUse.jinKa.meterDetailUrl}")
    private String meterDetailUrl;


    /**
     * 秦川燃气表用气量查询
     * @param realMeterId 燃气表号
     * @return
     */
    @GetMapping("/getQinChuanGasStayCount")
    public AjaxResult getQinChuanGasStayCount(@RequestParam(value="realMeterId")String realMeterId){
        try{
            String result = HttpUtils.sendPost(qinUrl,"Data={\"OPType\":3,\"PayCode\":\"\",\"RealMeterID\":"+ realMeterId +"}");
            log.info("秦川燃气表用户用气量查询结果=================" + result);
            if(StringUtils.isEmpty(result)) return AjaxResult.error("秦川燃气表用气量查询失败");
            JSONObject resultJson = JSONObject.parseObject(result);
            if(!"1".equals(resultJson.getString("ResultCode"))) return AjaxResult.error(resultJson.getString("ResultMsg"));
            return AjaxResult.success(resultJson);
        }catch (Throwable a){
            log.error("秦川燃气表用气量查询失败:",a);
            return AjaxResult.error("秦川燃气表用气量查询失败");
        }
    }


    /**
     * 金卡燃气表用气量查询
     * @param meterNo 燃气表号
     * @return
     */
    @GetMapping("/getJinKaGasStayCount")
    public AjaxResult getJinKaGasStayCount(@RequestParam(value="meterNo")String meterNo){

        try{
            Map<String,Object> head = new HashMap<>();
            head.put("AccessToken",getJinKaToken());
            head.put("Authorization", Base64.encode((appId + ":" + tenantId + ":" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())).getBytes()));
            head.put("Accept","application/json");
            head.put("Content-Type","application/json;charset=utf-8");
            Map<String,Object> param = new HashMap<>();
            param.put("meterNo",meterNo);
            String result = HttpClientUtils.doGet(meterDetailUrl,param,head);
            log.info("金卡燃气表用户用气量查询结果=================" + result);
            if(StringUtils.isEmpty(result)) return AjaxResult.error("金卡燃气表用户用气量查询失败");
            return AjaxResult.success(JSONObject.parseObject(result));
        }catch (Throwable a){
            log.error("金卡燃气表用户用气量查询失败:",a);
            return AjaxResult.error("金卡燃气表用户用气量查询失败");
        }
    }

    /**
     * 金卡登录获取token
     * @return
     * @throws Exception
     */
    private String getJinKaToken() throws Exception {
        //入参
        JSONObject param = new JSONObject();
        param.put("accessKeyID",accessKeyId);
        param.put("accessKeySecret",accessKeySecret);
        //请求头
        Map<String, Object> head = new HashMap<>();
        head.put("appid",appId);
        head.put("tenantId",tenantId);
        head.put("Accept","application/json");
        head.put("Content-Type","application/json;charset=utf-8");
        String result = HttpClientUtils.doPost(loginUrl,param.toJSONString(),head);
        log.info("金卡登录token结果==============" + result);
        JSONObject jsonResult = JSONObject.parseObject(result);
        if(StringUtils.isEmpty(result) || !"00".equals(jsonResult.getString("code")) || null == jsonResult.getString("data")) throw new Exception("金卡token接口请求异常!");
        return jsonResult.getJSONObject("data").getString("accessToken");
    }

}
