<template>
  <div class="table-page">
    <div class="table-page-content">
      <div class="left-tree">
        <tree-side
          ref="treeSide"
          :dataLoading="treeLoading"
          :defaultExpandAll="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
                :loading="syncLoading"
                class="btn btn-plus"
                icon="el-icon-receiving"
                size="small"
                type="primary"
                @click="syncData"
              >
                同步
              </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"
                >
                  <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="({name}) => name || '-'"
                    align="center"
                    label="沿线设施名称"
                    min-width="120"
                    prop="name"
                    show-overflow-tooltip
                    sortable="custom"
                  />
                  <el-table-column
                    :formatter="({direction}) => dictionaryEscape('qlfx', direction) || '-'"
                    align="center"
                    label="方向"
                    min-width="80"
                    prop="direction"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({type}) => dictionaryEscape('yxss', type) || '-'"
                    align="center"
                    label="类型"
                    min-width="80"
                    prop="type"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({pegK}) => pegK || '-'"
                    align="center"
                    label="桩号值"
                    min-width="90"
                    prop="pegK"
                    show-overflow-tooltip
                    sortable="custom"
                  />
                  <el-table-column
                    :formatter="({roadSegmentName}) => roadSegmentName || '-'"
                    align="center"
                    label="所属路段"
                    min-width="90"
                    prop="roadSegmentName"
                    show-overflow-tooltip
                    sortable="custom"
                  />
                  <el-table-column
                    :formatter="({expound}) => expound || '-'"
                    align="center"
                    label="详细说明"
                    min-width="120"
                    prop="expound"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="操作"
                    min-width="65"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <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 treeSide from '@/components/treeSide/index.vue'
import SearchCommon from '@/components/SearchCommon/index.vue'
import {synchroData, tableData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/alongRouteInfo'
import {tableData as roadSectionInfo} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadSectionInfo'
import PubSub from 'pubsub-js'
import {orgTree} from '@/api/systemInterface'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'

export default {
  name: 'TablePage',
  components: {
    pagination,
    treeSide,
    SearchCommon
  },
  mixins: [TableMixin],
  data() {
    return {
      pubSub: null,
      tableLoading: true,
      treeLoading: true,
      treeData: [], //左边树
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      optionList: [
        {title: '沿线设施名称', prop: 'name', type: 'input', default: true},
        {title: '所属路段', prop: 'road_segment_id_', type: 'select', option: [], multiple: false},
        {title: '方向', prop: 'direction', type: 'select', option: getDictionaryByCode('qlfx'), multiple: false},
        {title: '类型', prop: 'type', type: 'select', option: getDictionaryByCode('yxss'), multiple: false}
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'LIKE', property: 'COMPANY_IDS_'},
          {operation: 'LIKE', property: 'name'},
          {operation: 'EQUAL', property: 'road_segment_id_'},
          {operation: 'IN', property: 'direction'},
          {operation: 'EQUAL', property: 'type'}
        ],
        sorter: [
          {direction: '', property: 'name'},
          {direction: '', property: 'pegK'},
          {direction: '', property: 'roadSegmentName'}
        ]
      },
      treeItem: {}, // 树形节点选中对象
      syncLoading: false // 同步按钮Loading
    }
  },
  created() {
    // 获取树形目录
    this.getOrgTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = treeData[0] || {}
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      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
      }
    })

  },
  methods: {
    dictionaryEscape,
    dictionaryEscape,
    getSorterDirection,

    // 获取公司树
    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 roadSectionInfo(refineRequestBody({
        pageBean: {pageSize: -1},
        querys: [{operation: 'LIKE', property: 'COMPANY_IDS_', value}]
      }))
      this.optionList[1].option = rows.map(i => ({...i, value: i.id}))
    },

    //获取数据
    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
      }
    },

    //左边树节点
    currentChange(nodeItem) {
      this.getRoadSectionInfo(nodeItem?.path) // 获取路线信息
      // 修改对应的字段值
      setQueryValue(this.params, 'COMPANY_IDS_', nodeItem?.path || '')
      this.treeItem = nodeItem || {}
      this.params.pageBean.page = 1
      this.loadData()
      this.calcTableHeight(500)
    },

    // 同步数据
    syncData() {
      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(_ => _)
    },

    // 改变页面
    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 {
  ::v-deep .left-tree {
    width: 275px !important;
  }
}
</style>
