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.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.ReplenishmentOrder;
import com.haha.entity.ReplenishmentOrderItem;
import com.haha.entity.dto.ReplenishmentOrderCreateDTO;
import com.haha.entity.dto.ReplenishmentOrderQueryDTO;
import com.haha.entity.dto.ReplenishmentOrderUpdateDTO;
import com.haha.entity.dto.ReplenishmentSuggestionVO;
import com.haha.service.ReplenishmentOrderService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备补货单管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/replenishment-orders")
@RequiredArgsConstructor
public class ReplenishmentOrderController {

    private final ReplenishmentOrderService orderService;

    /**
     * 分页查询补货单列表
     */
    @RequirePermission("replenishment:order:read")
    @GetMapping("/list")
    public Result<PageResult<ReplenishmentOrder>> list(ReplenishmentOrderQueryDTO queryDTO) {
        IPage<ReplenishmentOrder> page = orderService.getPage(queryDTO);
        return Result.success("查询成功", PageResult.of(page));
    }

    /**
     * 获取补货单详情（含明细）
     */
    @RequirePermission("replenishment:order:read")
    @GetMapping("/{id}")
    public Result<ReplenishmentOrder> getById(@PathVariable Long id) {
        ReplenishmentOrder order = orderService.getDetailWithItems(id);
        List<ReplenishmentOrderItem> items = orderService.getItems(id);
        order.setItemCount(items != null ? items.size() : 0);
        return Result.success("查询成功", order);
    }

    /**
     * 获取补货单明细列表
     */
    @RequirePermission("replenishment:order:read")
    @GetMapping("/{id}/items")
    public Result<List<ReplenishmentOrderItem>> getItems(@PathVariable Long id) {
        List<ReplenishmentOrderItem> items = orderService.getItems(id);
        return Result.success("查询成功", items);
    }

    /**
     * 创建补货单
     */
    @RequirePermission("replenishment:order:create")
    @Log(module = "补货单管理", operation = OperationType.INSERT, summary = "创建补货单")
    @PostMapping
    public Result<ReplenishmentOrder> create(@Valid @RequestBody ReplenishmentOrderCreateDTO dto) {
        Long creatorId = getCurrentUserId();
        String creatorName = getCurrentUserName();
        ReplenishmentOrder order = orderService.createOrder(dto, creatorId, creatorName);
        return Result.success("创建成功", order);
    }

    /**
     * 更新补货单
     */
    @RequirePermission("replenishment:order:update")
    @Log(module = "补货单管理", operation = OperationType.UPDATE, summary = "更新补货单")
    @PutMapping
    public Result<ReplenishmentOrder> update(@Valid @RequestBody ReplenishmentOrderUpdateDTO dto) {
        ReplenishmentOrder order = orderService.updateOrder(dto);
        return Result.success("更新成功", order);
    }

    /**
     * 删除补货单
     */
    @RequirePermission("replenishment:order:delete")
    @Log(module = "补货单管理", operation = OperationType.DELETE, summary = "删除补货单")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        orderService.deleteOrder(id);
        return Result.success("删除成功");
    }

    /**
     * 提交补货单
     */
    @RequirePermission("replenishment:order:submit")
    @Log(module = "补货单管理", operation = OperationType.UPDATE, summary = "提交补货单")
    @PostMapping("/{id}/submit")
    public Result<ReplenishmentOrder> submit(@PathVariable Long id) {
        ReplenishmentOrder order = orderService.submitOrder(id);
        return Result.success("提交成功", order);
    }

    /**
     * 同步到ERP
     */
    @RequirePermission("replenishment:order:sync")
    @Log(module = "补货单管理", operation = OperationType.OTHER, summary = "同步补货单到ERP")
    @PostMapping("/{id}/sync-erp")
    public Result<ReplenishmentOrder> syncToErp(@PathVariable Long id) {
        ReplenishmentOrder order = orderService.syncToErp(id);
        return Result.success("同步ERP成功", order);
    }

    /**
     * 完成补货单
     */
    @RequirePermission("replenishment:order:complete")
    @Log(module = "补货单管理", operation = OperationType.UPDATE, summary = "完成补货单")
    @PostMapping("/{id}/complete")
    public Result<ReplenishmentOrder> complete(@PathVariable Long id) {
        ReplenishmentOrder order = orderService.completeOrder(id);
        return Result.success("完成补货单", order);
    }

    /**
     * 取消补货单
     */
    @RequirePermission("replenishment:order:update")
    @Log(module = "补货单管理", operation = OperationType.UPDATE, summary = "取消补货单")
    @PostMapping("/{id}/cancel")
    public Result<ReplenishmentOrder> cancel(@PathVariable Long id) {
        ReplenishmentOrder order = orderService.cancelOrder(id);
        return Result.success("取消成功", order);
    }

    /**
     * 获取补货建议
     * 根据设备ID批量计算：层模版标准库存 - 当前实际库存
     */
    @RequirePermission("replenishment:order:read")
    @GetMapping("/suggestions")
    public Result<List<ReplenishmentSuggestionVO>> getSuggestions(
            @RequestParam("deviceIds") String deviceIds) {
        List<String> ids = Arrays.stream(deviceIds.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
        if (ids.isEmpty()) {
            return Result.success("查询成功", Collections.emptyList());
        }
        List<ReplenishmentSuggestionVO> suggestions = orderService.getSuggestions(ids);
        return Result.success("查询成功", suggestions);
    }

    private Long getCurrentUserId() {
        try {
            return cn.dev33.satoken.stp.StpUtil.getLoginIdAsLong();
        } catch (Exception e) {
            return 1L;
        }
    }

    private String getCurrentUserName() {
        try {
            Object name = cn.dev33.satoken.stp.StpUtil.getSession().get("nickname");
            if (name != null) {
                return name.toString();
            }
            return cn.dev33.satoken.stp.StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return "系统";
        }
    }
}
