package com.ruoyi.asset.controller;

import java.util.List;
import com.ruoyi.asset.domain.AmsAsset;
import com.ruoyi.asset.domain.AmsAssetLocation;
import com.ruoyi.asset.domain.AmsReturnOrder;
import com.ruoyi.asset.domain.AmsWarehouse;
import com.ruoyi.asset.service.IAmsAssetLocationService;
import com.ruoyi.asset.service.IAmsReturnOrderService;
import com.ruoyi.asset.service.IAmsWarehouseService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 退库管理Controller
 *
 * @author Yangk
 */
@Controller
@RequestMapping("/asset/return")
public class AmsReturnOrderController extends BaseController
{
    private static final String ENABLED_YES = "Y";

    private String prefix = "asset/return";

    @Autowired
    private IAmsReturnOrderService amsReturnOrderService;

    @Autowired
    private IAmsWarehouseService amsWarehouseService;

    @Autowired
    private IAmsAssetLocationService amsAssetLocationService;

    @Autowired
    private ISysDeptService sysDeptService;

    @RequiresPermissions("asset:return:view")
    @GetMapping()
    public String returnPage(ModelMap mmap)
    {
        mmap.put("warehouseList", selectEnabledWarehouseList());
        mmap.put("deptList", selectNormalDeptList());
        return prefix + "/return";
    }

