package com.yupi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.project.annotation.AuthCheck;
import com.yupi.project.common.BaseResponse;
import com.yupi.project.common.DeleteRequest;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.constant.UserConstant;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.exception.ThrowUtils;
import com.yupi.project.model.dto.charging_robot.ChargingRobotAddRequest;
import com.yupi.project.model.dto.charging_robot.ChargingRobotQueryRequest;
import com.yupi.project.model.dto.charging_robot.ChargingRobotUpdateRequest;
import com.yupi.project.model.entity.ChargingRobot;
import com.yupi.project.model.enums.RobotStatusEnum;
import com.yupi.project.service.ChargingRobotService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 充电机器人管理接口 (管理员权限)
 */
@RestController
@RequestMapping("/admin/robot")
@Slf4j
@Api(tags = "充电机器人管理接口 (管理员)")
public class ChargingRobotAdminController {

    @Resource
    private ChargingRobotService chargingRobotService;

    @ApiOperation("添加充电机器人")
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addChargingRobot(@RequestBody ChargingRobotAddRequest addRequest, HttpServletRequest request) {
        if (addRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 参数校验
        if (StringUtils.isBlank(addRequest.getRobotUid())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "机器人UID不能为空");
        }
        if (addRequest.getStatus() == null || RobotStatusEnum.getEnumByValue(addRequest.getStatus()) == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的机器人状态");
        }
        if (addRequest.getBatteryLevel() != null && (addRequest.getBatteryLevel() < 0 || addRequest.getBatteryLevel() > 100)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "电池电量必须在0到100之间");
        }

        // 检查机器人UID是否已存在
        if (chargingRobotService.findByRobotUid(addRequest.getRobotUid()) != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "机器人UID '" + addRequest.getRobotUid() + "' 已存在");
        }

        ChargingRobot newRobot = new ChargingRobot();
        newRobot.setRobotUid(addRequest.getRobotUid());
        newRobot.setStatus(addRequest.getStatus()); // Directly use the validated status string
        if (addRequest.getBatteryLevel() != null) {
            newRobot.setBatteryLevel(addRequest.getBatteryLevel());
        }
        if (StringUtils.isNotBlank(addRequest.getCurrentLocation())) {
            newRobot.setCurrentLocation(addRequest.getCurrentLocation());
        }
        // Set createTime and updateTime if your entity doesn't auto-set them with @TableField(fill = ...)
        // newRobot.setCreateTime(new Date());
        // newRobot.setUpdateTime(new Date());

        boolean saved = chargingRobotService.save(newRobot);
        if (!saved || newRobot.getId() == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加机器人失败");
        }

        return ResultUtils.success(newRobot.getId());
    }

    @ApiOperation("删除充电机器人")
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteChargingRobot(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = chargingRobotService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    @ApiOperation("更新充电机器人信息")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChargingRobot(@RequestBody ChargingRobotUpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null || updateRequest.getId() == null || updateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ChargingRobot chargingRobot = new ChargingRobot();
        BeanUtils.copyProperties(updateRequest, chargingRobot);

        if (StringUtils.isNotBlank(updateRequest.getStatus()) && RobotStatusEnum.getEnumByValue(updateRequest.getStatus()) == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的机器人状态值");
        }
        if (updateRequest.getBatteryLevel() != null && (updateRequest.getBatteryLevel() < 0 || updateRequest.getBatteryLevel() > 100)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的电池电量值");
        }

        boolean result = chargingRobotService.updateById(chargingRobot);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @ApiOperation("根据ID获取充电机器人信息")
    @GetMapping("/get/{id}")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<ChargingRobot> getChargingRobotById(@PathVariable long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ChargingRobot chargingRobot = chargingRobotService.getById(id);
        ThrowUtils.throwIf(chargingRobot == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(chargingRobot);
    }

    @ApiOperation("分页获取充电机器人列表")
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ChargingRobot>> listChargingRobotsByPage(@RequestBody ChargingRobotQueryRequest queryRequest, HttpServletRequest request) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        Page<ChargingRobot> page = new Page<>(current, size);
        QueryWrapper<ChargingRobot> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(queryRequest.getRobotUid())) {
            queryWrapper.like("robot_uid", queryRequest.getRobotUid());
        }
        if (StringUtils.isNotBlank(queryRequest.getStatus())) {
            queryWrapper.eq("status", queryRequest.getStatus());
        }
        if (StringUtils.isNotBlank(queryRequest.getSortField())) {
            queryWrapper.orderBy(true, queryRequest.getSortOrder().equals("ascend"), queryRequest.getSortField());
        }
        chargingRobotService.page(page, queryWrapper);
        return ResultUtils.success(page);
    }

    @ApiOperation("获取所有机器人状态类型")
    @GetMapping("/status/types")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<String>> getRobotStatusTypes() {
        List<String> statusTypes = Arrays.stream(RobotStatusEnum.values())
                .map(RobotStatusEnum::getValue)
                .collect(Collectors.toList());
        return ResultUtils.success(statusTypes);
    }
} 