package com.luozhihui.project.controller;

import com.luozhihui.project.common.ApiResponse;
import com.luozhihui.project.entity.Parking;
import com.luozhihui.project.mapper.ParkingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/api")
@CrossOrigin
@RestController
public class ParkingController {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Resource
    ParkingMapper parkingMapper;
    @PostMapping("/webParking")
    @CrossOrigin
    public ApiResponse webParking() {
        String sql = "SELECT `parking`.id, parkingName, coord, COUNT(`car`.`parking_id`) as carsNumber " +
                "FROM `parking`, `car` WHERE parking.enable = 1 GROUP BY parking.id";

        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
        if (result.isEmpty()) {
            return new ApiResponse(null, 404, "停车场为空");
        }

        for (Map<String, Object> row : result) {
            String parkingId = row.get("id").toString();
            String countSql = "SELECT COUNT(parking_id) as carsNumber FROM car WHERE parking_id = ?";
            int carsNumber = jdbcTemplate.queryForObject(countSql, Integer.class, parkingId);
            row.put("carsNumber", carsNumber);
        }

        return new ApiResponse(result, 200, "停车场获取成功");
    }

    //查询所有停车场
    @PostMapping("/AllParking")
    public ApiResponse AllParking() {
        try {
            // 查询所有停车场
            List<Parking> parking = parkingMapper.FindAllParking();
            if (parking != null) {
                return new ApiResponse(parking, 200, "查询成功");
            } else {
                return new ApiResponse(null, 404, "未找到停车场"); // 如果未找到车辆，返回适当的状态码和消息
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse(e.getMessage(), 500, "服务器内部错误"); // 捕获任何异常并返回服务器内部错误
        }
    }

    //通过id查询信息
    @PostMapping("/FindParkingById")
    public ApiResponse FindParkingById(@RequestParam("id") Long id) {
        try {
            // 查询品牌信息
            Parking parking = (Parking) parkingMapper.FindParkingById(String.valueOf(id));

            if (parking != null) {
                return new ApiResponse(parking, 200, "查询成功");
            } else {
                return new ApiResponse(null, 404, "未找到停车场信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse(null, 500, "服务器内部错误：" + e.getMessage());
        }
    }
    //新增停车场
    @PostMapping("/AddParking")
    public ApiResponse AddBrand(@RequestBody Parking parking) {
        try {
            // 添加车辆
            parkingMapper.addParking(parking);
            // 返回成功消息
            return new ApiResponse(null, 200, "停车场添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            // 返回内部服务器错误
            return new ApiResponse(e.getMessage(), 500, "服务器内部错误");
        }
    }
    @CrossOrigin
//    删除停车场
    @PostMapping("/delete_parking")
    public ApiResponse delete_parking(@RequestBody Map<String, Object> requestBody) {
        try {
            String carIdsParam = (String) requestBody.get("ids");
            // 将逗号分隔的字符串carIdsParam拆分为carId列表
            List<String> carIdStrings = Arrays.asList(carIdsParam.split(","));
            List<Long> carIds = carIdStrings.stream().map(Long::parseLong).collect(Collectors.toList());
            int deletedCount = 0;
            for (Long carId : carIds) {
                boolean isDeleted = parkingMapper.DeleteParkingById(String.valueOf(carId));
                if (isDeleted) {
                    deletedCount++;
                }
            }
            if (deletedCount == carIds.size()) {
                return new ApiResponse(null, 200, "删除成功");
            } else if (deletedCount == 0) {
                return new ApiResponse(null, 404, "未找到信息");
            } else {
                return new ApiResponse(null, 207, "部分删除成功"); // 207 - Partial Content
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse(null, 500, "服务器内部错误");
        }
    }
    //更新停车场信息
    @PostMapping("/upparkinginfo")
    public ApiResponse updateCar(@RequestBody Parking parking) {
        System.out.println(parking.getId());
        System.out.println("-------------------------------");
        try {
            Parking existingParkinginfo = parkingMapper.ParkingId(Integer.valueOf(parking.getId()));
            System.out.println(existingParkinginfo);
            if (existingParkinginfo != null) {
                existingParkinginfo.setAddress(parking.getAddress());
                existingParkinginfo.setCarsNumber(parking.getCarsNumber());
                existingParkinginfo.setCoord(parking.getCoord());
                existingParkinginfo.setEnable(parking.getEnable());
                existingParkinginfo.setType(parking.getType());
                existingParkinginfo.setParkingName(parking.getParkingName());
                parkingMapper.update(existingParkinginfo);
                return new ApiResponse(null, 200, "停车场信息更新成功");
            } else {
                return new ApiResponse(null, 404, "品牌不存在");
            }
        } catch (Exception e) {
            return new ApiResponse(e.getMessage(), 500, "更新信息发生异常");
        }
    }

}
