<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备编号" prop="deviceCode">
              <el-input v-model="queryParams.deviceCode" placeholder="请输入设备编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="所在位置" prop="locationId">
              <el-tree-select
                v-model="queryParams.locationId"
                :data="locationOptions"
                :props="{ value: 'id', label: 'locationAlias', children: 'children' }"
                value-key="id"
                placeholder="请选择所在位置"
                check-strictly
                clearable
              />
            </el-form-item>
            <!-- 以下为不常用搜索条件，按需开放 -->
            <!--
            <el-form-item label="设备地址" prop="deviceAddress">
              <el-input v-model="queryParams.deviceAddress" placeholder="请输入设备地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备端口" prop="devicePort">
              <el-input-number v-model="queryParams.devicePort" :min="0" :max="65535" placeholder="请输入设备端口" controls-position="right" />
            </el-form-item>
            <el-form-item label="读取频率" prop="readFrequency">
              <el-input-number v-model="queryParams.readFrequency" :min="0" placeholder="请输入读取频率" controls-position="right" />
            </el-form-item>
            -->
            <el-form-item label="在线状态" prop="onlineStatus">
              <el-select v-model="queryParams.onlineStatus" placeholder="请选择在线状态" clearable >
                <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="告警状态" prop="alarmStatus">
              <el-select v-model="queryParams.alarmStatus" placeholder="请选择告警状态" clearable >
                <el-option v-for="dict in alarm_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="是否标识" prop="isMarked">
              <el-select v-model="queryParams.isMarked" placeholder="请选择是否标识" clearable >
                <el-option v-for="dict in is_marked" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['rfid:rfidDevice:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['rfid:rfidDevice:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['rfid:rfidDevice:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['rfid:rfidDevice:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="rfidDeviceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" width="55" align="center" label="序号" />
        <el-table-column label="设备编号" align="center" prop="deviceCode" v-if="columns[0].visible" />
        <el-table-column label="设备名称" align="center" prop="deviceName" v-if="columns[1].visible" />
        <el-table-column label="所在位置" align="center" prop="locationAlias" v-if="columns[2].visible" />
        <el-table-column label="设备地址" align="center" prop="deviceAddress" v-if="columns[3].visible" />
        <el-table-column label="设备端口" align="center" prop="devicePort" v-if="columns[4].visible" />
        <el-table-column label="读取频率" align="center" prop="readFrequency" v-if="columns[5].visible" />
        <el-table-column label="在线状态" align="center" prop="onlineStatus" v-if="columns[6].visible">
          <template #default="scope">
            <dict-tag :options="online_status" :value="scope.row.onlineStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="告警状态" align="center" prop="alarmStatus" v-if="columns[7].visible">
          <template #default="scope">
            <dict-tag :options="alarm_status" :value="scope.row.alarmStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="是否标识" align="center" prop="isMarked" v-if="columns[8].visible">
          <template #default="scope">
            <dict-tag :options="is_marked" :value="scope.row.isMarked"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[9].visible" />
        <el-table-column label="创建人" align="center" prop="createdBy" v-if="columns[10].visible" />
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180" v-if="columns[11].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新人" align="center" prop="updatedBy" v-if="columns[12].visible" />
        <el-table-column label="更新时间" align="center" prop="updatedAt" width="180" v-if="columns[13].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right"  class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['rfid:rfidDevice:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['rfid:rfidDevice:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="rfidDeviceFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="所在位置" prop="locationId">
          <el-tree-select
            v-model="form.locationId"
            :data="locationOptions"
            :props="{ value: 'id', label: 'locationAlias', children: 'children' }"
            value-key="id"
            placeholder="请选择所在位置"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="设备地址" prop="deviceAddress">
          <el-input v-model="form.deviceAddress" placeholder="请输入设备地址" />
        </el-form-item>
        <el-form-item label="设备端口" prop="devicePort">
          <el-input-number v-model="form.devicePort" :min="0" :max="65535" placeholder="请输入设备端口" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="读取频率" prop="readFrequency">
          <el-input-number v-model="form.readFrequency" :min="0" placeholder="请输入读取频率" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="在线状态" prop="onlineStatus">
          <el-radio-group v-model="form.onlineStatus">
            <el-radio
              v-for="dict in online_status"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="告警状态" prop="alarmStatus">
          <el-radio-group v-model="form.alarmStatus">
            <el-radio
              v-for="dict in alarm_status"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否标识" prop="isMarked">
          <el-radio-group v-model="form.isMarked">
            <el-radio
              v-for="dict in is_marked"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <!-- 以下为审计字段输入，默认由后端维护，前端不提供编辑入口，如有需要再放开 -->
        <!--
        <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新人" prop="updatedBy">
          <el-input v-model="form.updatedBy" placeholder="请输入更新人" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RfidDevice" lang="ts">
import { listRfidDevice, getRfidDevice, delRfidDevice, addRfidDevice, updateRfidDevice } from "@/api/rfid/rfidDevice";
import { RfidDeviceVO, RfidDeviceQuery, RfidDeviceForm } from '@/api/rfid/rfidDevice/types';
import { getRfidLocationList } from "@/api/rfid/rfidLocation";

    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { alarm_status, online_status, is_marked } = toRefs<any>(proxy?.useDict('alarm_status', 'online_status', 'is_marked'));

type RfidLocationOption = {
  id: number;
  locationAlias: string;
  children?: RfidLocationOption[];
}

const rfidDeviceList = ref<RfidDeviceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const locationOptions = ref<RfidLocationOption[]>([]);

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: '设备编号', visible: true },
  { key: 1, label: '设备名称', visible: true },
  { key: 2, label: '所在位置', visible: true },
  { key: 3, label: '设备地址', visible: true },
  { key: 4, label: '设备端口', visible: true },
  { key: 5, label: '读取频率', visible: true },
  { key: 6, label: '在线状态', visible: true },
  { key: 7, label: '告警状态', visible: true },
  { key: 8, label: '是否标识', visible: false },
  { key: 9, label: '备注', visible: false },
  { key: 10, label: '创建人', visible: false },
  { key: 11, label: '创建时间', visible: false },
  { key: 12, label: '更新人', visible: false },
  { key: 13, label: '更新时间', visible: false }
]);

