package com.jiayue.insu.incloud.compermisson;

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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jiayue.insu.incloud.constants.CommonStant;
import com.jiayue.insu.incloud.constants.enums.QNHLEnum;
import com.jiayue.insu.incloud.constants.vo.BJZYYJYSDTokenVo;
import com.jiayue.insu.incloud.entity.IntegrationCompany;
import com.jiayue.insu.incloud.entity.Record;
import com.jiayue.insu.incloud.entity.Station;
import com.jiayue.insu.incloud.service.IntegrationCompanyService;
import com.jiayue.insu.incloud.service.RecordService;
import com.jiayue.insu.incloud.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: tl
 * @Date: 2023/12/14 9:56
 */
@Component
@Slf4j
public class BJZYYJYSDComPermisson implements GeneratePermisson {

    @Autowired
    private IntegrationCompanyService integrationCompanyService;

    @Autowired
    private StationService stationService;

    @Autowired
    private RecordService recordService;

    private IntegrationCompany integrationCompany;

    @Override
    public Boolean generateKey(Station station) {
        Record record = new Record();
        record.setStationCode(station.getStationCode());
        record.setType(CommonStant.RECORD_TYPE_COM_PERMISSON);
        LocalDateTime localDateTime = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        record.setTime(localDateTime);
        record.setCreateTime(LocalDateTime.now());
        boolean result = false;
        String username = station.getUsername();
        String password = station.getPassword();
//        String passwordMD5 = DigestUtils.md5DigestAsHex(password.getBytes()).toUpperCase();
//        String auth = username+":"+passwordMD5;
        String auth = "Basic cGlnOkpxbXkjRnpqY0AyMDI1a2V5";
        IntegrationCompany integrationCompany = getIntegrationCompany(station.getInCode());
        if (integrationCompany != null) {

            record.setInCode(integrationCompany.getCode());

            String tokenUrl = integrationCompany.getComUrl();
            String response;
            String token;

            try {

                /**
                 * 请求头参数：
                 * Authorization: Basic dGVzdDp0ZXN0
                 * TENANT-ID: 4
                 * 说明：
                 * Authorization 值固定为 Basic dGVzdDp0ZXN0
                 * TENANT-ID 为登录用户所属租户 ID，目前固定为 4
                 *
                 *
                 *
                 * 请求表单参数：
                 * username:
                 * password:
                 * scope: server
                 * 参数说明：
                 * scope: 授权范围，这里固定为 server
                 * username: 用户名
                 * password: 密码
                 */
                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 BJZYYJYSDTokenVo = JSONUtil.toBean(response, BJZYYJYSDTokenVo.class);
                        if (BJZYYJYSDTokenVo.getAccess_token() != null && !BJZYYJYSDTokenVo.getAccess_token().equals("")) {
                            token = BJZYYJYSDTokenVo.getAccess_token();
                            log.info("========== 一体化token请求成功: {} token=" + token + "  ==========", station.getStationCode());
                            station.setComKey(token);
                            station.setKeyTime(Instant.ofEpochMilli(System.currentTimeMillis() + BJZYYJYSDTokenVo.getExpires_in() * 1000).atZone(ZoneId.systemDefault()).toLocalDateTime());
                            stationService.updateById(station);
                            record.setState(QNHLEnum.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;
    }


    IntegrationCompany getIntegrationCompany(String code) {
        if (this.integrationCompany == null) {
            LambdaQueryWrapper<IntegrationCompany> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(IntegrationCompany::getCode, code);
            this.integrationCompany = this.integrationCompanyService.getOne(lambdaQueryWrapper);
        }
        return this.integrationCompany;
    }


}

