<template>
  <div class="layout-pd">
    <el-row>
      <!-- 操作区域 -->
      <el-col :xs="24">
        <el-card class="mt8" shadow="hover">
          <el-form :model="Data.Filter" @submit.stop.prevent>
            <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="Data.Filter.CompanyName" 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="Data.Filter.name" 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="Data.Filter.StationName" 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="Data.Filter.onlineStatus" placeholder="请选择在线状态">
                    <el-option v-for="(value, key) in selectList.Online" :key="key" :label="value" :value="value" />
                  </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="Data.time1" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="To" start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-form>

          <hr>

          <!-- 按钮 -->
          <el-row justify="space-between" class="submit-button" style="margin-bottom:-6px">
            <el-row>
              <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
              <el-button type="primary" icon="ele-RefreshRight" @click="onReset"> 重置 </el-button>
            </el-row>
          </el-row>
        </el-card>
      </el-col>
      <!-- 表格区域 -->
      <el-col :xs="24">
        <el-card class="my-fill mt8" shadow="hover">
          <el-table 
            ref="multipleTableRef" 
            v-loading="Data.loading" 
            stripe 
            :data="Data.tableModel" 
            row-key="id" 
            style="width: 100%">
            <el-table-column 
              v-for="column in Data.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 === 'cheatStatus'">
                  <StatusBox :status="row.cheatStatus" />
                </template>
                <template v-else-if="column.prop === 'alarming'">
                  <StatusBox :status="row.alarming" />
                </template>
                <!-- 监控微处理器编号 - 跳转页面1 -->
                <template v-else-if="column.prop === 'monitoringUUID'">
                  <el-link 
                    type="primary" 
                    :underline="false"
                    @click="handleMonitoringJump(row)"
                  >
                    {{ row[column.prop] }}
                  </el-link>
                </template>
                <!-- 加密显示屏编号 - 跳转页面2 -->
                <template v-else-if="column.prop === 'displayControlsUUID'">
                  <el-link 
                    type="primary" 
                    :underline="false"
                    @click="handleDisplayJump(row)"
                  >
                    {{ row[column.prop] }}
                  </el-link>
                </template>
                <!-- 编码器编号 - 跳转页面3 -->
                <template v-else-if="column.prop === 'encoderControlsUUID'">
                  <el-link 
                    type="primary" 
                    :underline="false"
                    @click="handleEncoderJump(row)"
                  >
                    {{ row[column.prop] }}
                  </el-link>
                </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="Data.total" :page-sizes="[5, 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" name="partsManagement/oilGun">
import { onMounted, reactive, watch, ref } from "vue";
import { useRouter } from "vue-router";
import { oilGunFilterModel_SearchFilter, oilGunFilterModel, PageInputoilGunFilterModel } from "/@/api/admin/reportManagement/oilGun/oilGunDto";
import { OilGunApi } from "/@/api/admin/reportManagement/oilGun/oilGunApi";
import StatusBox from "/@/components/StatusBox.vue";
import { useDynamicPageSize } from "/@/composables/useDynamicPageSize";
import { ElMessage } from "element-plus";

// 初始化路由实例
const router = useRouter();
const multipleTableRef = ref<any>(null);

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

/** 页面路径配置 */
const pagePaths = {
  monitoring: '/statement/taxcontrol/index', // 监控微处理器详情页路径
  display: '/statement/displayControl/index', // 加密显示屏详情页路径
  encoder: '/statement/encodercontrols/index' // 编码器详情页路径
};