    @RequiresPermissions("asset:return:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AmsReturnOrder order)
    {
        startPage();
        return getDataTable(amsReturnOrderService.selectAmsReturnOrderList(order));
    }

    /** 
     * 打开在用资产分页选择页。
     * <p>
     * 业务意图：
     * 提供一个资产筛选弹出层，使得用户可以查找并选择要退库的资产。
     * 参数 `originWarehouseId` 和 `missingOriginOnly` 用于在单据保存了第一个资产后，
     * 强力约束后续资产必须和第一个资产的“来源仓库类型”或“原仓库 ID”相匹配，实现单仓库分组校验前端控制。
     * </p>
     */
    @RequiresPermissions(value = { "asset:return:add", "asset:return:edit" }, logical = Logical.OR)
    @GetMapping("/selectAsset")
    public String selectAsset(@RequestParam(value = "orderId", required = false) Long orderId,
            @RequestParam(value = "originWarehouseId", required = false) Long originWarehouseId,
            @RequestParam(value = "missingOriginOnly", required = false) Boolean missingOriginOnly,
            ModelMap mmap)
    {
        mmap.put("orderId", orderId);
        mmap.put("originWarehouseId", originWarehouseId);
        mmap.put("missingOriginOnly", missingOriginOnly);
        mmap.put("deptList", selectNormalDeptList());
        return prefix + "/selectAsset";
    }

    /** 
     * 查询未被其他有效退库单占用的在用资产。
     * <p>
     * 业务意图与避坑：
     * 1. 只有处于“在用(IN_USE)”状态的资产才允许被选择退库。
     * 2. 必须排除当前已被其他“草稿”或“待确认”退库单占用的资产，以防在审批流转中产生资产被重复退库的并发漏洞。
     * 3. 若 `orderId` 不为空，则查询时应把当前退库单已经占有的资产剔除排除条件，防止自冲突。
     * </p>
     */
    @RequiresPermissions(value = { "asset:return:add", "asset:return:edit" }, logical = Logical.OR)
    @PostMapping("/availableAssetList")
    @ResponseBody
    public TableDataInfo availableAssetList(AmsAsset asset,
            @RequestParam(value = "orderId", required = false) Long orderId,
            @RequestParam(value = "originWarehouseId", required = false) Long originWarehouseId,
            @RequestParam(value = "missingOriginOnly", required = false) Boolean missingOriginOnly)
    {
        startPage();
        return getDataTable(amsReturnOrderService.selectAvailableReturnAssetList(asset, orderId,
                originWarehouseId, missingOriginOnly));
    }

    @RequiresPermissions("asset:return:export")
    @Log(title = "退库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AmsReturnOrder order)
    {
        List<AmsReturnOrder> list = amsReturnOrderService.selectAmsReturnOrderList(order);
        return new ExcelUtil<AmsReturnOrder>(AmsReturnOrder.class).exportExcel(list, "退库管理数据");
    }

    @RequiresPermissions("asset:return:view")
    @GetMapping("/view/{orderId}")
    public String view(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        mmap.put("amsReturnOrder", amsReturnOrderService.selectAmsReturnOrderByOrderId(orderId));
        return prefix + "/view";
    }

    @RequiresPermissions("asset:return:add")
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        putReturnOptions(mmap);
        return prefix + "/add";
    }

    @RequiresPermissions("asset:return:add")
    @Log(title = "退库管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AmsReturnOrder order)
    {
        order.setCreateBy(getLoginName());
        return toAjax(amsReturnOrderService.insertAmsReturnOrder(order, getUserId(),
                getSysUser().getUserName(), getSysUser().getDeptId()));
    }

    @RequiresPermissions("asset:return:edit")
    @GetMapping("/edit/{orderId}")
    public String edit(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        mmap.put("amsReturnOrder", amsReturnOrderService.selectAmsReturnOrderByOrderId(orderId));
        putReturnOptions(mmap);
        return prefix + "/edit";
    }

    @RequiresPermissions("asset:return:edit")
    @Log(title = "退库管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AmsReturnOrder order)
    {
        order.setUpdateBy(getLoginName());
        return toAjax(amsReturnOrderService.updateAmsReturnOrder(order));
    }

    /**
     * 提交退库单。
     * <p>
     * 业务意图：
     * 将单据由“草稿(DRAFT)”状态提交为“待确认(PENDING_CONFIRM)”。
     * 在提交前，后台会校验单据中所有资产的最新状态与使用归属。
     * </p>
     */
    @RequiresPermissions("asset:return:submit")
    @Log(title = "退库管理", businessType = BusinessType.UPDATE)
    @PostMapping("/submit/{orderId}")
    @ResponseBody
    public AjaxResult submit(@PathVariable("orderId") Long orderId)
    {
        return toAjax(amsReturnOrderService.submitReturn(orderId, getLoginName()));
    }

    /**
     * 确认退库。
     * <p>
     * 业务意图与避坑：
     * 仓管员在实物清点无误后点击确认。单据状态由“待确认(PENDING_CONFIRM)”转为“已退库(RETURNED)”。
     * 此动作会触发核心台账变化：资产的使用部门与使用人被清空，仓库与存放位置更新为退库后的目标仓位，并向资产履历中写入变动历史。
     * 确认人及确认时间被作为最终审核凭证固化到单据主表中。
     * </p>
     */
    @RequiresPermissions("asset:return:confirm")
    @Log(title = "退库管理", businessType = BusinessType.UPDATE)
    @PostMapping("/confirm/{orderId}")
    @ResponseBody
    public AjaxResult confirm(@PathVariable("orderId") Long orderId)
    {
        return toAjax(amsReturnOrderService.confirmReturn(orderId, getUserId(),
                getSysUser().getUserName(), getLoginName()));
    }

    @RequiresPermissions("asset:return:remove")
    @Log(title = "退库管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(amsReturnOrderService.deleteAmsReturnOrderByOrderIds(ids));
    }

    private void putReturnOptions(ModelMap mmap)
    {
        mmap.put("warehouseList", selectEnabledWarehouseList());
        AmsAssetLocation location = new AmsAssetLocation();
        location.setEnabled(ENABLED_YES);
        mmap.put("locationList", amsAssetLocationService.selectAmsAssetLocationList(location));
    }

    private List<AmsWarehouse> selectEnabledWarehouseList()
    {
        AmsWarehouse warehouse = new AmsWarehouse();
        warehouse.setEnabled(ENABLED_YES);
        return amsWarehouseService.selectAmsWarehouseList(warehouse);
    }

    private List<SysDept> selectNormalDeptList()
    {
        SysDept dept = new SysDept();
        dept.setStatus(UserConstants.DEPT_NORMAL);
        return sysDeptService.selectDeptList(dept);
    }
}
