package com.jiayue.insu.inclientqn.permisson.com;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jiayue.insu.inclientqn.constant.CommonStant;
import com.jiayue.insu.inclientqn.entity.Record;
import com.jiayue.insu.inclientqn.entity.Station;
import com.jiayue.insu.inclientqn.inenum.BJZYYJYSDEnum;
import com.jiayue.insu.inclientqn.inenum.QNHLEnum;
import com.jiayue.insu.inclientqn.model.BJZYYJYSDTokenVo;
import com.jiayue.insu.inclientqn.model.WXResponseVo;
import com.jiayue.insu.inclientqn.service.RecordService;
import com.jiayue.insu.inclientqn.service.StationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;

/**
 * 武穴天机生成通讯token
 *
 * @author fxy
 * @version 1.0
 * @since 2023/12/14 11:29
 */
@Component
@Slf4j
public class WXComPermisson {

    @Autowired
    private StationService stationService;
    @Autowired
    private RecordService recordService;

    /**
     * 生成武穴一体化token
     *
     * @param station
     * @return
     */
    public Boolean generateKey(Station station) {
        // 记录
        Record record = new Record();
        record.setType(CommonStant.RECORD_TYPE_COM_PERMISSON);
        LocalDateTime localDateTime = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        record.setTime(localDateTime);
        record.setCreateTime(LocalDateTime.now());
        // 此处借用清能枚举，不新增武穴枚举
        record.setState(QNHLEnum.REQUEST_FAIL.getSign());
        record.setStationCode(station.getStationCode());
        boolean result = false;
        // token地址
        String tokenUrl = station.getComurl();
        String response;
        String token;
        Map<String,String> map = new HashMap<>();
        // 固定的请求体 直接写死
        map.put("accessKey","ik68V9W7YownNJwN8TyH6pW2DurQgbo3kFJtIBn58l");
        map.put("secretKey","{noop}bCycOavnyAL25Jde2vXLClXuBJ6g0BenvVbEHFCmO0YZKiHxWxLk7zS5ct4i8lxOGBlLMiwhn1mriE0HQbBry");
        // 请求token
        try {
            HttpRequest httpRequest = HttpRequest.post(tokenUrl)
                    .header("Content-Type", "application/json");
            httpRequest.setGlobalTimeout(20000);
            response = httpRequest.body(JSONUtil.toJsonStr(map)).execute().body();
            // 判断响应内容
            if (StrUtil.isNotEmpty(response)) {
                boolean isJson = JSONUtil.isJsonObj(response);
                if (isJson) {
                    WXResponseVo wxResponseVo = JSONUtil.toBean(response, WXResponseVo.class);
                    if (wxResponseVo.getData() != null) {
                        // 获取到token
                        JSONObject jsonObject = new JSONObject(wxResponseVo.getData());
                        String dataObject = jsonObject.getStr("token");
                        token = dataObject;
                        log.info("========== 武穴一体化token请求成功: {} token=" + token + "  ==========", station.getStationCode());
                        station.setComKey(token);
                        // token过期时间3小时
                        station.setKeyTime(Instant.ofEpochMilli(System.currentTimeMillis() + 3 * 60 * 60 * 1000L).atZone(ZoneId.systemDefault()).toLocalDateTime());
                        stationService.updateById(station);
                        record.setState(QNHLEnum.REQUEST_SUCCESS.getSign());
                        result = true;
                    } else {
                        log.error("========== 未成功获取到鉴权令牌 ========== ");
                    }
                } else {
                    log.error("========== 武穴一体化token请求异常: {} 接收响应字符串非json格式 ==========", station.getStationCode());
                }
            } else {
                log.error("========== 武穴一体化token请求异常: {} 接收响应字符串为空 ==========", station.getStationCode());
            }

        } catch (Exception e) {
            log.error("========== 武穴一体化token请求异常: {} 连接断开或请求超时 ==========", station.getStationCode());
            e.printStackTrace();

        }
        // 保存记录
        recordService.save(record);
        return result;
    }
}
