package com.ruoyi.web.stock.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.stock.domain.WarehouseInventory;
import com.ruoyi.web.stock.service.IRoleOrgService;
import com.ruoyi.web.stock.service.IWarehouseInventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 仓库库存控制器。
 */
@RestController
@RequestMapping("/stock/inventory")
public class WarehouseInventoryController extends BaseController {

    @Autowired
    private IWarehouseInventoryService warehouseInventoryService;
    @Autowired
    private IRoleOrgService roleOrgService;

    @PreAuthorize("@ss.hasPermi('erp:stock:inventory:list')")
    @GetMapping("/list")
    public TableDataInfo list(WarehouseInventory query) {
        query.setOrgId(currentOrgId());
        startPage();
        List<WarehouseInventory> list = warehouseInventoryService.selectList(query);
        return getDataTable(list);
    }

    /**
     * 获取指定仓库内的全部库存（当前企业、仓库编号精确匹配，不分页）。
     */
    @PreAuthorize("@ss.hasPermi('erp:stock:inventory:list')")
    @GetMapping("/warehouse/{warehouseNo}")
    public AjaxResult listByWarehouse(@PathVariable("warehouseNo") String warehouseNo) {
        if (warehouseNo == null || warehouseNo.trim().isEmpty()) {
            return error("仓库编号不能为空");
        }
        List<WarehouseInventory> list = warehouseInventoryService.listByWarehouseNo(
                currentOrgId(), warehouseNo.trim());
        return success(list);
    }

    @PreAuthorize("@ss.hasPermi('erp:stock:inventory:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        WarehouseInventory entity = warehouseInventoryService.selectById(id);
        if (entity == null || !currentOrgId().equals(entity.getOrgId())) {
            return error("无权访问该数据");
        }
        return success(entity);
    }

    @PreAuthorize("@ss.hasPermi('erp:stock:inventory:add')")
    @Log(title = "仓库库存", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WarehouseInventory entity) {
        entity.setOrgId(currentOrgId());
        if (entity.getBatchNo() == null || entity.getBatchNo().trim().isEmpty()) {
            return error("新增失败，批次号不能为空");
        }
        if (!warehouseInventoryService.checkBatchNoUnique(entity, currentOrgId())) {
            return error("新增失败，批次号已存在");
        }
        entity.setCreateBy(getUsername());
        entity.setUpdateBy(getUsername());
        return toAjax(warehouseInventoryService.insert(entity));
    }

    @PreAuthorize("@ss.hasPermi('erp:stock:inventory:edit')")
    @Log(title = "仓库库存", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WarehouseInventory entity) {
        WarehouseInventory old = warehouseInventoryService.selectById(entity.getId());
        if (old == null || !currentOrgId().equals(old.getOrgId())) {
            return error("无权修改该数据");
        }
        entity.setOrgId(currentOrgId());
        if (entity.getBatchNo() == null || entity.getBatchNo().trim().isEmpty()) {
            return error("修改失败，批次号不能为空");
        }
        if (!warehouseInventoryService.checkBatchNoUnique(entity, currentOrgId())) {
            return error("修改失败，批次号已存在");
        }
        entity.setUpdateBy(getUsername());
        return toAjax(warehouseInventoryService.update(entity));
    }

    @PreAuthorize("@ss.hasPermi('erp:stock:inventory:remove')")
    @Log(title = "仓库库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable("ids") String ids) {
        int rows = 0;
        for (Long id : Convert.toLongArray(ids)) {
            WarehouseInventory old = warehouseInventoryService.selectById(id);
            if (old == null || !currentOrgId().equals(old.getOrgId())) {
                continue;
            }
            rows += warehouseInventoryService.removeById(id);
        }
        return toAjax(rows);
    }

    @PreAuthorize("@ss.hasPermi('erp:stock:inventory:query')")
    @GetMapping("/materials/options")
    public AjaxResult materialOptions() {
        return success(warehouseInventoryService.listMaterialOptions(currentOrgId()));
    }

    private String currentOrgId() {
        return roleOrgService.resolveOrgId(getUserId(), getDeptId());
    }
}
