<template>
  <div class="table-page">
    <div class="table-page-content">
      <div class="right-table">
        <div class="full-page bg">
          <!--          <div class="search-box">-->
          <!--            <SearchCommon :optionList="optionList" @search="handleSearch" />-->
          <!--          </div>-->
          <div class="main-table-container" style="margin: 0 !important">
            <div class="table-container" style="padding: 20px">
              <div ref="tableRef" class="table-content">
                <div ref="btnPanel" class="btn-box">
                  <el-button
                    class="btn btn-plus"
                    icon="el-icon-plus"
                    size="small"
                    type="primary"
                    @click="
                  changePage('AddPage', {
                    eventName,
                    eventId,
                    eventTime,
                    eventDetail,
                    roadName,
                    roadId,
                    direction,
                    lat,
                    lng,
                    pegVal,
                  })
                "
                  >
                    添加
                  </el-button>
                  <el-button
                    :disabled="!currentDataDel.length"
                    class="btn btn-delete"
                    icon="el-icon-delete"
                    plain
                    size="small"
                    type="danger"
                    @click="handleDelete()"
                  >
                    删除
                  </el-button>
                  <el-button
                    class="btn btn-plus"
                    icon="el-icon-download"
                    size="small"
                    type="warning"
                    @click="exportWord"
                  >
                    导出
                  </el-button>
                </div>
                <el-table
                  ref="multipleSelection"
                  v-loading="tableLoading"
                  :data="tableData"
                  :default-sort="getSorterDirection(params, true)"
                  :max-height="tableMaxHeight"
                  border
                  class="table-list"
                  element-loading-background="rgba(10 ,38 ,61, 0.9)"
                  row-key="id"
                  stripe
                  @select="handleSelection"
                  @row-dblclick="handleDbClick"
                  @selection-change="handleSelectionChange"
                >
                  <!--             @row-dblclick="handleDbClick"     -->
                  <el-table-column align="center" type="selection" width="55" />
                  <el-table-column
                    :index="
                      (index) =>
                        index +
                        1 +
                        (params.pageBean.page - 1) * params.pageBean.pageSize
                    "
                    align="center"
                    label="序号"
                    type="index"
                    width="100"
                  />

                  <el-table-column
                    :formatter="({eventName}) => eventName || '-'"
                    align="center"
                    label="报告标题"
                    min-width="100"
                    prop="eventName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="
                      ({reportType}) =>
                        dictionaryEscape('jzsb-jzlx', reportType + '')
                    "
                    align="center"
                    label="报告类型"
                    min-width="100"
                    prop="reportType"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({uploadUserName}) => uploadUserName || '-'"
                    align="center"
                    label="上报人员"
                    min-width="100"
                    prop="uploadUserName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({uploadTime}) => uploadTime || '-'"
                    align="center"
                    label="上报时间"
                    min-width="70"
                    prop="uploadTime"
                    show-overflow-tooltip
                  />
                </el-table>
                <pagination
                  ref="paginationPanel"
                  :pageResult="params.pageBean"
                  style="margin-top: 10px"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <report-dialog
      ref="reportDialog"
      :isShow.sync="reportDialog"
      :videoData="videoData"
    ></report-dialog>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import SearchCommon from '@/components/SearchCommon/index.vue'
import {dictionaryEscape} from '@/utils/dictionary'
import pagination from '@/components/SuperPagination/index.vue'
import {TableMixin} from '@/mixins/tableMixin'
import {exportList, tableData, tableDelete} from '@/api/patrolAndRescue/videoPatrol/videoInspectionResults'
import ReportDialog from '../ReportDialog/index.vue'
import {getSorterDirection, setQueryValue} from '@/utils/requestWrappers'

