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.WarehouseStockIssue;
import com.ruoyi.web.stock.service.IRoleOrgService;
import com.ruoyi.web.stock.service.IWarehouseStockIssueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/stock/issue")
public class WarehouseStockIssueController extends BaseController {
    @Autowired private IWarehouseStockIssueService warehouseStockIssueService;
    @Autowired private IRoleOrgService roleOrgService;

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

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

    @PreAuthorize("@ss.hasPermi('erp:stock:issue:add')")
    @Log(title = "仓库领料", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WarehouseStockIssue entity) {
        entity.setOrgId(currentOrgId());
        return toAjax(warehouseStockIssueService.submitIssue(entity, getUsername()));
    }

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

    @PreAuthorize("@ss.hasPermi('erp:stock:issue:query')")
    @GetMapping("/inventory/options")
    public AjaxResult inventoryOptions() {
        return success(warehouseStockIssueService.listInventoryLineOptions(currentOrgId()));
    }

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