package com.xindazhou.business.controller.app.vehicle;

import com.xindazhou.business.controller.app.vehicle.convert.VehicleConvert;
import com.xindazhou.business.controller.app.vehicle.vo.*;
import com.xindazhou.framework.common.pojo.CommonResult;
import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.framework.common.pojo.PageParam;
import com.xindazhou.framework.security.core.util.SecurityFrameworkUtils;
import com.xindazhou.vehicle.api.VehicleApi;
import com.xindazhou.vehicle.api.VehicleBindApi;
import com.xindazhou.vehicle.api.VehicleStatusApi;
import com.xindazhou.vehicle.api.dto.VehicleRespDTO;
import com.xindazhou.vehicle.api.dto.bind.VehicleCreateAndBindReqDTO;
import com.xindazhou.vehicle.api.dto.bind.VehicleBindRespDTO;
import com.xindazhou.vehicle.api.dto.status.VehicleStatusRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.xindazhou.framework.common.pojo.CommonResult.success;

/**
 * 移动端 - 车辆管理 Controller
 *
 * @author xindazhou
 */
@Tag(name = "移动端 - 车辆管理")
@RestController("appVehicleController")
@RequestMapping("/app/vehicle")
@Validated
@Slf4j
public class VehicleController {

    @Resource
    private VehicleApi vehicleApi;

    @Resource
    private VehicleBindApi vehicleBindApi;

    @Resource
    private VehicleStatusApi vehicleStatusApi;

    @GetMapping("/list")
    @Operation(summary = "查询用户绑定的车辆列表")
    public CommonResult<PageResult<VehicleListRespVO>> getVehicleList(@Valid PageParam pageParam) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        // 默认用户类型为1（会员用户）
        Integer userType = 1;
        
        // 查询用户绑定的车辆列表
        CommonResult<List<VehicleRespDTO>> vehiclesResult = vehicleApi.listVehicleByUserId(userId, userType);
        List<VehicleRespDTO> vehicles = vehiclesResult.getData();
        
        // 查询用户的所有绑定关系
        CommonResult<List<VehicleBindRespDTO>> bindingsResult = vehicleBindApi.listBindByUserId(userId, userType);
        List<VehicleBindRespDTO> bindings = bindingsResult.getData();
        
        // 构建vehicleId到binding的映射
        Map<Long, VehicleBindRespDTO> bindingMap = bindings.stream()
                .collect(Collectors.toMap(VehicleBindRespDTO::getVehicleId, b -> b, (b1, b2) -> b1));
        
        // 转换为VehicleListRespVO
        List<VehicleListRespVO> list = vehicles.stream()
                .map(vehicle -> {
                    VehicleListRespVO vo = new VehicleListRespVO();
                    vo.setId(vehicle.getId());
                    vo.setVin(vehicle.getVin());
                    vo.setName(vehicle.getName());
                    vo.setBluetoothMac(vehicle.getBluetoothMac());
                    vo.setStatus(vehicle.getStatus());
                    
                    VehicleBindRespDTO binding = bindingMap.get(vehicle.getId());
                    if (binding != null) {
                        vo.setIsDefault(binding.getIsDefault() != null ? binding.getIsDefault() : 0);
                        vo.setUserType(binding.getUserType());
                        vo.setBindTime(binding.getBindTime());
                    }
                    return vo;
                })
                .collect(Collectors.toList());
        
        return success(new PageResult<>(list, (long) list.size()));
    }

    @GetMapping("/get")
    @Operation(summary = "查询车辆详情")
    @Parameter(name = "id", description = "车辆ID", required = true, example = "1")
    public CommonResult<VehicleDetailRespVO> getVehicle(@RequestParam("id") Long id) {
        CommonResult<VehicleRespDTO> result = vehicleApi.getVehicle(id);
        VehicleDetailRespVO vehicle = VehicleConvert.INSTANCE.convert(result.getData());
        return success(vehicle);
    }

    @PostMapping("/bind")
    @Operation(summary = "绑定车辆")
    public CommonResult<VehicleDetailRespVO> bindVehicle(@Valid @RequestBody VehicleBindReqVO bindReqVO) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        
        // 构建创建并绑定请求
        VehicleCreateAndBindReqDTO reqDTO = new VehicleCreateAndBindReqDTO();
        reqDTO.setVin(bindReqVO.getVin());
        reqDTO.setDeviceSn(bindReqVO.getDeviceSn());
        reqDTO.setName(bindReqVO.getName());
        reqDTO.setBluetoothMac(bindReqVO.getBluetoothMac());
        reqDTO.setImageUrl(bindReqVO.getImageUrl());
        reqDTO.setModelId(bindReqVO.getModelId());
        reqDTO.setFirmwareVersion(bindReqVO.getFirmwareVersion());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(bindReqVO.getUserType());
        
        // 调用创建并绑定接口
        CommonResult<VehicleRespDTO> result = vehicleBindApi.createVehicleAndBind(reqDTO);
        VehicleDetailRespVO vehicle = VehicleConvert.INSTANCE.convert(result.getData());
        return success(vehicle);
    }

    @DeleteMapping("/unbind")
    @Operation(summary = "解绑车辆")
    @Parameter(name = "vehicleId", description = "车辆ID", required = true, example = "1")
    public CommonResult<Boolean> unbindVehicle(@RequestParam("vehicleId") Long vehicleId) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        CommonResult<Boolean> result = vehicleBindApi.unbindVehicle(userId, vehicleId);
        return success(result.getData());
    }

    @PutMapping("/update")
    @Operation(summary = "更新车辆信息")
    public CommonResult<Boolean> updateVehicle(@Valid @RequestBody VehicleUpdateReqVO updateReqVO) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        
        // 构建更新请求DTO
        com.xindazhou.vehicle.api.dto.VehicleUpdateReqDTO reqDTO = new com.xindazhou.vehicle.api.dto.VehicleUpdateReqDTO();
        reqDTO.setId(updateReqVO.getId());
        reqDTO.setName(updateReqVO.getName());
        reqDTO.setImageUrl(updateReqVO.getImageUrl());
        
        // TODO: 验证用户权限（只有车主或授权用户可修改）
        // 可以调用vehicleBindApi.listBindByUserId检查用户是否有权限
        
        CommonResult<Boolean> result = vehicleApi.updateVehicle(reqDTO);
        return success(result.getData());
    }

    @PutMapping("/set-default")
    @Operation(summary = "设置默认车辆")
    @Parameter(name = "vehicleId", description = "车辆ID", required = true, example = "1")
    public CommonResult<Boolean> setDefaultVehicle(@RequestParam("vehicleId") Long vehicleId) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        CommonResult<Boolean> result = vehicleBindApi.setDefaultVehicle(userId, vehicleId);
        return success(result.getData());
    }

    @GetMapping("/status")
    @Operation(summary = "查询车辆状态")
    @Parameter(name = "vehicleId", description = "车辆ID", required = true, example = "1")
    public CommonResult<VehicleStatusRespVO> getVehicleStatus(@RequestParam("vehicleId") Long vehicleId) {
        CommonResult<VehicleStatusRespDTO> result = vehicleStatusApi.getVehicleStatus(vehicleId);
        VehicleStatusRespVO status = VehicleConvert.INSTANCE.convertStatus(result.getData());
        return success(status);
    }

}

