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.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.model.BJZYYJYSDTokenVo;
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;

/**
 * 山东国家研究院生成通讯token
 *
 * @author fxy
 * @version 1.0
 * @since 2023/12/14 11:29
 */
@Component
@Slf4j
public class BJZYYJYSDComPermisson {

    @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(BJZYYJYSDEnum.REQUEST_FAIL.getSign());
        record.setStationCode(station.getStationCode());

        boolean result = false;
        // 用户名
        String username = station.getUsername();
        // 密码
        String password = station.getPassword();
        // 身份验证
//        String auth = "Basic dGVzdDp0ZXN0";
        String auth = "Basic cGlnOkpxbXkjRnpqY0AyMDI1a2V5";
        // token地址
        String tokenUrl = station.getComurl();
        String response;
        String token;
        // 请求token
        try {
            HttpRequest httpRequest = HttpRequest.post(tokenUrl)
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header("Authorization", auth)
                    .header("TENANT-ID", "4").
                            form("username",username).
                            form("password",password).
                            form("scope","server");
            httpRequest.setGlobalTimeout(20000);
            response = httpRequest.execute().body();
            // 判断响应内容
            if (StrUtil.isNotEmpty(response)) {
                boolean isJson = JSONUtil.isJsonObj(response);
                if (isJson) {
                    BJZYYJYSDTokenVo sdTokenVo = JSONUtil.toBean(response, BJZYYJYSDTokenVo.class);
                    if (sdTokenVo.getAccess_token() != null) {
                        token = sdTokenVo.getAccess_token();
                        log.info("========== 山东国家研究院一体化token请求成功: {} token=" + token + "  ==========", station.getStationCode());
                        station.setComKey(token);
                        station.setKeyTime(Instant.ofEpochMilli(System.currentTimeMillis() + sdTokenVo.getExpires_in() * 1000).atZone(ZoneId.systemDefault()).toLocalDateTime());
                        stationService.updateById(station);
                        record.setState(BJZYYJYSDEnum.REQUEST_SUCCESS.getSign());
                        result = true;
                    } else {
                        log.error("========== 未成功获取到鉴权令牌 ========== ");
                        log.info("========== 请求参数 账号密码:" + username + ":" + password + " MD5加密:" + auth + " ==========");
                    }
                } 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;
    }
}
