package com.haha.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
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.InventoryStatisticsVO;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.DeviceInventory;
import com.haha.entity.InventoryLog;
import com.haha.entity.StockRecord;
import com.haha.entity.StockRecordItem;
import com.haha.entity.dto.*;
import com.haha.mapper.StockRecordItemMapper;
import com.haha.service.AdminService;
import com.haha.service.DeviceInventoryService;
import com.haha.service.InventoryLogService;
import com.haha.service.StockRecordService;
import lombok.RequiredArgsConstructor;
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;

/**
 * 库存管理控制器
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/inventory")
public class InventoryController {

    private final DeviceInventoryService deviceInventoryService;

    private final InventoryLogService inventoryLogService;

    private final StockRecordService stockRecordService;

    private final StockRecordItemMapper stockRecordItemMapper;

    private final AdminService adminService;

    // ==================== 库存查询 ====================

    /**
     * 分页查询设备库存统计列表
     * 按设备分组展示库存汇总信息
     */
    @RequirePermission("inventory:read")
    @GetMapping("/device-stats")
    public Result<PageResult<Map<String, Object>>> deviceStats(InventoryQueryDTO queryDTO) {
        queryDTO.validate();
        IPage<Map<String, Object>> pageResult = deviceInventoryService.getDeviceInventoryStats(
                queryDTO.getPage(), queryDTO.getPageSize(), queryDTO);
        return Result.success(PageResult.of(pageResult));
    }

    /**
     * 分页查询库存列表
     */
    @RequirePermission("inventory:read")
    @GetMapping("/list")
    public Result<PageResult<DeviceInventory>> list(InventoryQueryDTO queryDTO) {
        queryDTO.validate();
        IPage<DeviceInventory> pageResult = deviceInventoryService.getPage(
                queryDTO.getPage(), queryDTO.getPageSize(), queryDTO);
        return Result.success(PageResult.of(pageResult));
    }

    /**
     * 查询设备库存详情
     */
    @RequirePermission("inventory:read")
    @GetMapping("/device/{deviceId}")
    public Result<List<Map<String, Object>>> getDeviceInventory(@PathVariable String deviceId) {
        List<Map<String, Object>> inventory = deviceInventoryService.getInventoryWithProduct(deviceId);
        return Result.success(inventory);
    }

    /**
     * 查询低库存商品
     */
    @RequirePermission("inventory:read")
    @GetMapping("/low-stock")
    public Result<List<Map<String, Object>>> getLowStock() {
        List<Map<String, Object>> lowStockList = deviceInventoryService.getLowStockList();
        return Result.success(lowStockList);
    }

    /**
     * 获取库存统计
     */
    @RequirePermission("inventory:read")
    @GetMapping("/statistics")
    public Result<InventoryStatisticsVO> getStatistics() {
        Map<String, Object> stats = deviceInventoryService.getStatistics();
        InventoryStatisticsVO vo = new InventoryStatisticsVO();
        vo.setTotalRecords((Long) stats.get("totalRecords"));
        vo.setTotalStock((Integer) stats.get("totalStock"));
        vo.setLowStockCount((Long) stats.get("lowStockCount"));
        vo.setZeroStockCount((Long) stats.get("zeroStockCount"));
        return Result.success(vo);
    }

    // ==================== 库存操作 ====================

    /**
     * 增加库存（上货）
     */
    @RequirePermission("inventory:update")
    @Log(module = "库存管理", operation = OperationType.INSERT, summary = "上货增加库存")
    @PostMapping("/increase")
    public Result<DeviceInventory> increaseStock(@RequestBody @Validated StockIncreaseDTO dto) {
        Long userId = StpUtil.getLoginIdAsLong();
        String userName = getCurrentOperatorName();

        DeviceInventory inventory = deviceInventoryService.increaseStock(
                dto.getDeviceId(), dto.getProductId(), dto.getProductCode(), dto.getProductName(),
                dto.getQuantity(), dto.getShelfNum(), dto.getPosition(),
                userId, userName, dto.getActivityId());

        return Result.success("库存增加成功", inventory);
    }

    /**
     * 调整库存
     */
    @RequirePermission("inventory:update")
    @Log(module = "库存管理", operation = OperationType.UPDATE, summary = "调整库存")
    @PostMapping("/adjust")
    public Result<DeviceInventory> adjustStock(@RequestBody @Validated StockAdjustDTO dto) {
        Long userId = StpUtil.getLoginIdAsLong();
        String userName = getCurrentOperatorName();

        DeviceInventory inventory = deviceInventoryService.adjustStock(
                dto.getDeviceId(), dto.getProductId(), dto.getNewStock(),
                dto.getRemark(), userId, userName);

        return Result.success("库存调整成功", inventory);
    }

    // ==================== 库存变动日志 ====================

    /**
     * 分页查询库存变动日志
     */
    @RequirePermission("inventory:read")
    @GetMapping("/logs")
    public Result<PageResult<InventoryLog>> getLogList(InventoryLogQueryDTO queryDTO) {
        queryDTO.validate();
        IPage<InventoryLog> pageResult = inventoryLogService.getPage(
                queryDTO.getPage(), queryDTO.getPageSize(), queryDTO);
        return Result.success(PageResult.of(pageResult));
    }

    /**
     * 查询设备库存变动统计
     */
    @RequirePermission("inventory:read")
    @GetMapping("/logs/statistics")
    public Result<List<Map<String, Object>>> getLogStatistics(
            @RequestParam String deviceId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        List<Map<String, Object>> stats = inventoryLogService.getChangeStatistics(deviceId, startTime, endTime);
        return Result.success(stats);
    }

    // ==================== 上货记录 ====================

    /**
     * 分页查询上货记录
     */
    @RequirePermission("inventory:read")
    @GetMapping("/records")
    public Result<PageResult<StockRecord>> getRecordList(StockRecordQueryDTO queryDTO) {
        queryDTO.validate();
        IPage<StockRecord> pageResult = stockRecordService.getPage(
                queryDTO.getPage(), queryDTO.getPageSize(), queryDTO);
        return Result.success(PageResult.of(pageResult));
    }

    /**
     * 获取上货记录详情
     */
    @RequirePermission("inventory:read")
    @GetMapping("/records/{id}")
    public Result<Map<String, Object>> getRecordDetail(@PathVariable Long id) {
        Map<String, Object> detail = stockRecordService.getDetailWithDeviceName(id);
        List<StockRecordItem> items = stockRecordItemMapper.selectByRecordId(id);
        detail.put("items", items != null ? items : java.util.Collections.emptyList());
        return Result.success(detail);
    }

    /**
     * 创建上货记录（使用独立补货员体系）
     */
    @RequirePermission("inventory:create")
    @Log(module = "库存管理", operation = OperationType.INSERT, summary = "V2创建上货记录")
    @PostMapping("/records/v2")
    public Result<StockRecord> createRecordV2(@RequestBody @Validated StockRecordCreateV2DTO dto) {
        StockRecord record = stockRecordService.createRecordV2(
                dto.getDeviceId(), dto.getStockType(), dto.getReplenisherId(),
                dto.getReplenisherName(), dto.getReplenisherPhone(), dto.getRemark());

        return Result.success("上货记录创建成功", record);
    }

    /**
     * 完成上货记录
     */
    @RequirePermission("inventory:update")
    @PutMapping("/records/{id}/complete")
    public Result<String> completeRecord(
            @PathVariable Long id,
            @RequestBody StockRecordCompleteDTO dto) {
        stockRecordService.completeActivity(id, dto.getTotalItems(), dto.getTotalQuantity(), dto.getActivityId());
        return Result.success("上货记录已完成");
    }

    /**
     * 取消上货记录
     */
    @RequirePermission("inventory:update")
    @PutMapping("/records/{id}/cancel")
    public Result<String> cancelRecord(@PathVariable Long id) {
        stockRecordService.cancelActivity(id);
        return Result.success("上货记录已取消");
    }

    /**
     * 获取上货员工作统计
     */
    @RequirePermission("inventory:read")
    @GetMapping("/records/stocker-statistics")
    public Result<Map<String, Object>> getStockerStatistics(
            @RequestParam Long stockerId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        Map<String, Object> stats = stockRecordService.getStockerStatistics(stockerId, startTime, endTime);
        return Result.success(stats);
    }

    /**
     * 获取当前操作人名称
     * 优先从Session获取昵称，fallback到loginId字符串
     */
    private String getCurrentOperatorName() {
        String operatorName = StpUtil.getLoginIdAsString();
        try {
            Object nickname = StpUtil.getSession().get("nickname");
            if (nickname != null) {
                operatorName = nickname.toString();
            }
        } catch (Exception e) {
            log.debug("获取用户昵称失败，使用默认值");
        }
        return operatorName;
    }
}
