<template>
  <div class="layout-pd">
    <el-row>
      <!-- 操作区域 -->
      <el-col :xs="24">
        <el-card class="mt8" shadow="hover">
          <el-form :model="state.filter" :inline="true" @submit.stop.prevent style="margin-bottom: -3vh;">
            <el-form-item prop="name" style="width: 100%">
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="石油公司">
                  <el-input v-model="state.filter.OilCompanyName" placeholder="请输入石油公司" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="编码器编号">
                  <el-input v-model="state.filter.SerialNumber" placeholder="请输入编码器编号" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="编码器状态">
                  <el-select v-model="state.filter.DeviceStatus" placeholder="请选择状态">
                    <el-option label="所有" :value="''"></el-option>
                    <el-option v-for="(value, key) in DeviceStatusEnum" :key="key" :label="value" :value="key" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="在线状态">
                  <el-select v-model="state.filter.onlineStatus" placeholder="请选择在线状态">
                    <el-option label="所有" :value="''"></el-option>
                    <el-option v-for="(value, key) in OnlineStatusEnum" :key="key" :label="value" :value="key" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="安装时间">
                  <el-date-picker
                    v-model="state.dateRange"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :clearable="false"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-form>

          <hr>

          <div class="my-flex my-flex-start">
            <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
            <el-button type="primary" icon="ele-RefreshRight" @click="onReset" style="margin-left: 10px;"> 重置 </el-button>
          </div>
        </el-card>
      </el-col>
      <!-- 表格区域 -->
      <el-col :xs="24">
        <el-card style="height: 70vh" class="my-fill mt8" shadow="hover">
          <el-table 
            ref="multipleTableRef" 
            v-loading="state.loading" 
            stripe 
            :data="state.tableModel" 
            row-key="id" 
            style="width: 100%">
            <el-table-column 
              v-for="column in state.dynamicColumns" 
              :key="column.prop" 
              :prop="column.prop" 
              :label="column.label">
              <template #default="{ row }">
                <template v-if="column.prop === 'onlineStatus'">
                  <StatusBox :status="row.onlineStatus" />
                </template>
                <template v-else-if="column.prop === 'deviceStatus'">
                  <StatusBox :status="row.deviceStatus" />
                </template>
                <template v-else>
                  {{ row[column.prop] }}
                </template>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 20px">
            <el-pagination
              v-model:currentPage="pageState.pageInput.currentPage"
              v-model:page-size="pageState.pageInput.pageSize"
              :total="state.total"
              :page-sizes="[10, 15, 20, 50, 100]"
              small
              background
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import eventBus from "/@/utils/mitt";
import { PageInput, encodercontrolsDto } from "/@/api/admin/reportManagement/encodercontrols/encodercontrolsdto";
import { Api } from "/@/api/admin/reportManagement/encodercontrols/encodercontrolsapi";
import StatusBox from "/@/components/StatusBox.vue";
import { useDynamicPageSize } from "/@/composables/useDynamicPageSize";
import { ElMessage } from "element-plus";

// 初始化路由实例（接收参数）
const route = useRoute();
const multipleTableRef = ref<any>(null);

// 使用组合式函数获取分页状态
const pageState = useDynamicPageSize(10, 15);

/** 状态枚举 */
enum OnlineStatusEnum {
  online = '在线',
  offline = '离线'
}

enum DeviceStatusEnum {
  unregister = "未备案",
  produce = "已生产",
  register = "已备案",
  bind = "已绑定油机",
  factory = "已出厂注册",
  enable = "已启用",
  disable = "维修中"
}

