<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">
              <SearchCommon :optionList="optionList" @search="handleSearch" />
            </div>
          </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="primary"
                        @click="handleInspection(row)"
                      >
                        巡检记录
                      </el-link>
                      <el-link
                        :underline="false"
                        type="warning"
                        @click="handleReportRecord(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} 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: {
    treeSide,
    pagination,
    SearchCommon,
  },
  mixins: [TableMixin],
  data() {
    return {
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      btnLoading: false,
      tableData: [],
      treeLoading: true,
      treeData: [], //左边树
      treeItem: {}, //左边树选中的节点
      defaultProps: {
        children: 'children', //子节点
        label: 'name', //节点标签
      },
      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: ['2']},
          {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
      }
    })
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    datePickerChange(data) {
      setQueryValue(this.params, 'inspectDate', data?.[0] || '')
      setQueryValue(this.params, 'inspectDate', data?.[1] || '')
      this.params.pageBean.page = 1
      this.loadData()
    },
    // 获取公司树-异步方法，用于从后端获取树形数据
    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()
    },
    //获取数据
    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('ResultListPage', {
        ...row,
      })
    },
    //上报记录
    handleReportRecord(row) {
      this.changePage('AbnormalListPage', {
        ...row,
      })
    },
    // 改变页面
    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>
