package com.sky.ioc.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.ioc.mapper.job.TokenMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class LoginTokenJob implements Job {

    @Autowired
    TokenMapper tokenMapper;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format("获取登录token!  时间:" + new Date()));
        // 1.请求URL
        String postUrl = "http://192.168.1.45:9001/api/auth/login";
        // 2.请求参数JSON格式
        Map<String,String> map = tokenMapper.getNewToken();
        if(map==null){
            map = new HashMap<>();
            map.put("username","admin");
            map.put("password","admin123");
            tokenMapper.addToken(1,"admin","admin123");
        }
        map.put("loginType","API-TOKEN");
        String json = JSON.toJSONString(map);
        // 3.创建RestTemplate
          RestTemplate restTemplate = new RestTemplate();
        // 4.设置RestTemplate参数(请求头和body)
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(mediaType);
        headers.add("Accept", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        // 5.使用RestTemplate发起请求与接收返回值
        String resultData = restTemplate.postForObject(postUrl, entity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(resultData);
        Integer code = jsonObject.getInteger("code");
        String msg = jsonObject.getString("msg");
        if(code==200){
            JSONObject data = jsonObject.getJSONObject("data");
            String token = data.getString("access_token");
            String id = String.valueOf(map.get("id"));
            tokenMapper.updateToken(Integer.parseInt(id),token);
            log.info("token : "+token);
          //  System.out.println("data   "+data.getString(""));
        }else{
            log.info("登录接口失败："+msg);
        }
    }
}
