<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>
            <el-form-item prop="name" style="width: 100%">
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="4" class="mb20">
                <el-form-item label="加油站">
                  <el-input v-model="state.Filter.gasStation" placeholder="请输入加油站" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="4" class="mb20">
                <el-form-item label="报警类型">
                  <el-input v-model="state.Filter.alarmType" placeholder="请选择报警类型" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="4" class="mb20">
                <el-form-item>
                  <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
                  <!-- <el-button type="primary" icon="ele-Document" @click="onReset"> 导出 </el-button>
                  <el-button type="primary" @click="onReset"> 展开搜索 </el-button> -->
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-form>
        </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%"
            @row-click="onOilSdkRowClick" >
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <!-- <el-table-column type="selection" width="50"></el-table-column> -->
            <el-table-column v-for="column in state.dynamicColumns" :key="column.prop" :prop="column.prop" :label="column.label" />
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 20px">
            <el-pagination
              v-model:currentPage="state.pageInput.CurrentPage"
              v-model:page-size="state.pageInput.PageSize"
              :total="state.total"
              :page-sizes="[10000, 20000, 50000, 100000]"
              small
              background
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <EditDialog ref="editDialogRef" />
    <AuditDialog ref="auditDialogRef" />
  </div>

</template>

<script setup lang="ts" name="authorize/fuelingsdk">
import {defineAsyncComponent, onMounted, reactive, ref, watch, onBeforeMount,getCurrentInstance} from "vue";
import {OilSdkAuthorDto, oilSdkFilterModel, oilSdkTableModel,oilSdkAuthorPageOutput,FueilingSdkAuthInput} from "/@/api/admin/deviceAuthorization/oilSdkAuthorDto";
import {OilEngineDetailsApi} from "/@/api/admin/reportManagement/oilEngineDetails/oilEngineDetailsApi";
import eventBus from "/@/utils/mitt";
import * as ExcelJS from 'exceljs';
import * as FileSaver from 'file-saver';
import { ElTable } from 'element-plus'
import router from "/@/router";
/**引入组件*/
const EditDialog = defineAsyncComponent(() => import('/src/views/admin/authorize/fuelingsdk/components/form-edit.vue'))
const AuditDialog = defineAsyncComponent(() => import('/src/views/admin/authorize/fuelingsdk/components/form-audit.vue'))

const editDialogRef = ref()
const auditDialogRef = ref()

const multipleTableRef=ref<InstanceType<typeof ElTable>>()
const { proxy } = getCurrentInstance() as any

/**更多报警页面对象 */
const state = reactive({
  time:'',
  /**加载显示 */
  loading: false,
  /**条件查询模块 */
  Filter: {
    /**油机id */
    fuelId:"",
    /**油站名称 */
    gasStation: "",
    /**报警类型 */
    alarmType: "",
  },
  /**表格信息 */
  tableModel: [],
  /**动态表头 */
  dynamicColumns: [
    { prop: 'name', label: '油机号' },
    { prop: 'gasStation', label: '加油站' },
    { prop: 'serialNumber', label: '序列号' },
    { prop: 'alarmSource', label: '报警来源' },
    { prop: 'alarmType', label: '报警类型' },
    { prop: 'alarmDescription', label: '报警描述' },
    { prop: 'createdDate', label: '报警时间' }
  ],
  /**分页标识 */
  pageInput:{
    CurrentPage: 1,
    PageSize: 10000,
  },
  /**分页总数 */
  total: 0,
})

/**初始化 */
const init = async () => {
  state.loading = true
  const query = flattenObject({ Filter: state.Filter})
  state.Filter.fuelId=router.currentRoute.value.params.id
  const res:any = await new OilEngineDetailsApi().getAlarmHistoryDto({...state.pageInput,filter:state.Filter}).catch(() => {
    state.loading = false
  })
  state.tableModel = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}

onMounted(() => {
  init()
  eventBus.off('refreshView')
  eventBus.on('refreshView', async () => {
    init()
  })
})

onBeforeMount(() => {
  eventBus.off('refreshView')
})

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

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

