package com.jiayue.insu.incloud.compermisson;

import cn.hutool.core.date.DateUtil;
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.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jiayue.insu.incloud.constants.CommonStant;
import com.jiayue.insu.incloud.constants.enums.QNHLEnum;
import com.jiayue.insu.incloud.constants.vo.ResponseVo;
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 org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

/**
 * 清能生成通讯token
 *
 * @author yh
 * @version 1.0
 * @since 2022/5/22 11:29
 */
@Component
@Slf4j
public class QNHLComPermisson 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;
        IntegrationCompany integrationCompany = getIntegrationCompany(station.getInCode());
        if(integrationCompany!=null){

            record.setInCode(integrationCompany.getCode());

            String tokenUrl = integrationCompany.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;
    }


    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;
    }
}
