package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.BatchResultVO;
import com.haha.common.vo.BindingCodeVO;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.Replenisher;
import com.haha.entity.dto.*;
import com.haha.service.ReplenisherService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 补货员管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/replenishers")
@RequiredArgsConstructor
public class ReplenisherController {

    private final ReplenisherService replenisherService;

    /**
     * 分页查询补货员列表
     *
     * @param queryDTO 查询参数（支持关键词模糊搜索和状态筛选）
     * @return 补货员分页列表
     */
    @RequirePermission("replenisher:read")
    @GetMapping("/list")
    public Result<PageResult<Replenisher>> list(ReplenisherQueryDTO queryDTO) {
        IPage<Replenisher> page = replenisherService.getPage(queryDTO);
        return Result.success("查询成功", PageResult.of(page));
    }

    /**
     * 获取补货员详情（含绑定设备数）
     *
     * @param id 补货员ID
     * @return 补货员详情
     */
    @RequirePermission("replenisher:read")
    @GetMapping("/{id}")
    public Result<Replenisher> getById(@PathVariable Long id) {
        Replenisher replenisher = replenisherService.getReplenisherDetail(id);
        if (replenisher == null) {
            return Result.error(404, "补货员不存在");
        }
        return Result.success("查询成功", replenisher);
    }

    /**
     * 关键词搜索启用的补货员（用于下拉选择）
     *
     * @param keyword 搜索关键词（可选，搜索姓名/手机号/工号）
     * @return 启用的补货员列表
     */
    @RequirePermission("replenisher:read")
    @GetMapping("/search")
    public Result<List<Replenisher>> search(@RequestParam(required = false) String keyword) {
        List<Replenisher> list = replenisherService.searchByKeyword(keyword);
        return Result.success("查询成功", list);
    }

    /**
     * 创建补货员
     *
     * @param dto 创建参数
     * @return 创建的补货员
     */
    @RequirePermission("replenisher:create")
    @Log(module = "补货员管理", operation = OperationType.INSERT, summary = "创建补货员")
    @PostMapping
    public Result<Replenisher> create(@RequestBody ReplenisherCreateDTO dto) {
        Replenisher replenisher = replenisherService.createReplenisher(dto);
        return Result.success("创建成功", replenisher);
    }

    /**
     * 更新补货员信息
     *
     * @param id  补货员ID
     * @param dto 更新参数
     * @return 更新后的补货员
     */
    @RequirePermission("replenisher:update")
    @Log(module = "补货员管理", operation = OperationType.UPDATE, summary = "更新补货员")
    @PutMapping("/{id}")
    public Result<Replenisher> update(@PathVariable Long id, @RequestBody ReplenisherUpdateDTO dto) {
        Replenisher replenisher = replenisherService.updateReplenisher(id, dto);
        return Result.success("更新成功", replenisher);
    }

    /**
     * 启用/禁用补货员
     *
     * @param id  补货员ID
     * @param dto 状态参数
     * @return 操作结果
     */
    @RequirePermission("replenisher:update")
    @Log(module = "补货员管理", operation = OperationType.UPDATE, summary = "更新补货员状态")
    @PutMapping("/{id}/status")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestBody StatusDTO dto) {
        replenisherService.updateStatus(id, dto.getStatus());
        return Result.success("状态更新成功");
    }

    /**
     * 删除补货员（级联解绑所有设备）
     *
     * @param id 补货员ID
     * @return 操作结果
     */
    @RequirePermission("replenisher:delete")
    @Log(module = "补货员管理", operation = OperationType.DELETE, summary = "删除补货员")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        replenisherService.deleteReplenisher(id);
        return Result.success("删除成功");
    }

    /**
     * 获取补货员已绑定的设备ID列表
     *
     * @param id 补货员ID
     * @return 设备SN号列表
     */
    @RequirePermission("replenisher:read")
    @GetMapping("/{id}/devices")
    public Result<List<String>> getBoundDevices(@PathVariable Long id) {
        List<String> deviceIds = replenisherService.getBoundDeviceIds(id);
        return Result.success("查询成功", deviceIds);
    }

    /**
     * 绑定设备到补货员
     *
     * @param id  补货员ID
     * @param dto 设备ID列表
     * @return 绑定结果
     */
    @RequirePermission("replenisher:update")
    @Log(module = "补货员管理", operation = OperationType.UPDATE, summary = "绑定设备到补货员")
    @PostMapping("/{id}/devices")
    public Result<BatchResultVO> bindDevices(@PathVariable Long id, @RequestBody BindDeviceDTO dto) {
        int count = replenisherService.bindDevices(id, dto.getDeviceIds());
        BatchResultVO result = BatchResultVO.builder()
                .success(count)
                .total(dto.getDeviceIds().size())
                .build();
        return Result.success("绑定完成", result);
    }

    /**
     * 解绑补货员的某个设备
     *
     * @param id       补货员ID
     * @param deviceId 设备SN号
     * @return 操作结果
     */
    @RequirePermission("replenisher:update")
    @Log(module = "补货员管理", operation = OperationType.UPDATE, summary = "解绑补货员设备")
    @DeleteMapping("/{id}/devices/{deviceId}")
    public Result<Void> unbindDevice(@PathVariable Long id, @PathVariable String deviceId) {
        replenisherService.unbindDevice(id, deviceId);
        return Result.success("解绑成功");
    }

    /**
     * 批量绑定（多补货员到多设备）
     *
     * @param dto 补货员ID列表和设备ID列表
     * @return 绑定结果
     */
    @RequirePermission("replenisher:update")
    @Log(module = "补货员管理", operation = OperationType.UPDATE, summary = "批量绑定补货员到设备")
    @PostMapping("/batch-bind")
    public Result<BatchResultVO> batchBind(@RequestBody BatchBindDevicesDTO dto) {
        int count = replenisherService.batchBindDevices(dto.getReplenisherIds(), dto.getDeviceIds());
        int total = dto.getReplenisherIds().size() * dto.getDeviceIds().size();
        BatchResultVO result = BatchResultVO.builder()
                .success(count)
                .total(total)
                .build();
        return Result.success("批量绑定完成", result);
    }

    /**
     * 生成补货员绑定码
     * 用于补货员扫码绑定微信
     *
     * @param id 补货员ID
     * @return 绑定码
     */
    @RequirePermission("replenisher:update")
    @Log(module = "补货员管理", operation = OperationType.OTHER, summary = "生成补货员绑定码")
    @PostMapping("/{id}/binding-code")
    public Result<BindingCodeVO> generateBindingCode(@PathVariable Long id) {
        String bindingCode = replenisherService.generateBindingCode(id);
        BindingCodeVO result = BindingCodeVO.builder()
                .bindingCode(bindingCode)
                .replenisherId(id.toString())
                .build();
        return Result.success("生成绑定码成功", result);
    }
}
