package cn.iocoder.yudao.module.pms.job;


import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotZHBD.DeviceLogDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotZHBD.DeviceZHBDDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotZHBD.TDLogDO;
import cn.iocoder.yudao.module.pms.dal.mysql.TDDeviceMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.iotopeationfill.IotOpeationFillMapper;
import cn.iocoder.yudao.module.pms.job.httpEntity.ApiResponse;
import cn.iocoder.yudao.module.pms.job.httpEntity.LocationData;
import cn.iocoder.yudao.module.pms.job.httpEntity.LoginRequestEntity;
import cn.iocoder.yudao.module.pms.job.httpEntity.LoginResponseEntity;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xingyuv.captcha.util.StringUtils;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yc
 * @version 1.0
 * @className test
 * @date 2025/6/8 16:42
 * @description
 */
@Component
@Slf4j
public class IotZHBDJob implements JobHandler {


    private static final String ID = "NjI1LjUyNS42ODg";
    private static final String SECRET = "3897865b70d7bf29fcca5029147f7d0a";
    private static final String TOKEN_URL = "https://zhbdgps.cn/video/webapi/user/login";
    private static final String LOCATION_URL="https://zhbdgps.cn/video/webapi/location/get-location-use-carids";
    private static final String TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGllbnRpZCI6MTA2NTUsInRraSI6MTEzMDQ0NjQ2MjE1NzcyMTYwMCwiY3J0IjoxNzQ5Njg1OTA0ODg5LCJjbGllbnROYW1lIjoiWUa8r83FIiwicm9sZWlkIjo1MywidXNlcnR5cGUiOjAsImx0cCI6ImFwaSIsIn" +
            "R5cGVpZCI6MTUwMSwiZXhwIjoxNzQ5NzcyMzA0ODg5LCJ1c2VyaWQiOjUyNSwic2VydmVyaWQiOjE0MywidXNlcm5hbWUiOiJ5Zmp0In0=.MmFlMDlhZjE3ZGI2NTM2ODgzZjcyZTI2ZTBmYWM1N2U=";


    @Autowired
    private IotOpeationFillMapper zhbdmapper;
    @Autowired
    private TDDeviceMapper deviceMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    @TenantIgnore
    public String execute(String param) throws Exception {
        String token = "";



        String parameter = "lng,lat,today_distance,distance,todayoil,totaloil,online,oil1,oil2,oil3,oil4";

        try {

            //发送令牌请求
            token = getLoginToken(ID, SECRET);

            List<DeviceZHBDDO> zhbdList = zhbdmapper.carList();
            // 准备请求参数
            String carIds = StringUtils.strip(zhbdList.stream().map(e->e.getCarId()).collect(Collectors.toList()).toString(),"[]").replace(" ","") ;
            Long timestamp = System.currentTimeMillis();  // 当前时间戳


            for (DeviceZHBDDO zhbddo:zhbdList) {
                // 构建请求JSON
                Map<String, Object> requestMap = new HashMap<>();
                requestMap.put("car_ids", zhbddo.getCarId());
                requestMap.put("time", timestamp);
                // 发送定位信息请求并获取响应
                if(token!=null){
                    String jsonResponse = sendPostRequest(requestMap,token);
                    ApiResponse response = parseResponse(jsonResponse);
                    // 处理结果
                    if (response != null && response.code == 200) {

                        List<Map<String,Object>> locations = response.data.data;

                        for (Map<String,Object> location : locations) {

                            if(String.valueOf(location.get("vehicle_id")).equals(zhbddo.getCarId())){

                                TDLogDO logDO = new TDLogDO();
                                List<DeviceLogDO> list = new ArrayList<>();

                                logDO.setTableName(zhbddo.getDeviceCode().toLowerCase());
                                logDO.setSerialNumber("'"+zhbddo.getDeviceCode()+"'");

                                Map<String, String> abcMap = new HashMap<>();
                                location.forEach((k,v)->{
                                    if(parameter.contains(k)){
                                        DeviceLogDO deviceLogDO = new DeviceLogDO();
                                        deviceLogDO.setLogValue(String.valueOf(v));
                                        deviceLogDO.setIsMonitor(0);
                                        deviceLogDO.setLogType(0);
                                        deviceLogDO.setIdentity(k);
                                        deviceLogDO.setMode(0);
                                        deviceLogDO.setRemark("");
                                        deviceLogDO.setBatchId(0);
                                        list.add(deviceLogDO);
                                        logDO.setList(list);

                                        /**
                                         * 存入Redis
                                         */
                                        Map<String, String> abc=new HashMap<>();
                                        abc.put("value",String.valueOf(v));
                                        abcMap.put(k, JSON.toJSONString(abc));


                                    }
                                });
                                redisTemplate.opsForHash().putAll("TSLV:"+zhbddo.getDeviceCode(),abcMap);

                                /**
                                 * 插入时序库
                                 */
                                deviceMapper.batchInsert(logDO);
                            }

                        }
                    } else {
                        System.err.println("获取定位信息请求失败: " + (response != null ? response.message : "未知错误"));
                    }
                }

            }
            // 解析响应

        } catch (Exception e) {
            e.printStackTrace();
        }


        //System.out.println("获取到的Token: " + token);
        return "执行成功";
    }


    public static String getLoginToken(String id, String secret) {

        // 2. 创建请求实体类
        LoginRequestEntity request = new LoginRequestEntity();
        request.setId(id);
        request.setSecret(secret);

        // 3. 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 4. 封装请求实体
        HttpEntity<LoginRequestEntity> entity = new HttpEntity<>(request, headers);

        // 5. 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<LoginResponseEntity> response = restTemplate.exchange(
                TOKEN_URL,
                HttpMethod.POST,
                entity,
                LoginResponseEntity.class
        );

        // 6. 处理响应
        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            LoginResponseEntity body = response.getBody();
            if (body.getData() != null && body.getData().getToken() != null) {
                return body.getData().getToken();
            } else {
                log.error("登录响应中token为空，响应内容: {}", body);
                return null;
            }
        } else {
            log.error("登录失败，状态码: {}", response.getStatusCode());
            return null;
        }
    }


    private static String sendPostRequest(Map<String, Object> requestData,String token) throws IOException {

        OkHttpClient client = new OkHttpClient();
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(requestData);
        RequestBody body = RequestBody.create(json, okhttp3.MediaType.parse("application/json"));

        Request request = new Request.Builder()
                .url(LOCATION_URL)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + token)// 关键头信息
                .build();
        String responseData = "";
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            responseData = response.body().string();
            System.out.println(responseData);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return responseData;
    }

    private static ApiResponse parseResponse(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(json, ApiResponse.class);
    }



}