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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
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.IotDeviceDO;
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.IotDeviceMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.TDDeviceMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.iotopeationfill.IotOpeationFillMapper;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ZhbdJob 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 parameter = "lng,lat,today_distance,distance,todayoil,totaloil,online,oil1,oil2,oil3,oil4,vehicle_name";
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IotOpeationFillMapper zhbdmapper;
    @Autowired
    private TDDeviceMapper deviceMapper;
    @Autowired
    private IotDeviceMapper iotDeviceMapper;

    @Override
    @TenantIgnore
    public String execute(String param) throws Exception {
        String zhbdtoken = redisTemplate.opsForValue().get("zhbdtoken");
        if (StringUtils.isBlank(zhbdtoken)) {
            Map<String, String> map = new HashMap<>();
            map.put("id", ID);
            map.put("secret", SECRET);
            JSONObject entries = restTemplate.postForObject(TOKEN_URL, map, JSONObject.class);
            if (Objects.nonNull(entries)&&entries.get("code") != null&&Integer.parseInt(String.valueOf(entries.get("code")))==200) {
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(entries.get("data")));
                zhbdtoken = jsonObject.get("token").toString();
                redisTemplate.opsForValue().set("zhbdtoken", zhbdtoken, 80000, TimeUnit.SECONDS);
            }
        }
        List<DeviceZHBDDO> zhbdList = zhbdmapper.carList();
        String carIds = com.xingyuv.captcha.util.StringUtils.strip(zhbdList.stream().map(DeviceZHBDDO::getCarId).collect(Collectors.toList()).toString(),"[]").replace(" ","") ;
        String finalZhbdtoken = zhbdtoken;


        // 1. 设置请求头
        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON); // 表单类型
        // 或者设置为 JSON 类型：headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", finalZhbdtoken); // 添加自定义头信息
//                headers.addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                headers.add("Content-Type", "application/json");
                headers.add("Accept", "*/*");
                headers.add("Host", "zhbdgps.cn");
                headers.add("Connection", "keep-alive");

        // 2. 设置请求体参数
        // 方式一：表单参数（对应 MediaType.APPLICATION_FORM_URLENCODED）
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();

        params.add("car_ids", "8203,"+carIds+",8203");
        // 3. 组合请求头和请求体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        String result = restTemplate.postForObject(LOCATION_URL, requestEntity, String.class);
        JSONObject entries = JSON.parseObject(result,JSONObject.class);
        if (Objects.nonNull(entries)&&entries.get("code") != null&&Integer.parseInt(String.valueOf(entries.get("code")))==200) {
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(entries.get("data").toString());
            if (Objects.nonNull(jsonObject)) {
                List<Map> maps = JSON.parseArray(jsonObject.get("data").toString(), Map.class);
                for (Map<String,Object> location : maps) {
                    String vehicleId = String.valueOf(location.get("vehicle_id"));
                    zhbdList.stream().filter(e -> vehicleId.equals(e.getCarId())).findFirst().ifPresent(e -> {
                        TDLogDO logDO = new TDLogDO();
                        List<DeviceLogDO> list = new ArrayList<>();

                        logDO.setTableName(e.getDeviceCode().toLowerCase());
                        logDO.setSerialNumber("'"+e.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:"+e.getDeviceCode(),abcMap);
                        //插入td时序库
                        Integer i = deviceMapper.tableIfExist(logDO.getTableName().toLowerCase());
                        if (i==1) {
                            deviceMapper.batchInsert(logDO);
                        }
                        List<IotDeviceDO> iotDeviceDOS = iotDeviceMapper.selectByCodeIn(ImmutableList.of(e.getDeviceCode()));
                        if (CollUtil.isNotEmpty(iotDeviceDOS)) {
                            IotDeviceDO iotDeviceDO = iotDeviceDOS.get(0);
                            iotDeviceDO.setVehicleName(String.valueOf(location.get("vehicle_name")));
                            iotDeviceDO.setCarOnline(String.valueOf(location.get("online")));
                            iotDeviceMapper.updateZhbd(iotDeviceDO);
                        }
                    });
                }
            }
        }

        return "";
    }
}