export default {
  name: 'AbnormalListPage',
  mixins: [TableMixin],
  components: {
    pagination,
    SearchCommon,
    ReportDialog
  },
  data() {
    return {
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      btnLoading: false,
      tableData: [],
      reportDialog: false,
      videoData: {},
      optionList: [],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {
            group: 'quick',
            operation: 'EQUAL',
            property: 'eventId',
            relation: 'AND',
            value: ''
          },
          // {operation: 'EQUAL', property: 'eventId'},
          {operation: 'LIKE', property: 'video_name_'},
          // {operation: 'IN', property: 'inspecetStatus', value: [1]},
          {operation: 'IN', property: 'taskStatus'}
        ],
        sorter: [{direction: '', property: ''}]
      },
      eventId: '',
      eventTime: '',
      roadName: '',
      direction: '',
      roadId: '',
      eventName: '',
      eventDetail: '',
      lat: '',
      lng: '',
      pegVal: '',
      isUpdata: false
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  mounted() {
    this.pubSub = PubSub.subscribe('AbnormalListPage', (_, data) => {
      if (data.id) {
        this.eventId = data.id
        setQueryValue(this.params, 'taskId', data.id || '') //将选中的树节点的 id 设置为查询参数的一部分
      }
      // 设置这些值
      this.lat = data.lat || ''
      this.lng = data.lng || ''
      this.pegVal = data.pegSVal || ''
      this.eventName = data.eventName || ''
      this.eventTime = data.eventTime || ''
      this.eventDetail = data.memo || ''
      this.roadId = data.roadId || ''
      this.roadName = data.roadName || ''
      this.direction = data.direction || ''
      this.isUpdata = true
      this.loadData()
    })
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    handleReport(row) {
      this.videoData = row
      this.reportDialog = true
    },
    openPage() {
      if (this.isUpdata) {
        this.loadData()
      }
    },
    //获取数据
    async loadData() {
      try {
        this.tableLoading = true

        const queryother = {
          querys: [
            {
              group: 'main',
              operation: 'EQUAL',
              parentGroup: '',
              property: 'eventId',
              relation: 'AND',
              value: this.eventId
            }
          ]
        }
        const responce = await tableData(queryother)
        this.params.pageBean.total = responce.total
        this.tableData = responce.rows
      } finally {
        this.isUpdata = false
        this.tableLoading = false
      }
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      this.isUpdata = true
      if (!pageName) return

      this.$emit(
        'changePage',
        pageName,
        (_) => {
          PubSub.publish(pageName, row)
        },
        row.id ? '编辑' : '新增'
      )
    },
    // 删除
    handleDelete(row) {
      this.clickTimer = true
      this.$confirm('确定删除选中上报事件吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let ids = row ? row.id : this.currentDataDel.join()
          let {state, message} = await tableDelete(ids)
          if (state) {
            this.$message.success(`上报事件删除成功`)
            const {page, pageSize, total} = this.params.pageBean
            const totalPages = Math.ceil(total / pageSize) // 计算总页数
            if (totalPages > 1 && page === totalPages) {
              if (this.tableData.length === 1) {
                // 当前页只有一条数据
                this.params.pageBean.page -= 1 // 返回前一页
              }
            }
            await this.loadData()
          } else {
            this.$message.error(message)
          }
        })
        .catch((_) => _)
    },
    //修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      this.changePage('AddPage', row)
    },
    //导出
    async exportWord() {
      this.btnLoading = true
      try {
        // 获取当前选中的行ID（假设你已经实现了多选功能）
        const selectedIds =
          this.currentDataDel.length > 0
            ? this.currentDataDel
            : this.tableData.map((item) => item.id)

        // 如果没有选中任何数据且表格也没有数据
        if (selectedIds.length === 0) {
          this.$message.warning('请选择要导出的数据')
          return
        }
        const queryParams = {
          groupRelation: 'AND',
          groupTree: {},
          pageBean: {
            page: 1,
            pageSize: 10,
            showTotal: true
          },
          params: {},
          querys: [
            {
              group: 'main',
              operation: 'IN',
              parentGroup: '',
              property: 'ep.id_',
              relation: 'AND',
              value: selectedIds
            }
          ],
          sorter: [
            {
              direction: 'ASC',
              property: ''
            }
          ]
        }
        // await exportList(queryParams)
        const response = await exportList(queryParams)

        // 创建Blob对象
        const blob = new Blob([response], {type: 'application/zip'})

        // 创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl

        // 设置文件名（可以根据需要调整）
        const fileName =
          selectedIds.length === 1
            ? `事件报告_${selectedIds[0]}_${new Date().getTime()}.zip`
            : `批量事件报告_${new Date().getTime()}.zip`
        link.setAttribute('download', fileName)

        // 触发下载
        document.body.appendChild(link)
        link.click()

        // 清理
        document.body.removeChild(link)
        window.URL.revokeObjectURL(downloadUrl)
        this.$message.success('导出成功')
      } catch (error) {
        this.$message.error('导出失败')
      } finally {
        this.btnLoading = false
      }
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
.table-page {
  .basis {
    min-width: 400px !important;
  }
}
</style>
