<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="deviceId">
              <el-select v-model="queryParams.deviceId" placeholder="请选择设备名称" clearable filterable>
                <el-option
                  v-for="item in deviceOptions"
                  :key="item.id"
                  :label="item.deviceName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="读取状态" prop="readStatus">
              <el-select v-model="queryParams.readStatus" placeholder="请选择读取状态" clearable >
                <el-option v-for="dict in read_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="记录时间" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </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="warning" plain icon="Download" @click="handleExport" v-hasPermi="['rfid:downtimeRecord: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="downtimeRecordList">
        <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="readStatus" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="read_status" :value="scope.row.readStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="记录时间" align="center" prop="recordTime" width="180" v-if="columns[3].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </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>
  </div>
</template>

<script setup name="RfidReadRecord" lang="ts">
import { listDowntimeRecord } from "@/api/rfid/downtimeRecord";
import { RfidDowntimeRecordVO, RfidDowntimeRecordQuery } from '@/api/rfid/downtimeRecord/types';
import { getRfidDeviceList } from "@/api/rfid/rfidDevice";
import type { RfidDeviceVO } from '@/api/rfid/rfidDevice/types';
import { useDict } from '@/utils/dict';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { read_status } = toRefs(useDict('read_status'));

const downtimeRecordList = ref<RfidDowntimeRecordVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: '设备编号', visible: true },
  { key: 1, label: '设备名称', visible: true },
  { key: 2, label: '读取状态', visible: true },
  { key: 3, label: '记录时间', visible: true }
]);

const queryFormRef = ref<ElFormInstance>();

const deviceOptions = ref<RfidDeviceVO[]>([]);
// 记录时间范围（默认当天）
const dateRange = ref<[string, string] | []>([]);

/** 初始化默认时间范围：当天 00:00:00 ~ 23:59:59 */
const initDefaultDateRange = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  const dateStr = `${year}-${month}-${day}`;
  dateRange.value = [`${dateStr} 00:00:00`, `${dateStr} 23:59:59`];
};

const data = reactive<PageData<Record<string, never>, RfidDowntimeRecordQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: undefined,
    readStatus: undefined,
    beginRecordTime: undefined,
    endRecordTime: undefined,
    params: {
    }
  },
  rules: {}
});

const { queryParams } = toRefs(data);

/** 查询停机记录列表（上位机写入，web只读） */
const getList = async () => {
  loading.value = true;
  // 处理日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginRecordTime = dateRange.value[0];
    queryParams.value.endRecordTime = dateRange.value[1];
  } else {
    queryParams.value.beginRecordTime = undefined;
    queryParams.value.endRecordTime = undefined;
  }
  const res = await listDowntimeRecord(queryParams.value);
  downtimeRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 加载设备下拉（设备名称），使用 getRfidDeviceList 获取全量数据 */
const loadDeviceOptions = async () => {
    const res = await getRfidDeviceList({ isMarked: "1" });
    deviceOptions.value = res.data || [];
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  // 重置为当天时间范围
  initDefaultDateRange();
  queryFormRef.value?.resetFields();
  handleQuery();
}

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

onMounted(() => {
  // 初始化默认时间范围（当天），确保分表查询有依据
  initDefaultDateRange();
  getList();
  loadDeviceOptions();
});
</script>
