<template>
  <div class="table-page">
    <div class="table-page-content">
      <div class="left-tree">
        <tree-side ref="treeSide" :dataLoading="treeLoading" :default-expand-all="true" :defaultProps="defaultProps"
                   :tabList="['组织路段树']" :treeData="treeData" isDeselect
                   @currentChange="currentChange"></tree-side>
      </div>
      <div class="right-table">
        <div class="full-page bg">
          <div class="search-box">
            <SearchCommon :optionList="optionList" @search="handleSearch" />
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <div ref="btnPanel" class="btn-box">
                <el-button :loading="syncLoading" class="btn btn-plus" icon="el-icon-receiving" size="small"
                           type="primary" @click="handleRefreshData">
                  同步
                </el-button>
              </div>
              <div ref="tableRef" class="table-content">
                <el-table ref="multipleSelection" v-loading="tableLoading" :data="tableData"
                          :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" label="序号" type="index" width="60" />
                  <el-table-column align="center" label="涵洞编号" min-width="80" prop="number" show-overflow-tooltip />
                  <el-table-column align="center" label="所属路段" min-width="80" prop="roadSegmentName"
                                   show-overflow-tooltip />
                  <el-table-column align="center" label="所属公司" min-width="80" prop="companyName"
                                   show-overflow-tooltip />
                  <el-table-column align="center" label="涵洞类型" min-width="80" prop="typeValue"
                                   show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column align="center" label="中心桩号" min-width="80" prop="centPeg"
                                   show-overflow-tooltip />
                  <el-table-column align="center" label="涵洞高度" min-width="80" prop="height" show-overflow-tooltip />
                  <el-table-column align="center" label="涵洞长度" min-width="80" prop="length" show-overflow-tooltip />
                  <el-table-column align="center" label="完成日期" min-width="80" prop="finishDay"
                                   show-overflow-tooltip />
                  <el-table-column align="center" label="操作" min-width="80" 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 {refineRequestBody, setQueryValue} 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 {synchroData, tableData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/culvertInfo'
import PubSub from 'pubsub-js'
import {getTree} from '@/api/tree'

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,
      treeLoading: true,
      treeData: [], //左边树
      tabList: [], //左边tab
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      currentDataDel: [],
      optionList: [
        {title: '涵洞编号', prop: 'number', type: 'input', default: true}
        // {title: '所属路段', prop: 'road_Segment_Name_', type: 'input', default: false}
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 'roadSegmentId'},
          // {operation: 'LIKE', property: 'COMPANY_IDS_ ', value: ''},
          {operation: 'LIKE', property: 'number', value: ''}
          // {operation: 'LIKE', property: 'road_Segment_Name_', value: ''}
        ],
        sorter: []
      },
      fullPath: ['1766017468444450816'],
      treeItem: {}, // 树形节点选中对象
      syncLoading: false
    }
  },
  created() {
    // 获取树形目录
    this.getOrgTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = treeData[0] || {}
      let array = []
      if (this.treeItem.children.length > 0) {
        array = this.extractIds(this.treeItem)
      }
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 'roadSegmentId', array)
      // 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: {
    extractIds(node) {
      let ids = []
      // 如果当前节点有 children，则递归提取
      if (node.children) {
        ids = node.children.map(child => child.id) // 提取当前节点的 id
        // 递归提取子节点的 id
        node.children.forEach(child => {
          ids = ids.concat(this.extractIds(child))
        })
      }
      return ids
    },
    // 获取公司树
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true
        let {value} = await getTree()
        this.treeData = [value]
      } finally {
        this.treeLoading = false
        callback && callback(this.treeData)
      }
    },
    transformTreeData(data) {
      return {
        name: data.name,
        id: data.id,
        children: data.children.reduce((acc, child) => {
          acc.push({
            id: child.id,
            name: child.name,
            path: child.path,
            children: child.roadList.map(road => ({
              id: road.id,
              name: road.name,
              path: road.path
            }))
          })
          return acc
        }, [])
      }
    },
    // 获取路线信息
    // 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) // 获取路线信息
      if (nodeItem.id === '1766017468444450816') {
        setQueryValue(this.params, 'roadSegmentId ', this.extractIds(nodeItem))
      } else if (nodeItem.children && nodeItem.children.length > 0) {
        const array = nodeItem.children.map(item => item.id)
        setQueryValue(this.params, 'roadSegmentId ', array)
      } else {
        setQueryValue(this.params, 'roadSegmentId ', [nodeItem?.id] || [])
      }
      // if (nodeItem.children && nodeItem.children.length > 0) {
      //   this.isAddDisabled = true // 禁用新增按钮
      //   const array = nodeItem.children.map(item => item.id)
      //   setQueryValue(this.params, 'roadSegmentId ', array)
      //   this.$message.warning('请选择二级目录进行新增操作')
      // } else {
      //   this.isAddDisabled = false // 启用新增按钮
      //   // 修改对应的字段值
      //   setQueryValue(this.params, 'roadSegmentId ', [nodeItem?.id] || [])
      // }
      // 修改对应的字段值
      // setQueryValue(this.params, 'COMPANY_IDS_', nodeItem?.path || '')
      this.params.pageBean.page = 1
      this.loadData()
      this.calcTableHeight(500)

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

    // 关闭页面执行
    closePage() {
    },
    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>
