<template>
  <div class="layout-pd" >
    <el-row>
      <!--操作-->
      <el-col :xs="24" >
        <el-card class="mt8"  shadow="hover" >
          <el-form :model="sdkData.Filter" :inline="true" @submit.stop.prevent>
            <el-form-item prop="name" style="width: 100%">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="油站名称">
                  <el-input v-model="sdkData.Filter.OilStation"  placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="项目名称">
                  <el-input v-model="sdkData.Filter.Project" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="SN">
                  <el-input v-model="sdkData.Filter.SN" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="授权码">
                  <el-input v-model="sdkData.Filter.Key" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item label="失效时间">
                  <el-date-picker
                    v-model="sdkData.time"
                    type="datetimerange"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="To"
                    start-placeholder="Start date"
                    end-placeholder="End date"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
                <el-form-item>
                  <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
                  <el-button type="primary" icon="ele-RefreshRight" @click="onReset"> 重置 </el-button>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-form>
          <div class="my-flex my-flex-end" >
            <el-button  type="primary" icon="ele-CirclePlus" @click="onAdd"> 添加 </el-button>
            <el-button type="primary" icon="ele-Tickets" @click="onAuditRecord()"> 审核 </el-button>
            <el-button type="primary" icon="ele-UploadFilled" @click="uploadFiles"> 批量导入 </el-button>
            <el-button type="primary" icon="ele-Document" @click="exportTable(sdkData.tableModel,sdkData.dynamicColumns)"> 导出表格 </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="sdkData.loading"
            stripe :data="sdkData.tableModel"
            row-key="id"
            style="width: 100%"
            @row-click="onOilSdkRowClick" >
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column v-for="column in sdkData.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="100">
              <template #default="{ row }">
                <el-link
                  class="my-el-link mr12 ml12"
                  type="primary"
                  icon="ele-Edit"
                  size="small"
                  @click="editTableData(row)"
                  :underline="false"
                  target="_blank"
                >编辑</el-link>
                <!-- <el-link
                  class="my-el-link mr12 ml12"
                  v-if="showAudit(row)"
                  type="primary"
                  icon="ele-Tickets"
                  size="small"
                  @click="onAuditRecord(row)"
                  :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="sdkData.pageInput.CurrentPage"
              v-model:page-size="sdkData.pageInput.PageSize"
              :total="sdkData.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 {OilSdkAuthorAPI} from "/@/api/admin/deviceAuthorization/oilSdkAuthor";
import type {pageInput} from "/@/api/admin/shareDto/shareDto";
import eventBus from "/@/utils/mitt";
import * as ExcelJS from 'exceljs';
import * as FileSaver from 'file-saver';
import { ElTable } from 'element-plus'
/**引入组件*/
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

/**sdk授权页面对象 */
const sdkData = reactive({
  time:'',
  /**加载显示 */
  loading: false,
  /**条件查询模块 */
  Filter: {
    /**油站名称 */
    OilStation: "",
    /**项目名称 */
    Project: "",
    /**设备SN */
    SN: "",
    /**授权码*/
    Key: "",
    /**开始的时间 */
    BeginTime: null,
    /**开始的时间 */
    EndTime: null,
  } as oilSdkFilterModel,
  /**表格信息 */
  tableModel: [] as oilSdkTableModel,
  /**动态表头 */
  dynamicColumns: [
    { prop: 'guid', label: '编号' },
    { prop: 'oilStation', label: '油站名称' },
    { prop: 'projectName', label: '项目名称' },
    { prop: 'sn', label: '设备SN号' },
    { prop: 'key', label: '授权码' },
    { prop: 'expiedTime', label: '失效时间' },
    { prop: 'state', label: '状态' },
    { prop: 'remark', label: '备注' },
  ],
  /**分页标识 */
  pageInput:{
    CurrentPage: 1,
    PageSize: 10000,
  } as pageInput,
  /**分页总数 */
  total: 0,
} as OilSdkAuthorDto)

/**初始化 */
const init = async () => {
  sdkData.loading = true
  const query = flattenObject({ Filter: sdkData.Filter})
  const res:any = await new OilSdkAuthorAPI().getPageData({...sdkData.pageInput, ...query}).catch(() => {
    sdkData.loading = false
  })
  sdkData.tableModel = res?.data?.list ?? []
  sdkData.total = res?.data?.total ?? 0
  sdkData.loading = false
}

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

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

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

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

/**重置查询条件 */
const resetQuery = () => {
  sdkData.Filter.OilStation = ''
  sdkData.Filter.Project = ''
  sdkData.Filter.SN = ''
  sdkData.Filter.Key = ''
  sdkData.Filter.BeginTime =  ''
  sdkData.Filter.EndTime = ''
  sdkData.time = ''
  sdkData.pageInput.CurrentPage = 1
}

/**重置 */
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: 12px;
}
.el-form .el-col.mb20 {
  margin: 0 !important;
}
.el-input, .el-select {
  width: 240px;
}
</style>
