package com.zcloud.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.modules.djCarLog.entity.DjCarLogEntity;
import com.zcloud.modules.djCarLog.mapper.DjCarLogMapper;
import com.zcloud.modules.djPersonLog.entity.DjPersonLogEntity;
import com.zcloud.modules.djPersonLog.mapper.DjPersonLogMapper;
import com.zcloud.modules.job.task.ITask;
import com.zcloud.util.PerLocUtil;
import com.zcloud.util.ThreadPoolUtils;
import com.zcloud.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * 说明：TODO
 * 作者：wangxuan
 * 官网：www.zcloudchina.com
 * 闸机进出数据对接
 */
@Component("carAndPersonScheduledTasks")
public class CarAndPersonScheduledTasks implements ITask {

    @Autowired
    private PerLocUtil perLocUtil;

    @Resource
    private DjCarLogMapper djCarLogMapper;

    @Resource
    private DjPersonLogMapper djPersonLogMapper;


    ExecutorService threadPool = ThreadPoolUtils.getThreadPoolService();

    //正式使用
    static String CAR_URL = "http://192.168.210.32:8084/region/access/bayonetVehicleEntryAndExitRecords?";

    static String PERSON_URL = "http://192.168.210.32:8084/region/access/bayonetPersonnelEntryAndExitRecords?";

    @Override
    public void run(String params) {
        carTask();
        personTask();
    }

    public void carTask() {
        threadPool.execute(() -> {
            try {
                //开始时间为当前时间前10分钟
                String initialDates = formatDateTime(LocalDateTime.now().plusMinutes(-10));
                //结束时间为当前时间前5分钟
                String updatedDates = formatDateTime(LocalDateTime.now().plusMinutes(-5));
                MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
                paramMap.add("beginTime", initialDates);
                paramMap.add("endTime", updatedDates);
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.set("Authorization", perLocUtil.getToken());
                HttpEntity<String> entity = new HttpEntity<>(headers);

                String url = CAR_URL+"fstartDate="+initialDates+"&fendDate="+updatedDates+"&carsign=&accId=&entrystatus=&cartype=";
                ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

                if (response.getStatusCode().is2xxSuccessful()) {
                    String responseBody = response.getBody(); // 获取响应体字符串
                    JSONObject responseObject = JSONObject.parseObject(responseBody);
                    if(responseObject.get("code") != null && responseObject.get("code").toString().equals("200") ){
                        List<DjCarLogEntity> varList = JSONObject.parseArray(JSON.toJSON(responseObject.get("data")).toString(), DjCarLogEntity.class);
                        varList.forEach(item -> {
                            item.setCarLogId(UuidUtil.get32UUID());
                            item.setCorpinfoId("8854edee3aa94be496cee676b6d4845a");
                        });
                        djCarLogMapper.insert(varList);
                    }
                } else {
                    // 处理非成功状态码的情况
                    System.out.println("Request failed with status code: " + response.getStatusCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void personTask() {
        threadPool.execute(() -> {
            try {
                //开始时间为当前时间前10分钟
                String initialDates = formatDateTime(LocalDateTime.now().plusMinutes(-10));
                //结束时间为当前时间前5分钟
                String updatedDates = formatDateTime(LocalDateTime.now().plusMinutes(-5));
                MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
                paramMap.add("beginTime", initialDates);
                paramMap.add("endTime", updatedDates);
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.set("Authorization", perLocUtil.getToken());
                HttpEntity<String> entity = new HttpEntity<>(headers);

                String url = PERSON_URL+"fstartDate="+initialDates+"&fendDate="+updatedDates+"&empNo=&empId=&entrystatus=&accId=";
                ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
                if (response.getStatusCode().is2xxSuccessful()) {
                    String responseBody = response.getBody(); // 获取响应体字符串
                    JSONObject responseObject = JSONObject.parseObject(responseBody);
                    if(responseObject.get("code") != null && responseObject.get("code").toString().equals("200") ){
                        List<DjPersonLogEntity> varList = JSONObject.parseArray(JSON.toJSON(responseObject.get("data")).toString(), DjPersonLogEntity.class);
                        varList.forEach(item -> {
                            item.setPersonLogId(UuidUtil.get32UUID());
                            item.setCorpinfoId("8854edee3aa94be496cee676b6d4845a");
                        });
                        djPersonLogMapper.insert(varList);
                    }
                } else {
                    // 处理非成功状态码的情况
                    System.out.println("Request failed with status code: " + response.getStatusCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private static String formatDateTime(LocalDateTime dateTime) {
        if (dateTime == null) {
            return "null";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return dateTime.format(formatter);
    }


}
