<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
                icon="el-icon-plus"
                type="primary"
                class="btn btn-plus"
                @click="handleAddPage"
                size="small"
              >
                添加
              </el-button>
              <el-button
                size="small"
                icon="el-icon-delete"
                type="danger"
                plain
                class="btn btn-delete"
                :disabled="!currentDataDel.length"
                @click="handleDelete()"
              >
                删除
              </el-button>
            </div>
            <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"
                  @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="({confName}) => confName || '-'"
                    align="center"
                    label="模版名称"
                    min-width="100"
                    prop="confName"
                    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
                    align="center"
                    label="操作"
                    min-width="100"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <el-link
                        :underline="false"
                        type="warning"
                        @click="publish(row)"
                      >
                        执行单次模版
                      </el-link>
                      <el-link
                        :underline="false"
                        type="primary"
                        @click="handleDetailPage(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 treeSide from '@/components/treeSide/index.vue'
import {
  tableData,
  taskDelete,
  toggleTriggerRun,
  executeJob,
} from '@/api/patrolAndRescue/videoPatrol/videoConfig'
import PubSub from 'pubsub-js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {orgTree} from '@/api/systemInterface'
export default {
  name: 'TablePage',
  components: {
    pagination,
    SearchCommon,
    treeSide,
  },
  mixins: [TableMixin],
  data() {
    return {
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      treeLoading: true,
      treeData: [], //左边树
      treeItem: {}, //左边树选中的节点
      defaultProps: {
        children: 'children', //子节点
        label: 'name', //节点标签
      },
      btnLoading: false,
      tableData: [],
      rangeTime: [],
      optionList: [
        {
          title: '模版名称',
          prop: 'confName',
          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: 'confName'},
          {operation: 'IN', property: 'type'},
          {operation: 'EQUAL', property: 'roadId'},
        ],
        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,
    // 获取公司树-异步方法，用于从后端获取树形数据
    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, 'roadId', this.treeItem?.id || '')
      this.loadData() //加载表格数据
    },
    //左边树节点，点击选择
    currentChange(nodeItem) {
      // 修改对应的字段值--重点-点击选择传id
      setQueryValue(this.params, 'roadId', 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.map((i) => ({
          isEnable: i.taskStatus === 'NORMAL',
          ...i,
        }))
      } finally {
        this.tableLoading = false
      }
    },

    // 删除
    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((_) => _)
    },

    // 处置
    publish(row = {}) {
      if (this.clickTimer) return (this.clickTimer = false)
      this.$confirm('确定执行选中的视频巡检模版吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            let data = this.qs.stringify({
              id: row.id,
            })
            const {state, message} = await executeJob(data)
            if (state) {
              this.$message.success(`视频巡检模版执行成功`)
              await this.loadData()
            } else {
              this.$message.warning(message || `视频巡检模版执行失败！`)
            }
          } finally {
          }
        })
        .catch((_) => _)
    },
    //
    handleAddPage() {
      this.changePage('EditAddPage', {
        roadId: this.treeItem.id,
        roadName: this.treeItem.name,
      })
    },
    // 改变页面
    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>
