package com.mushiny.wms.slam;

import com.mushiny.wms.common.utils.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

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

@Component
public class SlamTokenTimer implements CommandLineRunner{

    public static final Logger logger  = LoggerFactory.getLogger(SlamTokenTimer.class);

    //public static String token = null;
    @Value("${mushiny.midea.slam.url.login}")
    private String slam_login;
    @Value("${mushiny.midea.slam.url.login.user}")
    private String user;
    @Value("${mushiny.midea.slam.url.login.passwd}")
    private String passwd;

    private final SlamTripService slamTripService;
    private final RestTemplateBuilder builder;

    @Autowired
    public SlamTokenTimer(SlamTripService slamTripService, RestTemplateBuilder builder) {
        this.slamTripService = slamTripService;
        this.builder = builder;
    }

    @Override
    public void run(String... strings) throws Exception {
        //启动时获取
        genToken();
    }
    @Scheduled(fixedDelay = 60*20000L,initialDelay = 10000L)
    public void genToken() {
        RestTemplate restTemplate = this.builder.build();
        Map data = new HashMap();
        data.put("name",user);
        data.put("password",CommonUtils.md5(passwd).toLowerCase());
        String timespan = System.currentTimeMillis()+"";
        String sign = slamTripService.exportSign(data, timespan);
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("sign",sign);
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> httpEntity = new HttpEntity<String>(JSONUtil.mapToJSon(data), headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(this.slam_login, httpEntity, String.class);
            logger.info("Slam服务器返回数据是:"+responseEntity.getBody());
            Map res = JSONUtil.jsonToMap(responseEntity.getBody());
            Map resData = (Map) res.get("data");
            String token = (String) resData.get("token");
            logger.debug("新token是:"+token);
            this.slamTripService.setToken(token);
        } catch (Exception e) {
            logger.error("发送到激光AGV出错!", e);
        }
    }
}
