package com.songhua.web.controller.park;

import com.songhua.common.core.domain.AjaxResult;
import com.songhua.common.utils.SignatureUtil;
import com.songhua.system.domain.dto.ParkData;
import com.songhua.system.service.IParkDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.songhua.common.core.domain.AjaxResult.success;


@Slf4j
@RestController
public class ParkingLotController {

    @Autowired
    private IParkDataService parkDataService;

    private static final String API_URL = "https://parking.youboyun.com.cn/thirdServer/v1/openApi";
    private static final String SIGN_FIELD = "sign";

    private static final Map<Integer, String> PARK_API_KEY_MAP = new HashMap<>();

    static {
        PARK_API_KEY_MAP.put(15305, "R3UuBEhxnkyhqLj8uJwEjHGBff8WxM");
        PARK_API_KEY_MAP.put(15338, "MQvp2y2DVzagEzhijar9iJ7rs2utaV");
    }

    @PostMapping("/getParkData")
    @ResponseBody
    public void getParkData(@RequestBody Map<String, Object> request) {
        // 获取停车场 ID
        int parkId = (int) request.get("park_id");
        // 获取对应的 API 密钥
        String apiKey = PARK_API_KEY_MAP.get(parkId);
        if (apiKey == null) {
            // 处理停车场 ID 对应的 API 密钥不存在的情况
            System.out.println("停车场 ID 对应的 API 密钥不存在");
            return;
        }
        // 准备请求体
        Map<String, Object> requestBody = prepareRequestBody(request);

        // 生成签名
        Object sign = SignatureUtil.sign2(requestBody, apiKey, SIGN_FIELD);
        requestBody.put(SIGN_FIELD, sign);

        // 发送POST请求到API
        RestTemplate restTemplate = new RestTemplate();
        Map<String, Object> response = restTemplate.postForObject(API_URL, requestBody, Map.class);

        // 验证签名并保存数据
        if (response != null && response.containsKey("code") && response.get("code").equals(1)) {
            if(!CollectionUtils.isEmpty((Collection<?>) response.get("data"))){
                saveParkData(response);
            }
        } else {
            log.error("调用接口失败：{}", response);
        }
    }

    private Map<String, Object> prepareRequestBody(Map<String, Object> request) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("service_name", "query_parkData");
        requestBody.put("park_id", request.get("park_id"));
        requestBody.put("reservedStr", request.get("reservedStr"));
        return requestBody;
    }

    private void saveParkData(Map<String, Object> response) {
        Map<String, Object> data = ((List<Map<String, Object>>) response.get("data")).get(0);
        ParkData statistics = new ParkData();
        statistics.setParkId(data.get("park_id").toString());
        statistics.setAllSpaceNumber(Integer.parseInt(data.get("allSpaceNumber").toString()));
        statistics.setUseSpaceNumber(Integer.parseInt(data.get("useSpaceNumber").toString()));
        statistics.setRemainSpaceNumber(Integer.parseInt(data.get("remainSpaceNumber").toString()));
        statistics.setInParkCount(Integer.parseInt(data.get("inParkCount").toString()));
        statistics.setOutParkCount(Integer.parseInt(data.get("outParkCount").toString()));
        statistics.setTotalOutMoney(Integer.parseInt(data.get("totalOutMoney").toString()));
        statistics.setTotalPreMoney(Integer.parseInt(data.get("totalPreMoney").toString()));
        parkDataService.save(statistics);
    }


    @GetMapping("/selectParkData")
    public AjaxResult selectParkData(ParkData parkData) {
        return success(parkDataService.selectParkData(parkData));
    }
}
