package com.ruoyi.asset.controller;

import java.util.List;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.asset.domain.AmsAsset;
import com.ruoyi.asset.domain.AmsBorrowOrder;
import com.ruoyi.asset.domain.AmsBorrowOrderItem;
import com.ruoyi.asset.domain.AmsAssetLocation;
import com.ruoyi.asset.domain.AmsWarehouse;
import com.ruoyi.asset.service.IAmsAssetLocationService;
import com.ruoyi.asset.service.IAmsBorrowOrderService;
import com.ruoyi.asset.service.IAmsWarehouseService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
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.domain.entity.SysUser;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 借用归还管理Controller
 *
 * 核心职责：提供借用单的新增草稿、修改、删除、提交、借出确认、驳回、归还申请、归还确认等API接口。
 *
 * @author Yangk
 * @date 2026-06-16
 */
@Controller
@RequestMapping("/asset/borrow")
public class AmsBorrowOrderController extends BaseController
{
    private String prefix = "asset/borrow";

    @Autowired
    private IAmsBorrowOrderService amsBorrowOrderService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IAmsWarehouseService amsWarehouseService;

    @Autowired
    private IAmsAssetLocationService amsAssetLocationService;

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

    /**
     * 查询借用归还管理列表
     */
    @RequiresPermissions("asset:borrow:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AmsBorrowOrder amsBorrowOrder)
    {
        startPage();
        List<AmsBorrowOrder> list = amsBorrowOrderService.selectAmsBorrowOrderList(amsBorrowOrder);
        return getDataTable(list);
    }

    /**
     * 弹出资产选择模态框
     */
    @RequiresPermissions(value = { "asset:borrow:add", "asset:borrow: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:borrow:add", "asset:borrow:edit" }, logical = Logical.OR)
    @PostMapping("/availableAssetList")
    @ResponseBody
    public TableDataInfo availableAssetList(AmsAsset asset, @RequestParam(value = "orderId", required = false) Long orderId)
    {
        startPage();
        List<AmsAsset> list = amsBorrowOrderService.selectAvailableBorrowAssetList(asset, orderId);
        return getDataTable(list);
    }

    /**
     * 导出借用归还管理列表
     */
    @RequiresPermissions("asset:borrow:export")
    @Log(title = "借用归还管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AmsBorrowOrder amsBorrowOrder)
    {
        List<AmsBorrowOrder> list = amsBorrowOrderService.selectAmsBorrowOrderList(amsBorrowOrder);
        ExcelUtil<AmsBorrowOrder> util = new ExcelUtil<AmsBorrowOrder>(AmsBorrowOrder.class);
        return util.exportExcel(list, "借用归还管理数据");
    }

    /**
     * 查看借用归还管理详情
     */
    @RequiresPermissions("asset:borrow:view")
    @GetMapping("/view/{orderId}")
    public String view(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        AmsBorrowOrder amsBorrowOrder = amsBorrowOrderService.selectAmsBorrowOrderByOrderId(orderId);
        mmap.put("amsBorrowOrder", amsBorrowOrder);
        putWarehouseLocationOptions(mmap);
        return prefix + "/view";
    }

    /**
     * 新增借用归还管理页面
     */
    @RequiresPermissions("asset:borrow:add")
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        putBorrowOptions(mmap);
        return prefix + "/add";
    }

    /**
     * 新增保存借用归还管理（草稿）
     */
    @RequiresPermissions("asset:borrow:add")
    @Log(title = "借用归还管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AmsBorrowOrder amsBorrowOrder)
    {
        amsBorrowOrder.setCreateBy(getLoginName());
        return toAjax(amsBorrowOrderService.insertAmsBorrowOrder(amsBorrowOrder));
    }

    /**
     * 修改借用归还管理页面
     */
    @RequiresPermissions("asset:borrow:edit")
    @GetMapping("/edit/{orderId}")
    public String edit(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        AmsBorrowOrder amsBorrowOrder = amsBorrowOrderService.selectAmsBorrowOrderByOrderId(orderId);
        mmap.put("amsBorrowOrder", amsBorrowOrder);
        putBorrowOptions(mmap);
        return prefix + "/edit";
    }

    /**
     * 修改保存借用归还管理（草稿）
     */
    @RequiresPermissions("asset:borrow:edit")
    @Log(title = "借用归还管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AmsBorrowOrder amsBorrowOrder)
    {
        amsBorrowOrder.setUpdateBy(getLoginName());
        return toAjax(amsBorrowOrderService.updateAmsBorrowOrder(amsBorrowOrder));
    }

    /**
     * 删除借用归还管理草稿
     */
    @RequiresPermissions("asset:borrow:remove")
    @Log(title = "借用归还管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(amsBorrowOrderService.deleteAmsBorrowOrderByOrderIds(ids));
    }

    /**
     * 提交借用申请
     */
    @RequiresPermissions("asset:borrow:submit")
    @Log(title = "借用归还管理", businessType = BusinessType.UPDATE)
    @PostMapping("/submit/{orderId}")
    @ResponseBody
    public AjaxResult submit(@PathVariable("orderId") Long orderId)
    {
        return toAjax(amsBorrowOrderService.submitBorrow(orderId, getLoginName()));
    }

    /**
     * 确认借出
     */
    @RequiresPermissions("asset:borrow:confirm")
    @Log(title = "借用归还管理", businessType = BusinessType.UPDATE)
    @PostMapping("/confirm/{orderId}")
    @ResponseBody
    public AjaxResult confirm(@PathVariable("orderId") Long orderId)
    {
        return toAjax(amsBorrowOrderService.confirmBorrow(orderId, getUserId(),
                getSysUser().getUserName(), getLoginName()));
    }

    /**
     * 驳回借用申请
     */
    @RequiresPermissions("asset:borrow:reject")
    @Log(title = "借用归还管理", businessType = BusinessType.UPDATE)
    @PostMapping("/reject/{orderId}")
    @ResponseBody
    public AjaxResult reject(@PathVariable("orderId") Long orderId, @RequestParam("rejectReason") String rejectReason)
    {
        return toAjax(amsBorrowOrderService.rejectBorrow(orderId, rejectReason, getLoginName()));
    }

    /**
     * 申请归还（分批归还，支持明细项上传）
     */
    @RequiresPermissions("asset:borrow:applyReturn")
    @Log(title = "借用归还管理", businessType = BusinessType.UPDATE)
    @PostMapping("/applyReturn/{orderId}")
    @ResponseBody
    public AjaxResult applyReturn(@PathVariable("orderId") Long orderId, @RequestBody List<AmsBorrowOrderItem> items)
    {
        return toAjax(amsBorrowOrderService.applyReturn(orderId, items, getLoginName()));
    }

    /**
     * 确认归还
     */
    @RequiresPermissions("asset:borrow:confirmReturn")
    @Log(title = "借用归还管理", businessType = BusinessType.UPDATE)
    @PostMapping("/confirmReturn/{orderId}")
    @ResponseBody
    public AjaxResult confirmReturn(@PathVariable("orderId") Long orderId, @RequestBody List<AmsBorrowOrderItem> items)
    {
        return toAjax(amsBorrowOrderService.confirmReturn(orderId, items, getUserId(),
                getSysUser().getUserName(), getLoginName()));
    }

    private void putBorrowOptions(ModelMap mmap)
    {
        mmap.put("deptList", selectNormalDeptList());
        SysUser user = new SysUser();
        user.setStatus(UserConstants.NORMAL);
        mmap.put("userList", sysUserService.selectUserList(user));
        SysUser currentUser = getSysUser();
        mmap.put("defaultBorrowDeptId", currentUser.getDeptId());
        mmap.put("defaultBorrowUserId", currentUser.getUserId());
    }

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

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

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