package cn.iocoder.yudao.module.pms.controller.admin.iotrhdailyreport;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
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 cn.iocoder.yudao.module.pms.job.httpEntity.ApiOilResponse;
import cn.iocoder.yudao.module.pms.job.httpEntity.LoginRequestEntity;
import cn.iocoder.yudao.module.pms.job.httpEntity.LoginResponseEntity;
import cn.iocoder.yudao.module.pms.service.iotprojectinfo.IotProjectInfoService;
import cn.iocoder.yudao.module.pms.service.iotprojecttask.IotProjectTaskService;
import cn.iocoder.yudao.module.pms.service.iotrhdailyreport.IotRhDailyReportService;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "中航北斗")
@RestController
@RequestMapping("/pms/iot-rh-daily-report")
@Validated
@Slf4j
public class IotZHBDController {

    @Resource
    private IotRhDailyReportService iotRhDailyReportService;
    @Resource
    private DeptService deptService;
    @Resource
    private IotProjectInfoService iotProjectInfoService;
    @Resource
    private IotProjectTaskService iotProjectTaskService;
    @Resource
    private DictDataService dictDataService;

    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/report/fuel/daily/detail";
    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;

    @GetMapping("/getOil")
    @Operation(summary = "获得车辆油耗")
    public CommonResult<Map<Integer, Double>> getIotRhDailyReport() {
        String zhbdtoken = redisTemplate.opsForValue().get("zhbdtoken");
        if (StrUtil.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);
            }
        }
        // 构建请求JSON
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("client_ids", ID);
        requestMap.put("vehicle_ids", "2109,14777");
        requestMap.put("begin_time", "2025-11-15 8:00:00");
        requestMap.put("end_time", "2025-11-30 8:00:00");
        requestMap.put("page_num", 1);
        requestMap.put("page_size", 10);
        // key车辆carId   value油耗值
        Map<Integer, Double> carOilFuelPair = new HashMap<>();
        if (StrUtil.isNotBlank(zhbdtoken)) {
            try {
                String jsonResponse = sendPostRequest(requestMap, zhbdtoken);
                ApiOilResponse response = parseResponse(jsonResponse);
                if (response != null && response.code == 200) {
                    List<Map<String, Object>> details = response.data.pageList;
                    // 组装某辆车 某天的油耗

                    for (Map<String, Object> detail : details) {
                        System.out.println("当前油耗：" + (detail.get("oil")));
                        Integer carId = Integer.valueOf(detail.get("vehicle_id").toString());
                        Double oil = Double.valueOf(detail.get("oil").toString());
                        String vehicleName = String.valueOf(detail.get("vehicle_name"));
                        carOilFuelPair.put(carId, oil);
                    }
                }
            } catch (Exception e) {
                log.info("获取油耗数据失败！");
            }
        }
        return success(carOilFuelPair);
    }

    private 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 String sendPostRequest(Map<String, Object> requestData,String token) throws IOException {

        OkHttpClient client = new OkHttpClient();
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(requestData);
        okhttp3.RequestBody body = okhttp3.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 ApiOilResponse parseResponse(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(json, ApiOilResponse.class);
    }

}