<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="读写器IP" prop="equipIp">
              <el-input v-model="queryParams.equipIp" placeholder="请输入读写器IP" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="读写器Key" prop="equipKey">
              <el-input v-model="queryParams.equipKey" placeholder="请输入读写器Key" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="机台代码" prop="machineCode">
              <el-input v-model="queryParams.machineCode" placeholder="请输入机台代码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="启用状态" prop="isFalg">
              <el-select v-model="queryParams.isFalg" placeholder="请选择启用状态" clearable>
                <el-option v-for="dict in is_falg" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="在线状态" prop="isOnline">
              <el-select v-model="queryParams.isOnline" placeholder="请选择在线状态" clearable>
                <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="Number(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="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wcs:rfidinfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wcs:rfidinfo:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wcs:rfidinfo:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wcs:rfidinfo:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="rfidinfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column v-if="columns[0].visible" type="index" label="序号" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="设备名称" align="center" prop="equipName" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[2].visible" label="读写器Key" align="center" prop="equipKey" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[3].visible" label="机台代码" align="center" prop="machineCode" width="120" />
        <el-table-column v-if="columns[4].visible" label="连接地址" align="center" min-width="160">
          <template #default="scope">
            <span>{{ formatEndpoint(scope.row.equipIp, scope.row.equipPort) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" label="启用状态" align="center" prop="isFalg" width="100">
          <template #default="scope">
            <dict-tag :options="is_falg" :value="scope.row.isFalg" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="在线状态" align="center" prop="isOnline" width="100">
          <template #default="scope">
            <dict-tag :options="online_status" :value="scope.row.isOnline" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" label="备注" align="center" prop="remark" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[8].visible" label="创建时间" align="center" prop="createTime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="110" 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="['wcs:rfidinfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wcs:rfidinfo:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="680px" append-to-body>
      <el-form ref="rfidinfoFormRef" :model="form" :rules="rules" label-width="104px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipName">
              <el-input v-model="form.equipName" placeholder="请输入设备名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机台代码" prop="machineCode">
              <el-input v-model="form.machineCode" placeholder="请输入机台代码" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="读写器IP" prop="equipIp">
              <el-input v-model="form.equipIp" placeholder="请输入IPv4地址" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="读写器端口" prop="equipPort">
              <el-input-number v-model="form.equipPort" :min="0" :max="65535" :controls="false" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="读写器Key" prop="equipKey">
              <el-input v-model="form.equipKey" placeholder="请输入唯一设备Key" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="isFalg">
              <el-radio-group v-model="form.isFalg">
                <el-radio-button v-for="dict in is_falg" :key="dict.value" :value="Number(dict.value)">
                  {{ dict.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在线状态" prop="isOnline">
              <el-radio-group v-model="form.isOnline">
                <el-radio-button v-for="dict in online_status" :key="dict.value" :value="Number(dict.value)">
                  {{ dict.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入安装位置、接线说明或维护备注" maxlength="300" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </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="Rfidinfo" lang="ts">
import { to } from 'await-to-js';
import { addRfidinfo, delRfidinfo, getRfidinfo, listRfidinfo, updateRfidinfo } from '@/api/wcs/rfidinfo';
import { RfidinfoForm, RfidinfoQuery, RfidinfoVO } from '@/api/wcs/rfidinfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 与 BaseRfidinfoVo @ExcelDictFormat 对齐：is_falg / online_status。
const { is_falg, online_status } = toRefs<any>(proxy?.useDict('is_falg', 'online_status'));

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

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

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

const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '设备名称', visible: true, children: [] },
  { key: 2, label: '读写器Key', visible: true, children: [] },
  { key: 3, label: '机台代码', visible: true, children: [] },
  { key: 4, label: '连接地址', visible: true, children: [] },
  { key: 5, label: '启用状态', visible: true, children: [] },
  { key: 6, label: '在线状态', visible: true, children: [] },
  { key: 7, label: '备注', visible: true, children: [] },
  { key: 8, label: '创建时间', visible: true, children: [] }
]);

const initFormData: RfidinfoForm = {
  configId: undefined,
  equipIp: undefined,
  equipPort: undefined,
  equipKey: undefined,
  isFalg: 0,
  remark: undefined,
  isOnline: 0,
  equipName: undefined,
  machineCode: undefined
};

const validateIpv4 = (_rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('读写器IP不能为空'));
    return;
  }
  const ipv4Pattern = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
  if (!ipv4Pattern.test(value)) {
    callback(new Error('请输入合法的IPv4地址'));
    return;
  }
  callback();
};

const data = reactive<PageData<RfidinfoForm, RfidinfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipIp: undefined,
    equipPort: undefined,
    equipKey: undefined,
    isFalg: undefined,
    isOnline: undefined,
    equipName: undefined,
    machineCode: undefined,
    params: {}
  },
  rules: {
    equipIp: [{ required: true, validator: validateIpv4, trigger: 'blur' }],
    equipKey: [{ required: true, message: '读写器Key不能为空', trigger: 'blur' }],
    isFalg: [{ required: true, message: '启用状态不能为空', trigger: 'change' }]
  }
});

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

const getList = async () => {
  loading.value = true;
  try {
    const res = await listRfidinfo(queryParams.value);
    rfidinfoList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const reset = () => {
  form.value = { ...initFormData };
  rfidinfoFormRef.value?.resetFields();
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: RfidinfoVO[]) => {
  ids.value = selection.map((item) => item.configId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增RFID读写器';
};

const handleUpdate = async (row?: RfidinfoVO) => {
  reset();
  const configId = row?.configId || ids.value[0];
  const res = await getRfidinfo(configId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改RFID读写器';
};

const submitForm = () => {
  rfidinfoFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    buttonLoading.value = true;
    try {
      if (form.value.configId) {
        await updateRfidinfo(form.value);
      } else {
        await addRfidinfo(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleDelete = async (row?: RfidinfoVO) => {
  const configIds = row?.configId || ids.value;
  const [err] = await to(proxy?.$modal.confirm('是否确认删除RFID读写器编号为"' + configIds + '"的数据项？') as any);
  if (!err) {
    await delRfidinfo(configIds);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  }
};

const handleExport = () => {
  proxy?.download('wcs/rfidinfo/export', { ...queryParams.value }, `rfidinfo_${new Date().getTime()}.xlsx`);
};

const formatEndpoint = (ip?: string, port?: number) => {
  if (!ip && !port) {
    return '';
  }
  return port ? `${ip || '-'}:${port}` : ip;
};

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