<template>
  <div class="table-page">
    <div class="table-page-content">
      <div class="left-tree">
        <tree-side :dataLoading="treeLoading" isDeselect :treeData="treeData" :tabList="['行政维度']"
          :defaultProps="defaultProps" @currentChange="currentChange" ref="treeSide"></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-receiving" type="primary" class="btn btn-plus" size="small"
                :loading="syncLoading" @click="handleRefreshData">
                同步
              </el-button>
            </div>
            <SearchCommon @search="handleSearch" :optionList="optionList" />
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <div class="table-content" ref="tableRef">
                <el-table stripe v-loading="tableLoading" element-loading-background="rgba(10 ,38 ,61, 0.9)"
                  ref="multipleSelection" :data="tableData" row-key="id" :max-height="tableMaxHeight" class="table-list"
                  border @select="handleSelection" @selection-change="handleSelectionChange">
                  <el-table-column type="index" width="60" label="序号" align="center" />
                  <el-table-column prop="number" show-overflow-tooltip min-width="80" align="center" label="隧道编号" />
                  <el-table-column prop="name" show-overflow-tooltip min-width="80" align="center" label="隧道名称" />
                  <el-table-column prop="companyName" show-overflow-tooltip min-width="80" align="center"
                    label="所属公司" />
                  <el-table-column prop="roadSegmentName" show-overflow-tooltip min-width="80" align="center"
                    label="所在路段">
                  </el-table-column>
                  <el-table-column prop="gradeValue" show-overflow-tooltip min-width="80" align="center" label="隧道等级" />
                  <el-table-column prop="typeValue" show-overflow-tooltip min-width="80" align="center" label="隧道类型" />
                  <el-table-column show-overflow-tooltip min-width="80" align="center" label="操作">
                    <template v-slot="{ row }">
                      <el-link type="primary" :underline="false" @click="handleDetailPage(row)">
                        详情
                      </el-link>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination ref="paginationPanel" style="margin-top: 10px" :pageResult="params.pageBean"
                  @size-change="handleSizeChange" @current-change="handleCurrentChange" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { setQueryValue, refineRequestBody } from '@/utils/requestWrappers'
import treeSide from '@/components/treeSide/index.vue'
import pagination from '@/components/SuperPagination/index.vue'
import { TableMixin } from '@/mixins/tableMixin'
import SearchCommon from '@/components/SearchCommon/index.vue'
import { tableData, synchroData } from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/tunnelInfo'
import { orgTree } from '@/api/systemInterface'
import PubSub from 'pubsub-js'

export default {
  name: 'TablePage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String,
    },
  },
  components: {
    pagination,
    SearchCommon,
    treeSide
  },
  mixins: [TableMixin], // 基础公共方法（如：双击修改、查看详情等）在mixin中，在实例中重写可覆盖。
  data() {
    return {
      pubSub: null,
      tableMaxHeight: '600px',
      loading: false,
      tableLoading: false,
      treeData: [], //左边树
      tabList: [], //左边tab
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      currentDataDel: [],
      optionList: [
        { title: '隧道名称', prop: 'name', type: 'input', default: true },
        { title: '隧道编码', prop: 'number', type: 'input', default: false }
      ],
      params: {
        pageBean: { pageSize: 20, page: 1, total: 0 },
        querys: [
          { operation: 'LIKE', property: 'COMPANY_IDS_ ', value: '' },
          { operation: 'LIKE', property: 'name', value: '' },
          { operation: 'LIKE', property: 'number', value: '' }
        ],
        sorter: []
      },
      fullPath: ['1766017468444450816'],
      treeItem: {}, // 树形节点选中对象
      syncLoading: false
    }
  },
  created() {
    // 获取树形目录
    this.getOrgTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = treeData[0] || {}
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
      })
      this.getRoadSectionInfo(this.treeItem?.path)  // 获取路段信息
      setQueryValue(this.params, 'COMPANY_IDS_', this.treeItem?.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
      }
    })
    this.calcTableHeight()
    this.$root.$on('resize', () => {
      this.calcTableHeight(500)
    })
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      },
    },
  },
  methods: {
    // 获取公司树
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true
        this.treeData = await orgTree()
      } finally {
        this.treeLoading = false
        callback && callback(this.treeData)
      }
    },
    // 获取路线信息
    async getRoadSectionInfo(value) {
      const { rows = [] } = await tableData(refineRequestBody({
        pageBean: { pageSize: -1 },
        querys: [{ operation: 'LIKE', property: 'COMPANY_IDS_', value }]
      }))
      this.optionList[1].option = rows.map(i => ({ ...i, value: i.id }))
    },

    //左边树节点
    currentChange(nodeItem) {
      this.getRoadSectionInfo(nodeItem?.path) // 获取路线信息

      // 修改对应的字段值
      setQueryValue(this.params, 'COMPANY_IDS_', nodeItem?.path || '')
      this.params.pageBean.page = 1
      this.loadData()
      this.calcTableHeight(500)

      this.treeItem = nodeItem || {}
    },
    // 打开页面执行
    openPage() {
      this.calcTableHeight(500)
    },

    // 关闭页面执行
    handleRefreshData() {
      this.$confirm('是否路段数据？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.syncLoading = true
          const { state } = await synchroData()
          if (state) {
            this.$message.success(`数据同步成功`)
            this.params.pageBean.page = 1
            await this.loadData()
          }
        } finally {
          this.syncLoading = false
        }
      }).catch(_ => _)
    },
    // 顶部公司搜索
    changeOrg(orgIds) {
      this.params.querys[1].value = orgIds
      this.loadData()
    },

    //获取数据
    async loadData() {
      this.tableLoading = true
      try {
        const { total = 0, rows = {} } = await tableData(
          refineRequestBody(this.params)
        )
        this.params.pageBean.total = total
        this.tableData = rows
      } catch (err) {
        console.log(err)
      }
      this.tableLoading = false
    },

    // 改变页面
    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>
.search-box-combination {
  display: flex;
  column-gap: 16px;
  align-items: center;

  .basis {
    width: 460px;
  }
}
</style>
