<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 ref="btnPanel" class="btn-box">
              <el-button :disabled="isAddDisabled" class="btn btn-plus" icon="el-icon-plus" size="small"
                         type="primary" @click="changePage('EditAddPage', { catalogId: treeItem.id })">
                添加
              </el-button>
              <el-button :disabled="!currentDataDel.length" :loading="btnLoading" class="btn btn-delete"
                         icon="el-icon-delete" plain size="small" type="danger" @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" @sort-change="sortChange"
                          @row-dblclick="handleDbClick">
                  <el-table-column align="center" type="selection" width="70" />
                  <el-table-column :index="index => index + 1 + (params.pageBean.page - 1) * params.pageBean.pageSize"
                                   align="center" label="序号" type="index" width="70" />
                  <el-table-column :formatter="({ name }) => name || '-'" align="center" label="巡查救援队伍"
                                   min-width="120"
                                   prop="account" show-overflow-tooltip />
                  <el-table-column :formatter="({ type }) => dictionaryEscape('dwlx', type) || '-'" align="center"
                                   label="队伍类型" min-width="80" prop="tel" show-overflow-tooltip />
                  <el-table-column :formatter="({ orgName }) => orgName || '-'" align="center" label="所在路段"
                                   min-width="80" prop="code" show-overflow-tooltip />
                  <el-table-column :formatter="({ man }) => man || '-'" align="center" label="负责人" min-width="80"
                                   prop="man" show-overflow-tooltip />
                  <el-table-column :formatter="({ tel }) => tel || '-'" align="center" label="负责人联系电话"
                                   min-width="80"
                                   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="primary" @click="toPersonMgmt(row)">
                        人员管理
                      </el-link>
                      <el-link :underline="false" type="primary" @click="handleDetailPage(row)">
                        详情
                      </el-link>
                      <el-link :disabled="btnLoading" :underline="false" type="danger" @click="handleDelete(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 treeSide from '@/components/treeSide/index.vue'
import SearchCommon from '@/components/SearchCommon/index.vue'
import {getTree, tableData, tableDelete} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'
import PubSub from 'pubsub-js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'


export default {
  name: 'TablePage',
  components: {
    pagination,
    treeSide,
    SearchCommon
  },
  mixins: [TableMixin],
  data() {
    return {
      isAddDisabled: false, // 新增按钮是否禁用
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      treeLoading: true,
      btnLoading: false,
      treeData: [], //左边树
      tabList: ['政策法规'], //左边tab
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      optionList: [
        {title: '巡查救援队伍、所在路段', prop: ['t.name_', 'r.name_'], type: 'input', default: true},
        {title: '队伍类型', prop: 't.type_', type: 'select', option: getDictionaryByCode('dwlx'), multiple: false}
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'LIKE', property: 't.ORG_FULL_ID_', value: ''},
          {group: 'nameRoadName', operation: 'LIKE', relation: 'OR', property: 't.name_'},
          {group: 'nameRoadName', operation: 'LIKE', relation: 'OR', property: 'r.name_'},
          {operation: 'EQUAL', property: 't.type_'}
        ],
        sorter: []
      },
      treeItem: {} // 树形节点选中对象
    }
  },
  created() {
    // 获取树形目录
    this.getOrgTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = treeData[0] || {}
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 't.ORG_FULL_ID_', this.treeItem?.path || '')
      this.loadData()
    })
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          this.handleCurrentChange(1)
          break
        case 'edit':
          this.loadData()
          break
      }
    })
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,

    toPersonMgmt({teamId}) {
      this.$router.push({
        path: '/platLayout/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescuePersonnelMgmt',
        query: {
          teamId
        }
      })
    },

    // 获取公司树
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true
        let {value} = await getTree()
        this.treeData = this.transformTreeData(value)
        callback && callback(this.treeData)
      } catch {
        callback && callback([])
      } finally {
        this.treeLoading = false
        this.tableLoading = false
      }
    },
    transformTreeData(data) {
      return data.map(item => ({
        id: item.id,
        name: item.name, // 一级目录的 label
        children: item.roadList.map(grid => ({
          id: grid.id,
          name: grid.name // 二级目录的 label
        }))
      }))
    },

    //左边树节点
    currentChange(nodeItem) {
      // 判断是否是一级目录（有 children 属性）
      if (nodeItem.children && nodeItem.children.length > 0) {
        this.isAddDisabled = true // 禁用新增按钮
        this.$message.warning('请选择二级目录进行新增操作')
      } else {
        this.isAddDisabled = false // 启用新增按钮
      }
      // 修改对应的字段值
      setQueryValue(this.params, 't.ORG_FULL_ID_', nodeItem?.id || '')
      this.params.pageBean.page = 1
      this.calcTableHeight(500)
      // 触发 TreeItemSelected 事件，并传递节点数据
      PubSub.publish('TreeItemSelected', nodeItem)
      this.treeItem = nodeItem || {}
      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
      }
    },

    // 删除
    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 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()
          }
        } finally {
          this.btnLoading = false
        }
      }).catch(_ => _)
    },
    //双击修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      this.changePage('EditAddPage', row)
    },
    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      // 传递当前选中的树节点信息
      const payload = row.id ? row : {
        catalogId: this.treeItem.id,
        orgName: this.treeItem.name,
        path: this.treeItem.path,
        clearForm: true // 清空表单标志
      }
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, payload)
      }, row.id ? '编辑' : '添加')


    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
.table-page {
  ::v-deep .left-tree {
    width: 270px !important;
  }

  .basis {
    min-width: 240px !important;
  }
}
</style>