/** 页面对象 */
const Data = reactive({
  time1: [] as string[],
  /** 选择框列表 */
  statusList: [] as any,
  supplierList: [] as any,
  /** 加载显示 */
  loading: false,
  /** 条件查询模块 */
  Filter: {
    /** 油枪号 */
    name: "",
    /** 加油站名称 */
    StationName: "",
    /** 石油公司 */
    CompanyName: "",
    /** 在线状态 */
    onlineStatus: "",
    /** 出厂开始的时间 */
    OutBeginTime: "",
    /** 出厂结束的时间 */
    OutEndTime: "",
    // 作弊状态
    cheatStatus: "",
    // 自锁状态
    alarming: ""
  } as oilGunFilterModel_SearchFilter,
  /** 表格信息 */
  tableModel: [] as Array<oilGunFilterModel>,
  /** 动态表头 */
  dynamicColumns: [
    { prop: 'name', label: '油枪号' },
    { prop: 'companyName', label: '石油公司' },
    { prop: 'stationName', label: '加油站名称' },
    { prop: 'fuelName', label: '油品' },
    { prop: 'alarming', label: '自锁' },
    { prop: 'fuelId', label: '油机ID' },
    { prop: 'onlineStatus', label: '在线状态' },
    { prop: 'cheatStatus', label: '作弊状态' },
    { prop: 'monitoringUUID', label: '监控微处理器编号' },
    { prop: 'displayControlsUUID', label: '加密显示屏编号' },
    { prop: 'encoderControlsUUID', label: '编码器编号' },
    { prop: 'productTime', label: '出厂时间' },
    { prop: 'soldTime', label: '安装时间' },
    { prop: 'supplierName', label: '加油机厂商' },
  ],
  /** 分页总数 */
  total: 0,
  /** 分页标识 */
  pageInput: {
    currentPage: 1,
    pageSize: 10,
  } as PageInputoilGunFilterModel,
})

/** 选择框列表 */
const selectList = reactive({
  Online: ["在线", "离线"],
  Device: [
    "启用",
    "备案",
    "维修",
    "出厂注册"
  ],
  Level: [1, 2, 3, 4, 5]
})

/** 监控微处理器编号跳转（传递UUID参数） */
const handleMonitoringJump = (row: oilGunFilterModel) => {
  if (!row.monitoringUUID) {
    ElMessage.warning("该记录没有监控微处理器编号，无法跳转");
    return;
  }
  router.push({
    path: pagePaths.monitoring,
    query: {
      queryParam: row.monitoringUUID, // 传递监控微处理器编号
      source: 'monitoring' // 标识来源
    }
  });
};

/** 加密显示屏编号跳转 */
const handleDisplayJump = (row: oilGunFilterModel) => {
  if (!row.displayControlsUUID) {
    ElMessage.warning("该记录没有加密显示屏编号，无法跳转");
    return;
  }
  router.push({
    path: pagePaths.display,
    query: {
      queryParam: row.displayControlsUUID,
      source: 'display'
    }
  });
};

/** 编码器编号跳转 */
const handleEncoderJump = (row: oilGunFilterModel) => {
  if (!row.encoderControlsUUID) {
    ElMessage.warning("该记录没有编码器编号，无法跳转");
    return;
  }
  router.push({
    path: pagePaths.encoder,
    query: {
      queryParam: row.encoderControlsUUID,
      source: 'encoder'
    }
  });
};

onMounted(() => {
  // 初始化分页大小
  Data.pageInput.pageSize = pageState.pageInput.pageSize;
  init();
})

// 条件查询
const init = async () => {
  Data.loading = true;
  try {
    const res: any = await new OilGunApi().getPage({ 
      ...Data.pageInput, 
      filter: Data.Filter 
    });
    Data.tableModel = res?.data?.list ?? [];
    Data.total = res?.data?.total ?? 0;
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('数据加载失败，请重试');
  } finally {
    Data.loading = false;
  }
}

const onQuery = () => {
  init();
}

/** 重置查询条件 */
const resetQuery = () => {
  Data.Filter = {
    name: "",
    StationName: "",
    CompanyName: "",
    onlineStatus: "",
    OutBeginTime: "",
    OutEndTime: "",
    cheatStatus: "",
    alarming: ""
  };
  Data.time1 = [];
  Data.pageInput.currentPage = 1;
  Data.pageInput.pageSize = 10;
}

/** 重置 */
const onReset = () => {
  resetQuery();
  init();
}

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

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

/** 监听时间变换 */
watch(() => Data.time1, (newVal) => {
  if (newVal && newVal.length === 2) {
    Data.Filter.OutBeginTime = newVal[0];
    Data.Filter.OutEndTime = newVal[1];
  } else {
    Data.Filter.OutBeginTime = "";
    Data.Filter.OutEndTime = "";
  }
})
</script>

<style scoped lang="scss">
.el-input,
.el-select {
  width: 240px;
}

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

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

/* 链接样式优化 */
::v-deep .el-link {
  cursor: pointer;
  &:hover {
    color: #4096ff;
    text-decoration: underline;
  }
}
</style>