/**重置查询条件 */
const resetQuery = () => {
  state.Filter.name = ''
  state.Filter.gasStation = ''
  state.Filter.alarmType = ''
}

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

/**添加*/
const onAdd = () => {
  editDialogRef.value.openDialog()
}

/**页条数变化*/
const onSizeChange = () => {
  init()
}

/**页数变化*/
const onCurrentChange = () =>{
  init()
}

/**批量导入*/
const uploadFiles = () =>{

}

/**导出表格*/
const exportTable = async(data:any[],columns:{ prop: string, label: string }[]) =>{
  // 创建一个新的工作簿
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('Sheet1');

// 添加表头（不包括名为 "guid" 的表头列）
  const headers = columns
    .filter(column => column.prop !== 'guid')  // 过滤掉名为 "guid" 的表头列
    .map(column => column.label);
  const headerRow = worksheet.addRow(headers);

  // 添加数据行（不包括 "guid" 的数据列）
  data.forEach((item) => {
    const row = columns
      .filter(column => column.prop !== 'guid')  // 过滤掉名为 "guid" 的数据列
      .map(column => item[column.prop]);
    worksheet.addRow(row);
  });

// 设置数据行样式
  worksheet.eachRow({ includeEmpty: true }, row => {
    row.eachCell(cell => {
      // 设置单元格样式
      cell.font = { bold: false }; // 设置字体为普通样式
      cell.border = { top: { style: 'thin' }, bottom: { style: 'thin' } }; // 设置上下边框为细线
      cell.alignment = { vertical: 'middle', horizontal: 'center' }; // 将内容垂直居中、水平居中
      // 设置单元格高度
      row.height = 25; // 设置每一行的高度为 25
    });
  });

  // 设置表头样式
  headerRow.font = { bold: true }; // 设置字体为粗体

  // 设置整个表格的边框样式
  worksheet.eachRow({ includeEmpty: true }, row => {
    row.eachCell(cell => {
      if (cell.row === 1) {
        // 设置表头单元格的边框为细线
        cell.border = { left: { style: 'thin' }, right: { style: 'thin' }, top: { style: 'thin' }, bottom: { style: 'thin' } };
        // 设置表头单元格背景颜色
        cell.fill={type: 'pattern',pattern: 'solid',fgColor: { argb: '409eff' }}
      } else {
        // 设置数据行单元格的边框为细线
        cell.border = { left: { style: 'thin' }, right: { style: 'thin' }, bottom: { style: 'thin' } };
      }
    });
  });

  // 调整单元格大小
  worksheet.columns.forEach(column => {
    column.width = 25; // 设置每列的宽度为 25
  });


  // 生成 Excel 文件
  const buffer = await workbook.xlsx.writeBuffer();

  // 将文件保存到本地
  const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  FileSaver.saveAs(blob, '油气SDK授权数据.xlsx');
}

/**将Filter对象成.的连接方式*/
const flattenObject = (obj, parentKey = '') => {
  const result = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const newKey = parentKey ? `${parentKey}.${key}` : key;
      if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
        const flattened = flattenObject(obj[key], newKey);
        Object.assign(result, flattened);
      } else {
        result[newKey] = obj[key];
      }
    }
  }

  return result;
}

/**编辑弹窗 */
const editTableData = (row) => {
  editDialogRef.value.openDialog(row)
}
/**审核弹窗 */
const onAuditRecord=()=>{
  const selectionRows = multipleTableRef.value!.getSelectionRows() as FueilingSdkAuthInput
  //console.log(selectionRows)

  if (!((selectionRows.length as number) > 0)) {
    proxy.$modal.msgWarning('请选择要审核的数据')
    return
  }else{
    auditDialogRef.value.openDialog(selectionRows)
  }

}
const onOilSdkRowClick=(row: FueilingSdkAuthInput)=> {
  // TODO: improvement typing when refactor table
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-expect-error
  multipleTableRef.value!.toggleRowSelection(row, undefined)
}
</script>

<style scoped lang="scss">
.my-el-link {
  font-size: 14px;
}
.el-form .el-col.mb20 {
  margin: 0 !important;
}
.el-input, .el-select {
  width: 240px;
}
</style>
