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.enums.BusinessType;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.web.stock.domain.WarehouseBase;
import com.ruoyi.web.stock.service.IRoleOrgService;
import com.ruoyi.web.stock.service.IWarehouseBaseService;
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/warehouse")
public class WarehouseBaseController extends BaseController {

    @Autowired
    private IWarehouseBaseService warehouseBaseService;
    @Autowired
    private IRoleOrgService roleOrgService;

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

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

    @PreAuthorize("@ss.hasPermi('erp:stock:warehouse:add')")
    @Log(title = "仓库基础设置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WarehouseBase entity) {
        entity.setOrgId(currentOrgId());
        if (!warehouseBaseService.checkWarehouseNoValid(entity.getWarehouseNo())) {
            return error("新增失败，仓库编号必须为大于0的数字，支持前导0格式（如0001）");
        }
        if (!warehouseBaseService.checkWarehouseNoUnique(entity, currentOrgId())) {
            return error("新增失败，仓库编号已存在");
        }
        entity.setCreateBy(getUsername());
        entity.setUpdateBy(getUsername());
        return toAjax(warehouseBaseService.insert(entity));
    }

    @PreAuthorize("@ss.hasPermi('erp:stock:warehouse:edit')")
    @Log(title = "仓库基础设置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WarehouseBase entity) {
        WarehouseBase old = warehouseBaseService.selectById(entity.getId());
        if (old == null || !currentOrgId().equals(old.getOrgId())) {
            return error("无权修改该数据");
        }
        entity.setOrgId(currentOrgId());
        if (!warehouseBaseService.checkWarehouseNoValid(entity.getWarehouseNo())) {
            return error("修改失败，仓库编号必须为大于0的数字，支持前导0格式（如0001）");
        }
        if (!warehouseBaseService.checkWarehouseNoUnique(entity, currentOrgId())) {
            return error("修改失败，仓库编号已存在");
        }
        entity.setUpdateBy(getUsername());
        return toAjax(warehouseBaseService.update(entity));
    }

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

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

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