<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="btn-box" ref="btnPanel">
              <el-button
                class="btn btn-plus"
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="handleAddPage"
              >
                添加
              </el-button>
              <el-button
                :disabled="!currentDataDel.length"
                class="btn btn-delete"
                icon="el-icon-delete"
                plain
                size="small"
                type="danger"
                @click="handleDelete()"
              >
                删除
              </el-button>
            </div>
            <SearchCommon :optionList="optionList" @search="handleSearch" />
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <div ref="tableRef" class="table-content">
                <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"
                  @selection-change="handleSelectionChange"
                >
                  <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="({taskName}) => taskName || '-'"
                    align="center"
                    label="任务名称"
                    min-width="100"
                    prop="taskName"
                    show-overflow-tooltip
                  />

                  <el-table-column
                    :formatter="({roadName}) => roadName || '-'"
                    align="center"
                    label="所属区域"
                    min-width="70"
                    prop="roadName"
                    show-overflow-tooltip
                  />

                  <el-table-column
                    :formatter="
                      ({type}) =>
                        dictionaryEscape('xjlx-xjrw', type, {
                          congruent: false,
                        }) || '-'
                    "
                    align="center"
                    label="巡检类型"
                    min-width="70"
                    prop="type"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="
                      ({taskStatus}) =>
                        dictionaryEscape('spxj-rwzt', taskStatus, {
                          congruent: false,
                        }) || '-'
                    "
                    align="center"
                    label="任务状态"
                    min-width="80"
                    prop="taskStatus"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({inspectDate}) => inspectDate || '-'"
                    align="center"
                    label="巡检日期"
                    min-width="100"
                    prop="inspectDate"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="操作"
                    min-width="100"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <el-link
                        :underline="false"
                        type="warning"
                        @click="handleInspection(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>
  </div>
</template>

<script>
import {
  getSorterDirection,
  refineRequestBody,
  setQueryValue,
} from '@/utils/requestWrappers'
import pagination from '@/components/SuperPagination/index.vue'
import {TableMixin} from '@/mixins/tableMixin'
import SearchCommon from '@/components/SearchCommon/index.vue'
import {
  tableData,
  taskDelete,
} from '@/api/patrolAndRescue/videoPatrol/videoInspection'
import PubSub from 'pubsub-js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import treeSide from '@/components/treeSide/index.vue'
import {orgTree} from '@/api/systemInterface'

export default {
  name: 'TablePage',
  components: {
    pagination,
    SearchCommon,
    treeSide,
  },
  mixins: [TableMixin],
  data() {
    return {
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      btnLoading: false,
      tableData: [],
      treeLoading: true,
      treeData: [], //左边树
      defaultProps: {
        children: 'children', //子节点
        label: 'name', //节点标签
      },
      treeItem: {}, //左边树选中的节点
      rangeTime: [],
      optionList: [
        {
          title: '任务名称',
          prop: 'taskName',
          type: 'input',
          multiple: false,
          default: true,
        },
        {
          title: '巡检类型',
          prop: 'type',
          type: 'select',
          option: getDictionaryByCode('xjlx-xjrw'),
          multiple: true,
        },
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'LIKE', property: 'taskName'},
          {operation: 'IN', property: 'type'},
          {operation: 'IN', property: 'taskStatus', value: ['0', '1']},
          {operation: 'EQUAL', property: 'road_id_'},
        ],
        sorter: [{direction: '', property: ''}],
      },
    }
  },
  created() {
    // 获取树形目录-
    this.getOrgTreeData()
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          this.handleCurrentChange(1)
          break
        case 'edit':
          this.loadData()
          break
      }
    })
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.loadData()
        }
      },
    },
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    // 获取公司树-异步方法，用于从后端获取树形数据
    async getOrgTreeData() {
      try {
        this.treeLoading = true
        let {value} = await orgTree() // 调用 API 获取树形数据
        this.treeData = value || []
      } finally {
        this.loadDataPre()
        this.treeLoading = false // 无论成功或失败，都关闭加载状态
      }
    },
    loadDataPre() {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = this.treeData[0] || {}
      this.$nextTick((_) => {
        this.$refs.treeSide?.setCurrentKey(this.treeItem?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 'road_id_', this.treeItem?.id || '')
      this.loadData() //加载表格数据
    },
    //左边树节点，点击选择
    currentChange(nodeItem) {
      // 修改对应的字段值--重点-点击选择传id
      setQueryValue(this.params, 'road_id_', nodeItem?.id || '') //将选中的树节点的 id 设置为查询参数的一部分。
      this.treeItem = nodeItem || {}
      this.calcTableHeight(500)
      this.params.pageBean.page = 1
      this.loadData()
    },
    datePickerChange(data) {
      setQueryValue(this.params, 'inspectDate', data?.[0] || '')
      setQueryValue(this.params, 'inspectDate', data?.[1] || '')
      this.params.pageBean.page = 1
      this.loadData()
    },
    //获取数据
    async loadData() {
      try {
        this.tableLoading = true
        const {total = 0, rows = []} = await tableData(
          refineRequestBody(this.params)
        )
        this.params.pageBean.total = total
        this.tableData = rows
      } finally {
        this.tableLoading = false
      }
    },

    // 巡检
    handleInspection(row) {
      this.changePage('DetailPage', {
        taskData: row,
      })
    },
    //
    handleAddPage() {
      this.changePage('EditAddPage', {
        roadId: this.treeItem.id,
        roadName: this.treeItem.name,
      })
    },

    // 删除
    handleDelete(row) {
      this.clickTimer = true
      setTimeout((_) => (this.clickTimer = false))
      this.$confirm('确定删除选中的视频巡检任务吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.btnLoading = true
          let ids = row ? row.id : this.currentDataDel.join()
          try {
            const {state} = await taskDelete(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()
            }
          } finally {
            this.btnLoading = false
          }
        })
        .catch((_) => _)
    },

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

      this.$emit(
        'changePage',
        pageName,
        (_) => {
          PubSub.publish(pageName, row)
        },
        row.id ? '编辑' : '添加'
      )
    },
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  },
}
</script>

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