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.AmsTransferOrder;
import com.ruoyi.asset.domain.AmsWarehouse;
import com.ruoyi.asset.service.IAmsAssetLocationService;
import com.ruoyi.asset.service.IAmsTransferOrderService;
import com.ruoyi.asset.service.IAmsWarehouseService;
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.utils.poi.ExcelUtil;
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/transfer")
public class AmsTransferOrderController extends BaseController
{
    private static final String ENABLED_YES = "Y";

    private String prefix = "asset/transfer";

    @Autowired
    private IAmsTransferOrderService amsTransferOrderService;

    @Autowired
    private IAmsWarehouseService amsWarehouseService;

    @Autowired
    private IAmsAssetLocationService amsAssetLocationService;

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

    @RequiresPermissions("asset:transfer:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AmsTransferOrder amsTransferOrder)
    {
        startPage();
        return getDataTable(amsTransferOrderService.selectAmsTransferOrderList(amsTransferOrder));
    }

    /** 打开可调拨资产分页选择页（调拨单新增/编辑的明细弹窗选择器） */
    @RequiresPermissions(value = { "asset:transfer:add", "asset:transfer:edit" }, logical = Logical.OR)
    @GetMapping("/selectAsset")
    public String selectAsset(@RequestParam(value = "orderId", required = false) Long orderId, ModelMap mmap)
    {
        mmap.put("orderId", orderId);
        return prefix + "/selectAsset";
    }

    /** 分页查询未被其他有效调拨单占用的在库资产（仅返回可调拨资产） */
    @RequiresPermissions(value = { "asset:transfer:add", "asset:transfer:edit" }, logical = Logical.OR)
    @PostMapping("/availableAssetList")
    @ResponseBody
    public TableDataInfo availableAssetList(AmsAsset amsAsset,
            @RequestParam(value = "orderId", required = false) Long orderId)
    {
        startPage();
        return getDataTable(amsTransferOrderService.selectAvailableTransferAssetList(amsAsset, orderId));
    }

    @RequiresPermissions("asset:transfer:export")
    @Log(title = "调拨管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AmsTransferOrder amsTransferOrder)
    {
        List<AmsTransferOrder> list = amsTransferOrderService.selectAmsTransferOrderList(amsTransferOrder);
        return new ExcelUtil<AmsTransferOrder>(AmsTransferOrder.class).exportExcel(list, "调拨管理数据");
    }

    @RequiresPermissions("asset:transfer:view")
    @GetMapping("/view/{orderId}")
    public String view(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        mmap.put("amsTransferOrder", amsTransferOrderService.selectAmsTransferOrderByOrderId(orderId));
        return prefix + "/view";
    }

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

    @RequiresPermissions("asset:transfer:add")
    @Log(title = "调拨管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AmsTransferOrder amsTransferOrder)
    {
        amsTransferOrder.setCreateBy(getLoginName());
        return toAjax(amsTransferOrderService.insertAmsTransferOrder(amsTransferOrder,
                getUserId(), getSysUser().getUserName()));
    }

    @RequiresPermissions("asset:transfer:edit")
    @GetMapping("/edit/{orderId}")
    public String edit(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        mmap.put("amsTransferOrder", amsTransferOrderService.selectAmsTransferOrderByOrderId(orderId));
        putTransferOptions(mmap);
        return prefix + "/edit";
    }

    @RequiresPermissions("asset:transfer:edit")
    @Log(title = "调拨管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AmsTransferOrder amsTransferOrder)
    {
        amsTransferOrder.setUpdateBy(getLoginName());
        return toAjax(amsTransferOrderService.updateAmsTransferOrder(amsTransferOrder));
    }

    /** 提交调拨单（DRAFT → PENDING_CONFIRM），提交后不可再修改或删除。 */
    @RequiresPermissions("asset:transfer:submit")
    @Log(title = "调拨管理", businessType = BusinessType.UPDATE)
    @PostMapping("/submit/{orderId}")
    @ResponseBody
    public AjaxResult submit(@PathVariable("orderId") Long orderId)
    {
        return toAjax(amsTransferOrderService.submitTransfer(orderId, getLoginName()));
    }

    /** 确认调拨（PENDING_CONFIRM → TRANSFERRED），确认后更新全部资产的当前归属并写入履历。 */
    @RequiresPermissions("asset:transfer:confirm")
    @Log(title = "调拨管理", businessType = BusinessType.UPDATE)
    @PostMapping("/confirm/{orderId}")
    @ResponseBody
    public AjaxResult confirm(@PathVariable("orderId") Long orderId)
    {
        return toAjax(amsTransferOrderService.confirmTransfer(orderId, getUserId(),
                getSysUser().getUserName(), getLoginName()));
    }

    @RequiresPermissions("asset:transfer:remove")
    @Log(title = "调拨管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(amsTransferOrderService.deleteAmsTransferOrderByOrderIds(ids));
    }

    /** 调拨表单只需要仓库和位置选项。 */
    private void putTransferOptions(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);
    }
}
