<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 style="margin-bottom:-20px;">
            <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="油机ID">
                  <el-input v-model="Data.Filter.fuelld" placeholder="请输入油机ID" 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.gasStation" 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.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-input v-model="Data.Filter.alarmSource" 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.alarmType" 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.alarmDevice" 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-date-picker v-model="Data.time" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="To" start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item>
                </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-button 
                 v-auth="'api:admin:file:upload-file'" 
                 type="primary" 
                 icon="ele-Upload" 
                 @click="handlePushRules"
               >
                 执行推送规则
               </el-button>              
          </el-row>
        </el-row>

        </el-card>
      </el-col>
      <!--表格-->
      <el-col :xs="24">
        <el-card class="my-fill mt8" shadow="hover">
          <!-- 修改表格引用，添加ref -->
          <el-table ref="tableRef" v-loading="Data.loading" stripe :data="Data.tableModel"
            style="width: 100%;overflow: hidden;">
            <!-- 多选框 -->
            <el-table-column type="selection" width="55" fixed="left"></el-table-column>
            <el-table-column v-for="column in Data.dynamicColumns" :key="column.prop" :prop="column.prop"
              :label="column.label" />
                <el-table-column label="操作" fixed="right" header-align="center" align="center" class="right-operation"
                width="150">
                <template #default="{ row }">
    <el-link class="my-el-link mr12 ml12" :href="row.linkUrl" type="primary" icon="ele-Download" size="small"
      :underline="false" target="_blank" @click="toList">报警推送记录</el-link>
      <el-link class="my-el-link mr12 ml12" :href="row.linkUrl" type="primary" icon="ele-Edit" size="small"
      :underline="false" target="_blank" @click="toPage(row)">油机详情</el-link>
      <el-link class="my-el-link mr12 ml12" :href="row.linkUrl" type="primary" icon="ele-InfoFilled" size="small"
      :underline="false" target="_blank">诊断说明</el-link>
                </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, 25, 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="authorize/fuelingsdk">
import { onMounted, reactive, ref, watch } from "vue";
import { ElMessage, ElTable } from 'element-plus'
import { alarmFilterModel_SearchFilter, alarmFilterModel, PageInputAlarmFilterModel, PushRulesQuery } from "/@/api/admin/reportManagement/alarm/alarmDto";
import { AlarmApi } from "/@/api/admin/reportManagement/alarm/alarmApi";
import { useDynamicPageSize } from "/@/composables/useDynamicPageSize";
import router from "/@/router";
import { PushRulesApi } from "/@/api/admin/reportManagement/alarm/alarmApi";
import { ResultOutputBoolean } from "/@/api/admin/reportManagement/alarm/alarmDto";

const pushRulesApi = new PushRulesApi();
const tableRef = ref<InstanceType<typeof ElTable>>(); // 添加表格引用

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

/**页面对象 */
const Data = reactive({
  time: '',
  /**加载显示 */
  loading: false,
  /**条件查询模块 */
  Filter: {
    /**油机id */
    fuelld: "",
    /**加油站 */
    gasStation: "",
    /**油机号*/
    name: "",
    /**序列号*/
    serialNumber: "",
    /**报警来源 */
    alarmSource: "",
    /**报警类型 */
    alarmType: "",
    /**报警描述 */
    alarmDescription: "",
    /**报警设备	 */
    alarmDevice: "",
    /** 油枪*/
    nozzleControlName: "",
    /**创建开始的时间 */
    CreateBeginTime: "",
    /**创建结束的时间 */
    CreateEndTime: "",
  } as alarmFilterModel_SearchFilter,
  /**表格信息 */
  tableModel: [] as Array<alarmFilterModel>,
  /**动态表头 */
  dynamicColumns: [
    // { prop: 'fuelld', label: '油机id' },
    { prop: 'gasStation', label: '加油站名称' },
    { prop: 'name', label: '油机号' },
    { prop: 'serialNumber', label: '序列号' },
    { prop: 'alarmSource', label: '报警来源' },
    { prop: 'alarmType', label: '报警类型' },
    { prop: 'alarmDescription', label: '报警描述' },
    { prop: 'alarmDevice', label: '报警设备' },
    { prop: 'nozzleControlName', label: '油枪' },
    { prop: 'createdDate', label: '报警时间' },
    { prop: '', label: '诊断说明' },
    { prop: '', label: '是否推送' },

    // { prop: 'alarmHistoryID', label: '报警历史ID' },
  ],
  /**分页标识 */
  pageInput: {
    currentPage: 1,
    pageSize: 15,
  } as PageInputAlarmFilterModel,
  /**分页总数 */
  total: 0,
})

/**初始化 */
const init = async () => {
  Data.loading = true
  const res: any = await new AlarmApi().getPage({ ...Data.pageInput, filter: Data.Filter })
  Data.tableModel = res?.data?.list ?? []
  Data.total = res?.data?.total ?? 0
  Data.loading = false
}

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


/**
 * 监听时间变换
 */
watch(() => Data.time, (newVal) => {
  if (newVal.length === 0) {
    return
  }
  Data.Filter.CreateBeginTime = newVal?.[0].toString()
  Data.Filter.CreateEndTime = newVal?.[1].toString()
})

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

/**重置查询条件 */
const resetQuery = () => {
  Data.Filter.fuelld = ''
  Data.Filter.gasStation = ''
  Data.Filter.name = ''
  Data.Filter.serialNumber = ''
  Data.Filter.alarmSource = ''
  Data.Filter.alarmType = ''
  Data.Filter.alarmDescription = ''
  Data.Filter.alarmDevice = ''
  Data.Filter.nozzleControlName = ''
  Data.Filter.CreateBeginTime = ''
  Data.Filter.CreateEndTime = ''
  Data.time = ''
}

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

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

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

const toPage = (row: {fuelId: any; 
}) => {
  router.push({ path: `/statement/${row.fuelId}` })
}

const toList = () =>{
  router.push({ path:`/authorize/statement/alarmQuery`})
}

/**
 * 执行推送规则
 */
const handlePushRules = async () => {
  const selection = tableRef.value?.getSelectionRows() || [];

  if (selection.length === 0) {
    ElMessage.warning('请至少选择一行数据');
    return;
  }

  const alarmHistoryIDs: string[] = selection
    .map(row => row.alarmHistoryID)
    .filter((id): id is string => !!id);

  if (alarmHistoryIDs.length === 0) {
    ElMessage.warning('所选项中没有有效的报警历史ID');
    return;
  }

  const idsString = alarmHistoryIDs.join(',');

  try {
    const res = await pushRulesApi.executePushRuleImmediately(undefined, {
      query: {
        alarmHistoryID: idsString,
      },
    });

    if (res.success && res.data) {
      ElMessage.success(`推送成功`);
    } else {
      ElMessage.error(`推送失败：${res.msg || '未知错误'}`);
    }
  } catch (error: any) {
    console.error('推送失败', error);
    ElMessage.error('报警推送过程中发生异常');
  }
};

</script>

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

/* 输入框标签固定四个字符宽度 */
::v-deep .el-form-item__label {
  // 字体大小14，4个字符，12px右间距
  width: 14*4px+12px;
  justify-content: start;
}

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