/** 数据对象 */
const state = reactive({
  dateRange: [] as [string, string], // 用于存储日期范围
  /** 加载显示 */
  loading: false,
  /** 条件查询模块 */
  filter: {
    // 开始日期
    startDate: "",
    // 结束日期
    endDate: "",
    // 石油公司
    OilCompanyName: "",
    // 序列号（编码器编号）
    SerialNumber: "",
    // 绑定加油机厂商
    BindingDispenserManufacturer: "",
    // 安全装置状态
    DeviceStatus: "",
    // 安装时间
    FixTime: "",
    // 在线状态
    onlineStatus: "",
    // 出厂时间
    SoldTime: "",
  },
  /** 表格信息 */
  tableModel: [] as encodercontrolsDto[],
  /** 动态表头 */
  dynamicColumns: [
    { prop: 'oilCompanyName', label: '石油公司' },
    { prop: 'stationName', label: '加油站名称' },
    { prop: 'serialNumber', label: '编码器编号' },
    { prop: 'bindingDispenserManufacturer', label: '加油机厂商' },
    { prop: 'dispenserNumber', label: '油机号' },
    { prop: 'nozzleNumber', label: '油枪号' },
    { prop: 'deviceStatus', label: '编码器状态' },
    { prop: 'onlineStatus', label: '在线状态' },
    { prop: 'fixTime', label: '安装时间' },
    { prop: 'soldTime', label: '出厂时间' },
  ],
  /** 分页总数 */
  total: 0,
  /** 分页标识 */
  pageInput: {
    currentPage: 1,
    pageSize: 10,
  } as PageInput,
})

/** 页面加载时接收参数并查询 */
onMounted(async () => {
  // 初始化分页大小
  state.pageInput.pageSize = pageState.pageInput.pageSize;

  // 从路由参数中获取编码器编号
  const { queryParam } = route.query;
  if (queryParam && typeof queryParam === 'string') {
    // 设置到序列号查询条件中
    state.filter.SerialNumber = queryParam;
  }

  // 触发查询
  await init();

  // 监听路由参数变化（防止同页面刷新参数丢失）
  watch(() => route.query, (newQuery) => {
    if (newQuery.queryParam && typeof newQuery.queryParam === 'string') {
      state.filter.SerialNumber = newQuery.queryParam;
      init(); // 参数变化时重新查询
    }
  }, { immediate: false });
});

/** 页条数变化 */
const onSizeChange = (val: number) => {
  state.pageInput.pageSize = val;
  init();
}

/** 页数变化 */
const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val;
  init();
}

/** 监听日期范围变化 */
watch(
  () => state.dateRange,
  (newVal) => {
    if (newVal && newVal.length === 2) {
      state.filter.startDate = newVal[0]; // 开始时间
      state.filter.endDate = newVal[1];   // 结束时间
    } else {
      state.filter.startDate = "";
      state.filter.endDate = "";
    }
  }
);

/** 条件查询 */
const onQuery = () => {
  init();
}

/** 重置查询条件 */
const onReset = () => {
  state.dateRange = [] as [string, string];
  state.filter = {
    startDate: "",
    endDate: "",
    OilCompanyName: "",
    SerialNumber: "",
    BindingDispenserManufacturer: "",
    DeviceStatus: "",
    FixTime: "",
    onlineStatus: "",
    SoldTime: "",
  };
  state.pageInput.currentPage = 1;
  init();
}

/** 初始化查询接口 */
const init = async () => {
  state.loading = true;
  try {
    // 调用编码器查询接口
    const res: any = await new Api().getList({
      ...state.pageInput,
      Filter: state.filter
    });
    state.total = res?.data?.total ?? 0;
    state.tableModel = res?.data?.list ?? [];
  } catch (error) {
    console.error('编码器查询失败:', error);
    ElMessage.error('数据加载失败，请重试');
  } finally {
    state.loading = false;
  }
};

// 清理事件监听
onBeforeMount(() => {
  eventBus.off('refreshView');
});
</script>

<style scoped lang="scss">
.my-flex {
  margin-top: 20px;
}

.el-input,
.el-select {
  width: 240px;
}

/* 输入框标签固定宽度 */
::v-deep .el-form-item__label {
  width: 14*5px + 12px;
  justify-content: start;
}

/* 数据表头样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #F6F6F6;
}
</style>