<template>
  <div class="table-page">
    <div class="table-page-content">
      <div class="left-tree">
        <tree-side
          ref="treeSide"
          :dataLoading="treeLoading"
          :default-expand-all="false"
          :defaultProps="defaultProps"
          :tabList="['组织路段树']"
          :treeData="treeData"
          isDeselect
          @currentChange="currentChange"
        ></tree-side>
      </div>
      <div class="right-table">
        <div class="full-page bg">
          <div class="search-box">
            <div class="search-box-combination">
              <div class="search-box-label">报案时间：</div>
              <div>
                <el-date-picker
                  v-model="params.querys[4].value"
                  end-placeholder="报案时间"
                  range-separator="至"
                  start-placeholder="报案时间"
                  style="width: 360px"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="datePickerChange"
                >
                </el-date-picker>
              </div>
              <SearchCommon :optionList="optionList" @search="handleSearch" />
            </div>
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <div ref="btnPanel" class="btn-box">
                <el-button
                  :disabled="multiSelectData.length === 0"
                  :loading="downloadLoading"
                  class="btn btn-plus"
                  icon="el-icon-download"
                  size="small"
                  type="success"
                  @click="exportData"
                >档案导出
                </el-button>
              </div>
              <div ref="tableRef" class="table-content">
                <el-table
                  ref="multipleSelection"
                  v-loading="tableLoading"
                  :data="tableData"
                  :default-sort="{ prop: 'rescueTime', order: 'descending' }"
                  :max-height="tableMaxHeight"
                  border
                  class="table-list"
                  element-loading-background="rgba(10 ,38 ,61, 0.9)"
                  row-key="id"
                  stripe
                  @select="handleSelection"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column align="center" type="selection" width="55" />
                  <el-table-column
                    align="center"
                    label="序号"
                    type="index"
                    width="60"
                  />
                  <el-table-column
                    align="center"
                    label="救援单号"
                    min-width="120"
                    prop="rescueNo"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="报案电话"
                    min-width="80"
                    prop="rescueTel"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="报案时间"
                    min-width="120"
                    prop="rescueTime"
                    show-overflow-tooltip
                    sortable
                  />
                  <el-table-column
                    align="center"
                    label="救援点位桩号"
                    min-width="100"
                    prop="pegVal"
                    show-overflow-tooltip
                  />
                  <!-- <el-table-column
                    align="center"
                    label="报案来源"
                    min-width="80"
                    prop="rescueSrc"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      {{ dictionaryEscape('baly', row.rescueSrc + '') || '-' }}
                    </template>
                  </el-table-column> -->
                  <el-table-column
                    align="center"
                    label="所属路段"
                    min-width="80"
                    prop="roadName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="救援类型"
                    min-width="80"
                    prop="rescueType"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      {{ dictionaryEscape('jylx', row.rescueType + '') || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="开始站"
                    min-width="80"
                    prop="startPatrolName"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="结束站"
                    min-width="80"
                    prop="endPatrolName"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="处置状态"
                    min-width="80"
                    prop="status"
                    show-overflow-tooltip
                  >
                  <template v-slot="{row}">
                      <el-link
                        :type="
                          row.status === 1
                            ? 'danger'
                            : row.status === 0
                            ? 'success'
                            : 'info'
                        "
                        :underline="false"
                      >
                        {{ dictionaryEscape('sjczzt',  String(row.status)) || '-' }}
                      </el-link>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="救援状态"
                    prop="rescueStatus"
                    width="100"
                  >
                    <template v-slot="{row}">
                      <el-link
                        :type="
                          row.rescueStatus < 2
                            ? 'warning'
                            : row.rescueStatus == '2'
                            ? 'primary'
                            : row.rescueStatus == '4' || row.rescueStatus == '5'
                            ? 'success'
                            : 'danger'
                        "
                        :underline="false"
                      >
                        {{ dictionaryEscape('jy_zt',  String(row.rescueStatus)) || '-' }}
                      </el-link>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    min-width="80"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <!--                      <el-link-->
                      <!--                        v-methodauth="rescueInquiryEdit"-->
                      <!--                        :underline="false"-->
                      <!--                        type="primary"-->
                      <!--                        @click="handleEditPage(row)"-->
                      <!--                      >-->
                      <!--                        编辑-->
                      <!--                      </el-link>-->
                      <el-link
                        :underline="false"
                        type="primary"
                        @click="handleDetailPage(row)"
                      >
                        详情
                      </el-link>
                      <el-link
                        :underline="false"
                        type="primary"
                        @click="filePreviewChange(row)"
                      >
                        预览
                      </el-link>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination
                  ref="paginationPanel"
                  :pageResult="params.pageBean"
                  style="margin-top: 10px"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <FileDialog
      :file-info="fileInfo"
      :is-show.sync="fileShowDialog"
    />

    <!--  目录树修改新增弹层  -->
    <tree-dialog
      :id.sync="treeItemId"
      :is-show.sync="treeDialog"
      :parent-id.sync="treeItemParentId"
      @catalogChange="catalogChange"
    />
  </div>
</template>

<script>
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {refineRequestBody, setQueryValue} from '@/utils/requestWrappers'
import pagination from '@/components/SuperPagination/index.vue'
import {TableMixin} from '@/mixins/tableMixin'
import treeSide from '@/components/treeSide/index.vue'
import SearchCommon from '@/components/SearchCommon/index.vue'
import {exportDataFile, tableData} from '@/api/patrolAndRescue/obstacleClearingRescue/rescueInquiry'
import TreeDialog from './components/TreeDialog/index.vue'
import PubSub from 'pubsub-js'
import moment from 'moment'
import FileDialog from '@/views/patrolAndRescue/obstacleClearingRescue/RescueInquiry/components/FileDialog/index.vue'
import {getTree} from '@/api/tree'

export default {
  name: 'TablePage',
  components: {
    FileDialog,
    TreeDialog,
    pagination,
    treeSide,
    SearchCommon
  },
  mixins: [TableMixin],
  data() {
    return {
      fileInfo: {},
      fileShowDialog: false,
      multiSelectData: [],
      downloadLoading: false,
      pubSub: null,
      tableMaxHeight: '600px',
      loading: false,
      tableLoading: false,
      treeData: [], //左边树
      tabList: ['政策法规'], //左边tab
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      currentDataDel: [],
      optionList: [
        {title: '救援单号', prop: ['RESCUE_NO_'], type: 'input', default: true},
        {
          title: '救援类型',
          prop: ['RESCUE_TYPE_'],
          type: 'select',
          option: getDictionaryByCode('jylx'),
          multiple: true
        },
        {
          title: '报案来源',
          prop: ['RESCUE_SRC_'],
          type: 'select',
          option: getDictionaryByCode('baly'),
          multiple: true
        },
        {
          title: '处置状态',
          prop: ['STATUS_'],
          type: 'select',
          option: getDictionaryByCode('sjczzt'),
          multiple: true
        },
        {
          title: '救援状态',
          prop: ['RESCUE_STATUS_'],
          type: 'select',
          option: getDictionaryByCode('jy_zt'),
          multiple: true
        }
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 'roadId'},
          {operation: 'IN', property: 'RESCUE_TYPE_', value: ''},
          {operation: 'IN', property: 'RESCUE_SRC_', value: ''},
          {operation: 'EQUAL', property: 'RESCUE_NO_', value: ''},
          {
            operation: 'BETWEEN',
            property: 'rescue_time_',
            value: [
              moment()
                .startOf('month')
                .format('YYYY-MM-DD HH:mm:ss'),
              moment()
                .endOf('month')
                .format('YYYY-MM-DD HH:mm:ss')
            ]
          },
          {operation: 'IN', property: 'RESCUE_STATUS_', value: ''},
          {operation: 'IN', property: 'STATUS_', value: ''}
        ],
        sorter: [{property: 'createTime', direction: 'DESC'}] // 排序字段
      },
      treeDialog: false, // 科目信息弹层
      treeItemId: '', // 树形目录id
      treeItem: {}, // 树形节点选中对象
      treeItemParentId: '', // 树形目录父级id
      rescueInquiryEdit: ''
    }
  },
  created() {
    // 获取树形目录-
    this.getOrgTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = treeData[0] || {}
      let array = []
      if (this.treeItem.children.length > 0) {
        array = this.extractIds(this.treeItem)
      }
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id) //通过 $refs 获取treeSide组件引用，并调用 setCurrentKey方法设置当前选中的树节点。
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 'roadId', array) //将选中的树节点的 path 设置为查询参数的一部分，用于后续的表格数据请求。
      this.loadData() //加载表格数据
    })
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          this.params.pageBean.page = 1
          this.loadData()
          break
        case 'edit':
          this.loadData()
          break
      }
    })
  },
  methods: {
    extractIds(node) {
      let ids = []
      // 如果当前节点有 children，则递归提取
      if (node.children) {
        ids = node.children.map(child => child.id) // 提取当前节点的 id
        // 递归提取子节点的 id
        node.children.forEach(child => {
          ids = ids.concat(this.extractIds(child))
        })
      }
      return ids
    },
    filePreviewChange(row) {
      this.fileInfo = row
      this.fileShowDialog = true
    },
    // 时间范围切换
    datePickerChange(val) {
      setQueryValue(this.params, 'rescue_time_', val)
      this.params.pageBean.page = 1
      this.loadData()
    },
    handleSelectionChange(row) {
      this.multiSelectData = row.map(item => item.id)
    },
    async exportData() {
      this.downloadLoading = true
      try {
        let params = {
          groupRelation: 'AND',
          groupTree: {},
          pageBean: {
            page: 1,
            pageSize: -1,
            showTotal: true
          },
          params: {},
          querys: [
            {
              group: 'main',
              operation: 'IN',
              parentGroup: '',
              property: 'ri.id_',
              relation: 'AND',
              value: this.multiSelectData
            }
          ],
          sorter: [
            {
              direction: 'ASC',
              property: ''
            }
          ]
        }
        const response = await exportDataFile(params)
        // 创建Blob对象
        const blob = new Blob([response], {type: 'application/zip'})
        // 创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        // 设置文件名（可以根据需要调整）
        link.setAttribute('download', '清障救援档案.zip')
        // 触发下载
        document.body.appendChild(link)
        link.click()
        // 清理
        document.body.removeChild(link)
        window.URL.revokeObjectURL(downloadUrl)
        this.$message.success('导出成功')
      } finally {
        this.downloadLoading = false
      }
    },
    handleEditPage(row) {
      this.changePage('EditAddPage', row, '编辑')
    },
    // 获取公司树-异步方法，用于从后端获取树形数据
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true //开始加载时显示加载状态
        let {value} = await getTree() // 调用 API 获取树形数据
        this.treeData = [value]
      } finally {
        this.treeLoading = false // 无论成功或失败，都关闭加载状态
        callback && callback(this.treeData) // 如果提供了回调函数，则调用它并传入树形数据
      }
    },
    transformTreeData(data) {
      return {
        name: data.name,
        id: data.id,
        children: data.children.reduce((acc, child) => {
          acc.push({
            id: child.id,
            name: child.name,
            path: child.path,
            children: child.roadList.map(road => ({
              id: road.id,
              name: road.name,
              path: road.path
            }))
          })
          return acc
        }, [])
      }
    },

    selectable(row, index) {
      return row.rescueStatus < '1'
    },
    // 删除
    handleDelete() {
      this.clickTimer = true
      this.$confirm('确定删除选中的事件信息吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let ids = 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(_ => _)
    },
    // 撤回
    revocation({id}) {
      this.$confirm('确定撤回救援委派吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {state} = await revocation(id)
        if (state) {
          this.$message.success('撤回成功！')
          this.loadData()
        }
      })
    },
    dictionaryEscape,

    //获取数据
    async loadData() {
      this.tableLoading = true
      const {total = 0, rows = []} = await tableData(
        refineRequestBody(this.params)
      )
      this.params.pageBean.total = total
      this.tableData = rows
      this.tableLoading = false
    },

    //左边树节点
    currentChange(nodeItem) {
      // 判断是否是一级目录（有 children 属性）
      // if (nodeItem.children && nodeItem.children.length > 0) {
      //   this.isAddDisabled = true // 禁用新增按钮
      //   // this.$message.warning('请选择二级目录进行新增操作')
      //   const array = nodeItem.children.map(item => item.id)
      //   setQueryValue(this.params, 'roadId ', array)
      // } else {
      //   this.isAddDisabled = false // 启用新增按钮
      //   // 修改对应的字段值
      //   setQueryValue(this.params, 'roadId ', [nodeItem?.id] || [])
      // }

      if (nodeItem.id === '1766017468444450816') {
        this.isAddDisabled = true
        setQueryValue(this.params, 'roadId', this.extractIds(nodeItem))
      } else if (nodeItem.children && nodeItem.children.length > 0) {
        this.isAddDisabled = true
        const array = nodeItem.children.map(item => item.id)
        setQueryValue(this.params, 'roadId', array)
      } else {
        this.isAddDisabled = false
        setQueryValue(this.params, 'roadId', [nodeItem?.id] || [])
      }
      this.params.pageBean.page = 1
      this.calcTableHeight(500)
      PubSub.publish('TreeItemSelected', nodeItem)
      this.treeItem = nodeItem || {}
      this.loadData()
    },

    // 树节点操作
    operateEvent(type, data) {
      switch (type) {
        case '新增':
          this.treeItemParentId = data.id
          this.treeDialog = true
          break
        case '编辑':
          this.treeItemId = data.id
          this.treeItemParentId = data.parentId
          this.treeDialog = true
          break
        case '删除':
          this.$confirm('确定删除选中资料分类吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              const {state} = await treeDelete(data.id)
              if (state) {
                this.$message.success(`删除资料分类成功`)
              } else {
                this.$message.error(`删除资料分类失败`)
              }
              await this.getTreeData()
            })
            .catch(_ => _)
          break
      }
    },

    // 目录改变
    catalogChange(dialogName) {
      this.getTreeData(_ => (this[dialogName] = false))
    },

    //修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      this.changePage('EditAddPage', row)
    },

    // 改变页面
    changePage(pageName = '', row = {}, type = '') {
      if (!pageName) return

      this.$emit(
        'changePage',
        pageName,
        _ => {
          PubSub.publish(pageName, row)
        },
        type || '详情'
      )
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped></style>
