package com.ruoyi.asset.controller;

import java.util.List;
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.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.asset.domain.AmsAsset;
import com.ruoyi.asset.domain.AmsRfidTag;
import com.ruoyi.asset.domain.RfidBindingContext;
import com.ruoyi.asset.service.IAmsAssetService;
import com.ruoyi.asset.service.IAmsRfidTagService;
import com.ruoyi.asset.service.IRfidBindingService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * RFID标签Controller
 * 
 * @author Yangk
 * @date 2026-06-05
 */
@Controller
@RequestMapping("/asset/tag")
public class AmsRfidTagController extends BaseController
{
    private String prefix = "asset/tag";

    @Autowired
    private IAmsRfidTagService amsRfidTagService;

    @Autowired
    private IAmsAssetService amsAssetService;

    @Autowired
    private IRfidBindingService rfidBindingService;

    @RequiresPermissions("asset:tag:view")
    @GetMapping()
    public String tag()
    {
        return prefix + "/tag";
    }

    /**
     * 查询RFID标签列表
     */
    @RequiresPermissions("asset:tag:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AmsRfidTag amsRfidTag)
    {
        startPage();
        List<AmsRfidTag> list = amsRfidTagService.selectAmsRfidTagList(amsRfidTag);
        return getDataTable(list);
    }

    /**
     * 导出RFID标签列表
     */
    @RequiresPermissions("asset:tag:export")
    @Log(title = "RFID标签", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AmsRfidTag amsRfidTag)
    {
        List<AmsRfidTag> list = amsRfidTagService.selectAmsRfidTagList(amsRfidTag);
        ExcelUtil<AmsRfidTag> util = new ExcelUtil<AmsRfidTag>(AmsRfidTag.class);
        return util.exportExcel(list, "RFID标签数据");
    }

    /**
     * 查看RFID标签详情
     */
    @RequiresPermissions("asset:tag:view")
    @GetMapping("/view/{tagId}")
    public String view(@PathVariable("tagId") Long tagId, ModelMap mmap)
    {
        AmsRfidTag amsRfidTag = amsRfidTagService.selectAmsRfidTagByTagId(tagId);
        mmap.put("amsRfidTag", amsRfidTag);
        return prefix + "/view";
    }

    /**
     * 新增RFID标签
     */
    @RequiresPermissions("asset:tag:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存RFID标签
     */
    @RequiresPermissions("asset:tag:add")
    @Log(title = "RFID标签", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AmsRfidTag amsRfidTag)
    {
        if (!amsRfidTagService.checkTagCodeUnique(amsRfidTag))
        {
            return error("新增RFID标签失败，标签编码已存在");
        }
        if (!amsRfidTagService.checkEpcCodeUnique(amsRfidTag))
        {
            return error("新增RFID标签失败，EPC编码已存在");
        }
        amsRfidTag.setCreateBy(getLoginName());
        return toAjax(amsRfidTagService.insertAmsRfidTag(amsRfidTag));
    }

    /**
     * 修改RFID标签
     */
    @RequiresPermissions("asset:tag:edit")
    @GetMapping("/edit/{tagId}")
    public String edit(@PathVariable("tagId") Long tagId, ModelMap mmap)
    {
        AmsRfidTag amsRfidTag = amsRfidTagService.selectAmsRfidTagByTagId(tagId);
        mmap.put("amsRfidTag", amsRfidTag);
        return prefix + "/edit";
    }

    /**
     * 修改保存RFID标签
     */
    @RequiresPermissions("asset:tag:edit")
    @Log(title = "RFID标签", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AmsRfidTag amsRfidTag)
    {
        if (!amsRfidTagService.checkTagCodeUnique(amsRfidTag))
        {
            return error("修改RFID标签失败，标签编码已存在");
        }
        if (!amsRfidTagService.checkEpcCodeUnique(amsRfidTag))
        {
            return error("修改RFID标签失败，EPC编码已存在");
        }
        amsRfidTag.setUpdateBy(getLoginName());
        return toAjax(amsRfidTagService.updateAmsRfidTag(amsRfidTag));
    }

    /**
     * 作废RFID标签
     */
    @RequiresPermissions("asset:tag:edit")
    @Log(title = "RFID标签", businessType = BusinessType.UPDATE)
    @PostMapping("/void/{tagId}")
    @ResponseBody
    public AjaxResult voidTag(@PathVariable("tagId") Long tagId)
    {
        return toAjax(amsRfidTagService.voidAmsRfidTagByTagId(tagId, getLoginName()));
    }

    /**
     * 解绑RFID标签
     */
    @RequiresPermissions("asset:tag:edit")
    @Log(title = "RFID标签", businessType = BusinessType.UPDATE)
    @PostMapping("/unbind/{tagId}")
    @ResponseBody
    public AjaxResult unbind(@PathVariable("tagId") Long tagId)
    {
        return toAjax(amsRfidTagService.unbindAmsRfidTagByTagId(tagId, getUserId(),
                getSysUser().getUserName(), getLoginName()));
    }

    /**
     * 打开RFID标签绑定页面
     */
    @RequiresPermissions("asset:tag:bind")
    @GetMapping("/bind/{tagId}")
    public String bind(@PathVariable("tagId") Long tagId, ModelMap mmap)
    {
        AmsRfidTag amsRfidTag = requireExistingTag(tagId);
        mmap.put("amsRfidTag", amsRfidTag);
        return prefix + "/bind";
    }

    /**
     * 打开可绑定资产选择页面
     */
    @RequiresPermissions("asset:tag:bind")
    @GetMapping("/selectAsset")
    public String selectAsset()
    {
        return prefix + "/selectAsset";
    }

    /**
     * 查询可绑定RFID标签的资产
     */
    @RequiresPermissions("asset:tag:bind")
    @PostMapping("/bindableAssetList")
    @ResponseBody
    public TableDataInfo bindableAssetList(AmsAsset amsAsset)
    {
        startPage();
        List<AmsAsset> list = amsAssetService.selectBindableAmsAssetList(amsAsset);
        return getDataTable(list);
    }

    /**
     * Web后台绑定RFID标签
     */
    @RequiresPermissions("asset:tag:bind")
    @Log(title = "RFID标签绑定", businessType = BusinessType.UPDATE)
    @PostMapping("/bind")
    @ResponseBody
    public AjaxResult bindSave(Long tagId, String assetCode, String remark)
    {
        AmsRfidTag amsRfidTag = requireExistingTag(tagId);
        RfidBindingContext context = new RfidBindingContext();
        context.setOperateUserId(getUserId());
        context.setOperateUserName(getSysUser().getUserName());
        context.setOperateLoginName(getLoginName());
        context.setRemark(remark);
        // EPC始终从数据库读取，避免页面篡改后绑定到其他标签。
        rfidBindingService.bind(assetCode, amsRfidTag.getEpcCode(), context);
        return success("RFID标签绑定成功");
    }

    /**
     * 删除RFID标签
     */
    @RequiresPermissions("asset:tag:remove")
    @Log(title = "RFID标签", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(amsRfidTagService.deleteAmsRfidTagByTagIds(ids));
    }

    private AmsRfidTag requireExistingTag(Long tagId)
    {
        if (StringUtils.isNull(tagId))
        {
            throw new ServiceException("RFID标签ID不能为空");
        }
        AmsRfidTag amsRfidTag = amsRfidTagService.selectAmsRfidTagByTagId(tagId);
        if (StringUtils.isNull(amsRfidTag))
        {
            throw new ServiceException("RFID标签不存在或已删除");
        }
        return amsRfidTag;
    }
}
