package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.common.DataEnrichmentUtil;
import com.rj.entity.CustomerManagement;
import com.rj.entity.DeviceManagement;
import com.rj.entity.SalesManagement;
import com.rj.service.IDeviceManagementService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 设备管理表 前端控制器
 * </p>
 *
 * @author 李中华 ,spllzh
 * @since 2025-08-07
 */
@RestController
@RequestMapping("/api/deviceManagement")
@Tag(name = "设备管理", description = "设备管理相关接口")
public class DeviceManagementController {

    @Autowired
    private IDeviceManagementService deviceManagementService;

    /**
     * 新增设备
     */
    @PostMapping("/add")
    @Operation(summary = "新增设备", description = "添加新的设备信息")
    public ResponseEntity<Map<String, Object>> addDevice(
            @Parameter(description = "设备信息", required = true)
            @RequestBody DeviceManagement deviceManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            deviceManagement.setCreateTime(LocalDateTime.now());
            deviceManagement.setUpdateTime(LocalDateTime.now());
            boolean success = deviceManagementService.save(deviceManagement);
            if (success) {
                result.put("success", true);
                result.put("message", "设备添加成功");
                result.put("data", deviceManagement);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "设备添加失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设备添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID查询设备
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询设备", description = "根据设备ID获取设备详细信息")
    public ResponseEntity<Map<String, Object>> getDeviceById(
            @Parameter(description = "设备ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            DeviceManagement device = deviceManagementService.getById(id);
            if (device != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", device);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "设备不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据设备编号查询
     */
    @GetMapping("/getByCode")
    @Operation(summary = "根据设备编号查询", description = "根据设备编号查询设备信息")
    public ResponseEntity<Map<String, Object>> getDeviceByCode(
            @Parameter(description = "设备编号", required = true)
            @RequestParam String deviceCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<DeviceManagement> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DeviceManagement::getDeviceCode, deviceCode);
            List<DeviceManagement> deviceList = deviceManagementService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", deviceList);
            result.put("count", deviceList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @Autowired
    private DataEnrichmentUtil dataEnrichmentUtil;
    /**
     * 分页查询设备列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询设备列表", description = "分页查询设备信息列表")
    public ResponseEntity<Map<String, Object>> getDeviceList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "设备编号（模糊查询）")
            @RequestParam(required = false) String deviceCode,
            @Parameter(description = "所属门店ID")
            @RequestParam(required = false) String dealershipId,
            @Parameter(description = "绑定状态")
            @RequestParam(required = false) Boolean bindStatus,
            @Parameter(description = "场景")
            @RequestParam(required = false) String scenario,
            @Parameter(description = "电话")
            @RequestParam(required = false) String salesPhone) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<DeviceManagement> page = new Page<>(current, size);
            LambdaQueryWrapper<DeviceManagement> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (deviceCode != null && !deviceCode.trim().isEmpty()) {
                queryWrapper.like(DeviceManagement::getDeviceCode, deviceCode);
            }
            if (dealershipId != null && !dealershipId.trim().isEmpty()) {
                queryWrapper.eq(DeviceManagement::getDealershipId, dealershipId);
            }
            if (bindStatus != null) {
                queryWrapper.eq(DeviceManagement::getBindStatus, bindStatus);
            }
            if (scenario != null && !scenario.trim().isEmpty()) {
                queryWrapper.eq(DeviceManagement::getScenario, scenario);
            }
            if (salesPhone != null && !salesPhone.trim().isEmpty()) {
                queryWrapper.eq(DeviceManagement::getSalesPhone, salesPhone);
            }
            
            // 按getUpdateTime 时间倒序排列
            queryWrapper.orderByDesc(DeviceManagement::getUpdateTime);
            
            Page<DeviceManagement> devicePage = deviceManagementService.page(page, queryWrapper);

            // 使用工具类提取ID列表
            List<String> dealershipIds = DataEnrichmentUtil.extractIds(devicePage.getRecords(), DeviceManagement::getDealershipId);
            List<String> projectIds = DataEnrichmentUtil.extractIds(devicePage.getRecords(), DeviceManagement::getProjectId);
            List<String> saleIds = DataEnrichmentUtil.extractIds(devicePage.getRecords(), DeviceManagement::getBindUserId);

            // 使用工具类批量获取关联数据
            Map<String, String> saleNameMap = dataEnrichmentUtil.getSalesIdNameMap(saleIds);
            Map<String, String> dealershipNameMap = dataEnrichmentUtil.getDealershipIdNameMap(dealershipIds);
            Map<String, String> projectNameMap = dataEnrichmentUtil.getProjectIdNameMap(projectIds);

            for (DeviceManagement deviceManagement : devicePage.getRecords()) {
                deviceManagement.setDealershipName(dealershipNameMap.get(deviceManagement.getDealershipId()));
                deviceManagement.setProjectName(projectNameMap.get(deviceManagement.getProjectId()));
                deviceManagement.setBindUserName(saleNameMap.get(deviceManagement.getBindUserId()));
            }

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", devicePage.getRecords());
            result.put("total", devicePage.getTotal());
            result.put("current", devicePage.getCurrent());
            result.put("size", devicePage.getSize());
            result.put("pages", devicePage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新设备信息
     */
    @PutMapping("/update")
    @Operation(summary = "更新设备信息", description = "更新设备详细信息")
    public ResponseEntity<Map<String, Object>> updateDevice(
            @Parameter(description = "设备信息", required = true)
            @RequestBody DeviceManagement deviceManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (deviceManagement.getId() == null || deviceManagement.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "设备ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            deviceManagement.setUpdateTime(LocalDateTime.now());
            boolean success = deviceManagementService.updateById(deviceManagement);
            
            if (success) {
                result.put("success", true);
                result.put("message", "设备信息更新成功");
                result.put("data", deviceManagement);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "设备信息更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID删除设备
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除设备", description = "根据设备ID删除设备信息")
    public ResponseEntity<Map<String, Object>> deleteDevice(
            @Parameter(description = "设备ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = deviceManagementService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "设备删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "设备删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量删除设备
     */
    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除设备", description = "根据设备ID列表批量删除设备信息")
    public ResponseEntity<Map<String, Object>> batchDeleteDevices(
            @Parameter(description = "设备ID列表", required = true)
            @RequestBody List<String> ids) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (ids == null || ids.isEmpty()) {
                result.put("success", false);
                result.put("message", "设备ID列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean success = deviceManagementService.removeByIds(ids);
            if (success) {
                result.put("success", true);
                result.put("message", "批量删除成功，共删除 " + ids.size() + " 条记录");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "批量删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取设备统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取设备统计信息", description = "获取设备总数等统计信息")
    public ResponseEntity<Map<String, Object>> getDeviceStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = deviceManagementService.count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalDevices", totalCount);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "统计信息获取异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
