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.JSON;
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.QNHLEnum;
import com.jiayue.insu.inclientqn.model.ResponseVo;
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 org.springframework.util.DigestUtils;
import java.time.LocalDateTime;

/**
 * 清能生成通讯token
 *
 * @author yh
 * @version 1.0
 * @since 2022/5/22 11:29
 */
@Component
@Slf4j
public class ComPermisson {

    @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;
        String username = station.getUsername();
        String password = station.getPassword();
        String passwordMD5 = DigestUtils.md5DigestAsHex(password.getBytes()).toUpperCase();
        String auth = username + ":" + passwordMD5;

        String tokenUrl = station.getComurl();
        String response;
        String token;

        try {
            HttpRequest httpRequest = HttpRequest.post(tokenUrl)
                    .header("Content-Type", "application/json")
                    .header("Authorization", auth);
            httpRequest.setGlobalTimeout(20000);
            response = httpRequest.execute().body();
            if (StrUtil.isNotEmpty(response)) {
                boolean isJson = JSONUtil.isJsonObj(response);
                if (isJson) {
                    JSON resultJson = JSONUtil.parse(response);
                    ResponseVo responseVo = JSONUtil.toBean(response, ResponseVo.class);
                    if (responseVo.getRetCode().equals(QNHLEnum.REQUEST_SUCCESS.getCode())) {
                        token = responseVo.getData();
                        log.info("========== 一体化token请求成功: {} token=" + token + "  ==========", station.getStationCode());
                        station.setComKey(token);
                        station.setKeyTime(LocalDateTime.now().plusDays(1));
                        stationService.updateById(station);
                        record.setState(QNHLEnum.REQUEST_SUCCESS.getSign());
                        result = true;
                    } else {
                        log.error("========== 一体化token请求异常: {} 接收retCode响应码非成功标识T200 标识为" + resultJson.getByPath("retCode") + " " + resultJson.getByPath("retMsg") + " ==========", station.getStationCode());
                        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;
    }

    /**
     * 校验token
     * @param station 场站
     * @return 是否
     */
    public boolean isToken(Station station){
        boolean result = false;
        String token = station.getComKey();
        LocalDateTime tokenTime = station.getKeyTime();
        if (StrUtil.isEmpty(token) || LocalDateTime.now().isAfter(tokenTime)) {
            if (generateKey(station)) {
                station = stationService.findThis();
                token = station.getComKey();
                tokenTime = station.getKeyTime();
            }
        }

        if (StrUtil.isNotEmpty(token) && LocalDateTime.now().isBefore(tokenTime)){
            result = true;
        }
        return result;
    }

}
