package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.admin.dto.ShopQueryDTO;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.Shop;
import com.haha.entity.Device;
import com.haha.entity.ShopReplenisher;
import com.haha.entity.Admin;
import com.haha.service.ShopService;
import com.haha.service.DeviceService;
import com.haha.service.ShopReplenisherService;
import com.haha.service.AdminService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

/**
 * 门店管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/shops")
@RequiredArgsConstructor
public class ShopController {

    private final ShopService shopService;
    private final DeviceService deviceService;
    private final ShopReplenisherService shopReplenisherService;
    private final AdminService adminService;

    /**
     * 分页查询门店列表
     * @param queryDTO 查询参数
     * @return 门店列表
     */
    @RequirePermission("shop:read")
    @GetMapping("/list")
    public Result<PageResult<Shop>> list(ShopQueryDTO queryDTO) {
        queryDTO.validate();
        
        Map<String, Object> params = new HashMap<>();
        params.put("name", queryDTO.getName());
        params.put("city", queryDTO.getCity());
        params.put("status", queryDTO.getStatus());
        
        IPage<Shop> shopPage = shopService.getPage(queryDTO.getPage(), queryDTO.getPageSize(), params);

        return Result.success("查询成功", PageResult.of(shopPage));
    }

    /**
     * 获取门店详情
     * @param id 门店ID
     * @return 门店详情
     */
    @RequirePermission("shop:read")
    @GetMapping("/{id}")
    public Result<Shop> getById(@PathVariable Long id) {
        Shop shop = shopService.getShopWithStats(id);
        if (shop == null) {
            return Result.error(404, "门店不存在");
        }
        return Result.success("查询成功", shop);
    }

    /**
     * 获取门店统计数据
     * @return 统计数据
     */
    @RequirePermission("shop:read")
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        Map<String, Object> statistics = shopService.getStatistics();
        return Result.success("查询成功", statistics);
    }

    /**
     * 获取所有启用的门店（下拉选择用）
     * @return 门店列表
     */
    @GetMapping("/enabled")
    public Result<List<Map<String, Object>>> getEnabledShops() {
        List<Map<String, Object>> shops = shopService.getAllEnabledShops();
        return Result.success("查询成功", shops);
    }

    /**
     * 新增门店
     * @param shop 门店信息
     * @return 新增后的门店
     */
    @RequirePermission("shop:create")
    @Log(module = "门店管理", operation = OperationType.INSERT, summary = "新增门店")
    @PostMapping
    public Result<Shop> create(@RequestBody Shop shop) {
        Shop created = shopService.createShop(shop);
        return Result.success("创建成功", created);
    }

    /**
     * 编辑门店
     * @param id 门店ID
     * @param shop 门店信息
     * @return 编辑后的门店
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.UPDATE, summary = "编辑门店")
    @PutMapping("/{id}")
    public Result<Shop> update(@PathVariable Long id, @RequestBody Shop shop) {
        shop.setId(id);
        Shop updated = shopService.updateShop(shop);
        return Result.success("更新成功", updated);
    }

    /**
     * 删除门店
     * @param id 门店ID
     * @return 操作结果
     */
    @RequirePermission("shop:delete")
    @Log(module = "门店管理", operation = OperationType.DELETE, summary = "删除门店")
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        // 检查门店是否有设备
        Shop shop = shopService.getShopWithStats(id);
        if (shop == null) {
            return Result.error(404, "门店不存在");
        }
        
        if (shop.getDeviceCount() != null && shop.getDeviceCount() > 0) {
            return Result.error(400, "该门店下存在设备，无法删除");
        }
        
        shopService.removeById(id);
        return Result.success("删除成功");
    }

    /**
     * 切换门店状态
     * @param id 门店ID
     * @param params 状态参数
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.UPDATE, summary = "切换门店状态")
    @PutMapping("/{id}/status")
    public Result<String> toggleStatus(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        Integer status = Integer.valueOf(params.get("status").toString());
        boolean result = shopService.toggleStatus(id, status);
        
        if (result) {
            return Result.success("状态更新成功");
        } else {
            return Result.error(500, "状态更新失败");
        }
    }

    /**
     * 获取门店下的设备列表
     * @param id 门店ID
     * @return 设备列表
     */
    @RequirePermission("shop:read")
    @GetMapping("/{id}/devices")
    public Result<List<Map<String, Object>>> getDevices(@PathVariable Long id) {
        List<Map<String, Object>> devices = shopService.getDevicesByShopId(id);
        return Result.success("查询成功", devices);
    }

    /**
     * 将设备关联到门店
     * @param id 门店ID
     * @param params 设备ID参数
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.UPDATE, summary = "关联设备到门店")
    @PostMapping("/{id}/devices")
    public Result<String> linkDevice(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        Long deviceId = Long.valueOf(params.get("deviceId").toString());
        boolean result = shopService.linkDevice(id, deviceId);
        if (result) {
            return Result.success("关联成功");
        } else {
            return Result.error(500, "关联失败");
        }
    }

    /**
     * 批量将设备关联到门店
     * @param id 门店ID
     * @param params 设备ID列表参数
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.UPDATE, summary = "批量关联设备到门店")
    @PostMapping("/{id}/devices/batch")
    public Result<Map<String, Object>> batchLinkDevices(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Integer> deviceIdInts = (List<Integer>) params.get("deviceIds");
        List<Long> deviceIds = deviceIdInts.stream()
                .map(Integer::longValue)
                .toList();
        
        int count = shopService.batchLinkDevices(id, deviceIds);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", count);
        result.put("total", deviceIds.size());
        
        return Result.success("批量关联完成", result);
    }

    /**
     * 从门店移除设备关联
     * @param id 门店ID
     * @param deviceId 设备ID
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.UPDATE, summary = "移除门店设备关联")
    @DeleteMapping("/{id}/devices/{deviceId}")
    public Result<String> unlinkDevice(@PathVariable Long id, @PathVariable Long deviceId) {
        boolean result = shopService.unlinkDevice(id, deviceId);
        if (result) {
            return Result.success("移除成功");
        } else {
            return Result.error(500, "移除失败");
        }
    }

    /**
     * 批量移除设备关联
     * @param id 门店ID
     * @param params 设备ID列表参数
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.UPDATE, summary = "批量移除设备关联")
    @DeleteMapping("/{id}/devices/batch")
    public Result<Map<String, Object>> batchUnlinkDevices(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Integer> deviceIdInts = (List<Integer>) params.get("deviceIds");
        List<Long> deviceIds = deviceIdInts.stream()
                .map(Integer::longValue)
                .toList();
        
        int count = shopService.batchUnlinkDevices(id, deviceIds);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", count);
        result.put("total", deviceIds.size());
        
        return Result.success("批量移除完成", result);
    }

    /**
     * 获取未关联门店的设备列表
     * @return 设备列表
     */
    @RequirePermission("shop:read")
    @GetMapping("/unlinked-devices")
    public Result<List<Device>> getUnlinkedDevices() {
        List<Device> devices = deviceService.getUnlinkedDevices();
        return Result.success("查询成功", devices);
    }

    // ==================== 补货员管理 ====================

    /**
     * 获取门店补货员列表
     * @param id 门店ID
     * @return 补货员列表
     */
    @RequirePermission("shop:read")
    @GetMapping("/{id}/replenishers")
    public Result<List<ShopReplenisher>> getReplenishers(@PathVariable Long id) {
        List<ShopReplenisher> replenishers = shopReplenisherService.getReplenishersByShopId(id);
        return Result.success("查询成功", replenishers);
    }

    /**
     * 添加补货员
     * @param id 门店ID
     * @param params 管理员ID参数
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.INSERT, summary = "添加门店补货员")
    @PostMapping("/{id}/replenishers")
    public Result<Void> addReplenisher(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        Long adminId = Long.valueOf(params.get("adminId").toString());
        return shopReplenisherService.addReplenisher(id, adminId);
    }

    /**
     * 批量添加补货员
     * @param id 门店ID
     * @param params 管理员ID列表参数
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.INSERT, summary = "批量添加门店补货员")
    @PostMapping("/{id}/replenishers/batch")
    public Result<Map<String, Object>> batchAddReplenishers(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Integer> adminIdInts = (List<Integer>) params.get("adminIds");
        List<Long> adminIds = adminIdInts.stream()
                .map(Integer::longValue)
                .toList();

        int count = shopReplenisherService.batchAddReplenishers(id, adminIds);

        Map<String, Object> result = new HashMap<>();
        result.put("success", count);
        result.put("total", adminIds.size());

        return Result.success("批量添加完成", result);
    }

    /**
     * 移除补货员
     * @param id 门店ID
     * @param adminId 管理员ID
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.DELETE, summary = "移除门店补货员")
    @DeleteMapping("/{id}/replenishers/{adminId}")
    public Result<Void> removeReplenisher(@PathVariable Long id, @PathVariable Long adminId) {
        return shopReplenisherService.removeReplenisher(id, adminId);
    }

    /**
     * 批量移除补货员
     * @param id 门店ID
     * @param params 管理员ID列表参数
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.DELETE, summary = "批量移除门店补货员")
    @DeleteMapping("/{id}/replenishers/batch")
    public Result<Map<String, Object>> batchRemoveReplenishers(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Integer> adminIdInts = (List<Integer>) params.get("adminIds");
        List<Long> adminIds = adminIdInts.stream()
                .map(Integer::longValue)
                .toList();

        int count = shopReplenisherService.batchRemoveReplenishers(id, adminIds);

        Map<String, Object> result = new HashMap<>();
        result.put("success", count);
        result.put("total", adminIds.size());

        return Result.success("批量移除完成", result);
    }

    /**
     * 更新补货员状态
     * @param id 补货员关联ID
     * @param params 状态参数
     * @return 操作结果
     */
    @RequirePermission("shop:update")
    @Log(module = "门店管理", operation = OperationType.UPDATE, summary = "更新补货员状态")
    @PutMapping("/replenishers/{id}/status")
    public Result<Void> updateReplenisherStatus(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        Integer status = Integer.valueOf(params.get("status").toString());
        return shopReplenisherService.updateStatus(id, status);
    }

    /**
     * 获取可选的管理员列表（用于添加补货员）
     * @return 管理员列表
     */
    @RequirePermission("shop:read")
    @GetMapping("/available-users")
    public Result<List<Admin>> getAvailableUsers(@RequestParam(required = false) String keyword) {
        List<Admin> admins = adminService.getAvailableAdmins(keyword);
        return Result.success("查询成功", admins);
    }
}