const queryFormRef = ref<ElFormInstance>();
const rfidDeviceFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: RfidDeviceForm = {
  id: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  locationId: undefined,
  deviceAddress: undefined,
  devicePort: undefined,
  readFrequency: undefined,
  onlineStatus: undefined,
  alarmStatus: undefined,
  isMarked: '1',
  remark: undefined,
  createdBy: undefined,
  createdAt: undefined,
  updatedBy: undefined,
  updatedAt: undefined
}
const data = reactive<PageData<RfidDeviceForm, RfidDeviceQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceCode: undefined,
    deviceName: undefined,
    locationId: undefined,
    deviceAddress: undefined,
    devicePort: undefined,
    readFrequency: undefined,
    onlineStatus: undefined,
    alarmStatus: undefined,
    isMarked: undefined,
    createdBy: undefined,
    createdAt: undefined,
    updatedBy: undefined,
    updatedAt: undefined,
    params: {
    }
  },
  rules: {
    deviceCode: [
      { required: true, message: "设备编号不能为空", trigger: "blur" }
    ],
    deviceName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
    onlineStatus: [
      { required: true, message: "在线状态不能为空", trigger: "change" }
    ],
    alarmStatus: [
      { required: true, message: "告警状态不能为空", trigger: "change" }
    ],
    isMarked: [
      { required: true, message: "是否标识不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRfidDevice(queryParams.value);
  rfidDeviceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 加载位置下拉树（所在位置），使用 getRfidLocationList 获取全量数据 */
const loadLocationOptions = async () => {
	const res = await getRfidLocationList();
	locationOptions.value = [];
	const root: RfidLocationOption = { id: 0, locationAlias: '顶级节点', children: [] };
	root.children = proxy?.handleTree<RfidLocationOption>(res.data, 'id', 'parentId') || [];
	locationOptions.value.push(root);
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  rfidDeviceFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: RfidDeviceVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加设备信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: RfidDeviceVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getRfidDevice(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改设备信息";
}

/** 提交按钮 */
const submitForm = () => {
  rfidDeviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateRfidDevice(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addRfidDevice(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: RfidDeviceVO) => {
  const _ids = row?.id || ids.value;
  try {
    await proxy?.$modal.confirm('是否确认删除设备信息编号为"' + _ids + '"的数据项？');
    loading.value = true;
    await delRfidDevice(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  } finally {
    loading.value = false;
  }
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('rfid/rfidDevice/export', {
    ...queryParams.value
  }, `rfidDevice_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  loadLocationOptions();
});
</script>
