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.Result;
import com.haha.entity.DeviceInventory;
import com.haha.entity.InventoryLog;
import com.haha.entity.StockRecord;
import com.haha.service.DeviceInventoryService;
import com.haha.service.InventoryLogService;
import com.haha.service.StockRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

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

    @Autowired
    private DeviceInventoryService deviceInventoryService;

    @Autowired
    private InventoryLogService inventoryLogService;

    @Autowired
    private StockRecordService stockRecordService;

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

    /**
     * 分页查询设备库存统计列表
     * 按设备分组展示库存汇总信息
     */
    @RequirePermission("inventory:read")
    @GetMapping("/device-stats")
    public Result<Map<String, Object>> deviceStats(@RequestParam Map<String, Object> params) {
        int page = 1;
        int pageSize = 10;

        Object pageObj = params.get("page");
        if (pageObj != null && !pageObj.toString().isEmpty()) {
            page = Integer.parseInt(pageObj.toString());
        }
        Object pageSizeObj = params.get("pageSize");
        if (pageSizeObj != null && !pageSizeObj.toString().isEmpty()) {
            pageSize = Integer.parseInt(pageSizeObj.toString());
        }

        IPage<Map<String, Object>> pageResult = deviceInventoryService.getDeviceInventoryStats(page, pageSize, params);

        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("page", page);
        result.put("pageSize", pageSize);

        return Result.success(result);
    }

    /**
     * 分页查询库存列表
     */
    @RequirePermission("inventory:read")
    @GetMapping("/list")
    public Result<Map<String, Object>> list(@RequestParam Map<String, Object> params) {
        int page = 1;
        int pageSize = 10;

        Object pageObj = params.get("page");
        if (pageObj != null && !pageObj.toString().isEmpty()) {
            page = Integer.parseInt(pageObj.toString());
        }
        Object pageSizeObj = params.get("pageSize");
        if (pageSizeObj != null && !pageSizeObj.toString().isEmpty()) {
            pageSize = Integer.parseInt(pageSizeObj.toString());
        }

        // 处理低库存筛选参数
        if ("true".equals(params.get("lowStock"))) {
            params.put("lowStock", true);
        }

        IPage<DeviceInventory> pageResult = deviceInventoryService.getPage(page, pageSize, params);

        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("page", page);
        result.put("pageSize", pageSize);

        return Result.success(result);
    }

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

    /**
     * 查询低库存商品
     */
    @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<Map<String, Object>> getStatistics() {
        Map<String, Object> stats = deviceInventoryService.getStatistics();
        return Result.success(stats);
    }

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

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

            String deviceId = (String) params.get("deviceId");
            Long productId = Long.parseLong(params.get("productId").toString());
            String productCode = (String) params.get("productCode");
            String productName = (String) params.get("productName");
            Integer quantity = Integer.parseInt(params.get("quantity").toString());
            Integer shelfNum = params.get("shelfNum") != null ? 
                    Integer.parseInt(params.get("shelfNum").toString()) : null;
            String position = (String) params.get("position");
            String activityId = (String) params.get("activityId");

            DeviceInventory inventory = deviceInventoryService.increaseStock(
                    deviceId, productId, productCode, productName,
                    quantity, shelfNum, position,
                    userId, userName, activityId);

            return Result.success("库存增加成功", inventory);
        } catch (Exception e) {
            log.error("增加库存失败", e);
            return Result.error(e.getMessage());
        }
    }

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

            String deviceId = (String) params.get("deviceId");
            Long productId = Long.parseLong(params.get("productId").toString());
            Integer newStock = Integer.parseInt(params.get("newStock").toString());
            String remark = (String) params.get("remark");

            DeviceInventory inventory = deviceInventoryService.adjustStock(
                    deviceId, productId, newStock, remark, userId, userName);

            return Result.success("库存调整成功", inventory);
        } catch (Exception e) {
            log.error("调整库存失败", e);
            return Result.error(e.getMessage());
        }
    }

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

    /**
     * 分页查询库存变动日志
     */
    @RequirePermission("inventory:read")
    @GetMapping("/logs")
    public Result<Map<String, Object>> getLogList(@RequestParam Map<String, Object> params) {
        int page = 1;
        int pageSize = 10;

        Object pageObj = params.get("page");
        if (pageObj != null && !pageObj.toString().isEmpty()) {
            page = Integer.parseInt(pageObj.toString());
        }
        Object pageSizeObj = params.get("pageSize");
        if (pageSizeObj != null && !pageSizeObj.toString().isEmpty()) {
            pageSize = Integer.parseInt(pageSizeObj.toString());
        }

        IPage<InventoryLog> pageResult = inventoryLogService.getPage(page, pageSize, params);

        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("page", page);
        result.put("pageSize", pageSize);

        return Result.success(result);
    }

    /**
     * 查询设备库存变动统计
     */
    @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<Map<String, Object>> getRecordList(@RequestParam Map<String, Object> params) {
        int page = 1;
        int pageSize = 10;

        Object pageObj = params.get("page");
        if (pageObj != null && !pageObj.toString().isEmpty()) {
            page = Integer.parseInt(pageObj.toString());
        }
        Object pageSizeObj = params.get("pageSize");
        if (pageSizeObj != null && !pageSizeObj.toString().isEmpty()) {
            pageSize = Integer.parseInt(pageSizeObj.toString());
        }

        IPage<StockRecord> pageResult = stockRecordService.getPage(page, pageSize, params);

        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("page", page);
        result.put("pageSize", pageSize);

        return Result.success(result);
    }

    /**
     * 获取上货记录详情
     */
    @RequirePermission("inventory:read")
    @GetMapping("/records/{id}")
    public Result<Map<String, Object>> getRecordDetail(@PathVariable Long id) {
        Map<String, Object> detail = stockRecordService.getDetailWithDeviceName(id);
        return Result.success(detail);
    }

    /**
     * 创建上货记录
     */
    @RequirePermission("inventory:create")
    @PostMapping("/records")
    public Result<StockRecord> createRecord(@RequestBody Map<String, Object> params) {
        try {
            String deviceId = (String) params.get("deviceId");
            Integer stockType = params.get("stockType") != null ?
                    Integer.parseInt(params.get("stockType").toString()) : 1;
            String remark = (String) params.get("remark");

            // 获取当前用户作为上货员
            Long stockerId = StpUtil.getLoginIdAsLong();
            String stockerName = StpUtil.getLoginIdAsString();
            String stockerPhone = (String) params.get("stockerPhone");

            StockRecord record = stockRecordService.createRecord(
                    deviceId, stockType, stockerId, stockerName, stockerPhone, remark);

            return Result.success("上货记录创建成功", record);
        } catch (Exception e) {
            log.error("创建上货记录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 完成上货记录
     */
    @RequirePermission("inventory:update")
    @PutMapping("/records/{id}/complete")
    public Result<String> completeRecord(
            @PathVariable Long id,
            @RequestBody Map<String, Object> params) {
        try {
            Integer totalItems = params.get("totalItems") != null ?
                    Integer.parseInt(params.get("totalItems").toString()) : 0;
            Integer totalQuantity = params.get("totalQuantity") != null ?
                    Integer.parseInt(params.get("totalQuantity").toString()) : 0;
            String activityId = (String) params.get("activityId");

            stockRecordService.completeActivity(id, totalItems, totalQuantity, activityId);
            return Result.success("上货记录已完成");
        } catch (Exception e) {
            log.error("完成上货记录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 取消上货记录
     */
    @RequirePermission("inventory:update")
    @PutMapping("/records/{id}/cancel")
    public Result<String> cancelRecord(@PathVariable Long id) {
        try {
            stockRecordService.cancelActivity(id);
            return Result.success("上货记录已取消");
        } catch (Exception e) {
            log.error("取消上货记录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取上货员工作统计
     */
    @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);
    }
}
