<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="search-box-combination">
              <SearchCommon ref="searchCommon" :optionList="optionList" @search="handleSearch" />
            </div>
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <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', { treeItem })">
                  添加
                </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 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="({ account }) => account || '-'" align="center" label="账号名"
                                   min-width="80" prop="account" show-overflow-tooltip />
                  <el-table-column :formatter="({ roadName }) => roadName || '-'" align="center" label="所属路段"
                                   min-width="80" prop="roadName" show-overflow-tooltip />
                  <el-table-column :formatter="({ name }) => name || '-'" align="center" label="队员姓名" min-width="80"
                                   prop="name" show-overflow-tooltip />
                  <el-table-column :formatter="({ tel }) => tel || '-'" align="center" label="手机号" min-width="80"
                                   prop="tel" show-overflow-tooltip />
                  <!-- <el-table-column :formatter="({ code }) => code || '-'" align="center" label="身份证号" min-width="100"
                    prop="code" show-overflow-tooltip /> -->
                  <!--                  <el-table-column :formatter="({ code }) => code || '-'" align="center" label="身份证号"-->
                  <!--                                   min-width="100"-->
                  <!--                                   prop="code" show-overflow-tooltip />-->
                  <!--                  <el-table-column :formatter="({ outCompanyId }) => outCompanyId || '-'" align="center"-->
                  <!--                                   label="外包公司" min-width="100" prop="outCompanyId" show-overflow-tooltip>-->
                  <!--                  </el-table-column>-->

                  <el-table-column :formatter="({ type }) => dictionaryEscape('rylx-xcjyry', type) || '-'"
                                   align="center" label="人员类型" min-width="80" prop="type" show-overflow-tooltip />
                  <el-table-column :formatter="({ post }) => dictionaryEscape('ryzw-xcjyry', post) || '-'"
                                   align="center" label="人员职务" min-width="80" prop="post" show-overflow-tooltip />
                  <el-table-column :formatter="({ isOut }) => dictionaryEscape('sfpj', isOut) || '-'" align="center"
                                   label="是否外派人员" min-width="120" prop="isOut" show-overflow-tooltip
                                   sortable="custom" />
                  <el-table-column align="center" label="外包公司" min-width="200" prop="outCompanyId"
                                   show-overflow-tooltip>
                    <template slot-scope="scope">
                      <div v-if="scope.row.outCompanyName">
                        {{ scope.row.outCompanyName }}
                      </div>
                      <div v-else>-</div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作" min-width="100" show-overflow-tooltip>
                    <template v-slot="{ row }">
                      <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 {tableData, tableDelete} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescuePersonnelMgmt'
import PubSub from 'pubsub-js'
import {dictionaryEscape} from '@/utils/dictionary'

import {tableData as teamData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'
import {getTree} from '@/api/tree'

export default {
  name: 'TablePage',
  components: {
    pagination,
    treeSide,
    SearchCommon
  },
  mixins: [TableMixin],
  data() {
    return {
      isAddDisabled: true, // 新增按钮是否禁用
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      treeLoading: true,
      btnLoading: false,
      treeData: [], //左边树
      tabList: ['政策法规'], //左边tab
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      optionList: [
        // {title: '账号名、队员姓名、手机号', prop: ['account', 'name', 'tel'], type: 'input', default: true},
        {title: '队员姓名', prop: 'tm.name_', type: 'input', default: true},
        {title: '手机号', prop: ' tm.tel_', type: 'input', default: false},
        // {title: '身份证号', prop: 'code', type: 'input'},
        // {title: '外包公司', prop: 'out_company_name_', type: 'input'},
        // {title: '外包公司', prop: 'oc.name_', type: 'select', option: [], multiple: false},
        {title: '外包公司', prop: 'oc.name_', type: 'input', default: false}
        // {title: '人员类型', prop: 'type', type: 'select', option: getDictionaryByCode('rylx-xcjyry'), multiple: false},
        // {title: '人员职务', prop: 'tm.post_', type: 'input', default: true}

        // {
        //   title: '人员职务',
        //   prop: 'tm.post_',
        //   type: 'select',
        //   option: getDictionaryByCode('ryzw-xcjyry'),
        //   multiple: false
        // }
        // {title: '是否外派人员', prop: 'isOut', type: 'select', option: dictionaryEscape('sfpj'), multiple: true}
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 'tm.road_id_'},
          // {operation: 'EQUAL', property: 'type', value: '1'},
          // { operation: 'LIKE', property: 'TEAM_FULL_ID_' },
          {group: 'accountNameTel', operation: 'LIKE', relation: 'OR', property: 'account'},
          {group: 'accountNameTel', operation: 'LIKE', relation: 'OR', property: 'name'},
          {group: 'accountNameTel', operation: 'LIKE', relation: 'OR', property: 'tel'},
          {operation: 'LIKE', property: 'tm.name_'},
          {operation: 'LIKE', property: ' tm.tel_'},
          {operation: 'LIKE', property: 'oc.name_'},
          {operation: 'EQUAL', property: 'team_Id_'},
          {operation: 'EQUAL', property: 'tm.type_', value: '1'},
          {operation: 'EQUAL', property: 'tm.post_'},
          {operation: 'EQUAL', property: 'isOut'}
        ],
        sorter: [
          {direction: '', property: 'account'},
          {direction: '', property: 'name'},
          {direction: '', property: 'tel'},
          {direction: '', property: 'isOut'}
        ]
      },
      treeItem: {} // 树形节点选中对象
    }
  },
  created() {
    // 获取树形目录
    this.getOrgTreeData(treeData => {
      this.treeItem = treeData[0] || {}
      let array = []
      if (this.treeItem.children.length > 0) {
        array = this.extractIds(this.treeItem)
      }
      // 从路由参数中获取teamId
      // let {teamId} = this.$route.query
      // // 如果有teamId参数，则查找对应的树节点
      // if (teamId) {
      //   const findNode = this.findTreeNode(treeData, teamId)
      //   if (findNode) {
      //     this.treeItem = findNode
      //     this.$nextTick(_ => {
      //       this.$refs.treeSide?.setCurrentKey(findNode.id)
      //       this.$refs.treeSide?.expandHandle(true, 2)
      //     })
      //     // 设置查询参数
      //     setQueryValue(this.params, 'tm.road_id_', [findNode.id])
      //   }
      // } else {
      // 默认选中第一项
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 'tm.road_id_', array)
      // }
      //进入页面调用一次
      this.loadData()
    })
    // this.getTeamData()

  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          this.handleCurrentChange(1)
          // this.params.pageBean.page = 1
          this.loadData()
          break
        case 'edit':
          this.loadData()
          break
      }
    })
  },
  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
    },
    // 辅助方法：在树数据中查找特定节点(定位)
    findTreeNode(treeData, id) {
      for (const node of treeData) {
        if (node.id === id) return node
        if (node.children) {
          const found = this.findTreeNode(node.children, id)
          if (found) return found
        }
      }
      return null
    },
    dictionaryEscape,
    getSorterDirection,
    async getTeamData() {
      const {rows = []} = await teamData()
      // this.optionList[3].option = rows.map(item => {
      //   item.value = item.id
      //   return item
      // })

      let {teamId} = this.$route.query
      if (teamId) {
        this.params.querys[5].value = teamId
      }

      this.$nextTick(() => {
        this.loadData()
      })

    },

    // 获取公司树
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true
        let {value} = await getTree()
        this.treeData = [value]
        // 如果有路由参数，在树加载完成后自动选中对应节点
        // const {teamId} = this.$route.query
        // if (teamId) {
        //   const findNode = this.findTreeNode(this.treeData, teamId)
        //   if (findNode) {
        //     this.treeItem = findNode
        //     this.$nextTick(_ => {
        //       this.$refs.treeSide?.setCurrentKey(findNode.id)
        //       this.$refs.treeSide?.expandHandle(true, 2)
        //     })
        //     setQueryValue(this.params, 'tm.road_id_', [findNode.id])
        //   }
        // }
      } finally {
        this.treeLoading = false
        this.tableLoading = 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
        }, [])
      }
    },
    //左边树节点
    currentChange(nodeItem) {
      if (nodeItem.id === '1766017468444450816') {
        this.isAddDisabled = true
        setQueryValue(this.params, 'tm.road_id_ ', this.extractIds(nodeItem))
      } else if (nodeItem.children && nodeItem.children.length > 0) {
        this.isAddDisabled = true
        const array = nodeItem.children.map(item => item.id)
        setQueryValue(this.params, 'tm.road_id_ ', array)
      } else {
        this.isAddDisabled = false
        setQueryValue(this.params, 'tm.road_id_ ', [nodeItem?.id] || [])
      }
      // 判断是否是一级目录（有 children 属性）
      // if (nodeItem.children && nodeItem.children.length > 0) {
      //   this.isAddDisabled = true // 禁用新增按钮
      //   const array = nodeItem.children.map(item => item.id)
      //   setQueryValue(this.params, 'tm.road_id_', array)
      //   this.$message.warning('请选择二级目录进行新增操作')
      // } else {
      //   this.isAddDisabled = false // 启用新增按钮
      //   // 修改对应的字段值
      //   setQueryValue(this.params, 'tm.road_id_', [nodeItem?.id] || [])
      // }
      this.treeItem = nodeItem || {}
      this.calcTableHeight(500)
      // 更新URL中的teamId参数，但不触发页面刷新
      this.$router.replace({
        query: {
          ...this.$route.query,
          teamId: nodeItem?.id || ''
        }
      })


      PubSub.publish('TreeItemSelected', {
        id: nodeItem?.id || '',
        name: nodeItem?.name || '',
        path: nodeItem?.path || '',
        orgId: nodeItem?.orgId || ''
      })
      this.params.pageBean.page = 1
      this.loadData()

    },
    //获取数据
    async loadData() {
      this.tableLoading = true
      const {total = 0, rows = []} = await tableData(refineRequestBody(this.params))
      this.params.pageBean.total = total

      this.tableData = rows.map(row => ({
        ...row,
        roadName: row.roadName || this.treeItem.name // 如果 row.orgName 为空，使用 treeItem.name
      }))
      this.tableLoading = false
    },

    //双击修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      // 确保 row 中包含 orgName
      const payload = {
        ...row,
        roadName: row.roadName || this.treeItem.name,// 如果 row.orgName 为空，使用 treeItem.name
        roadId: row.roadId || this.treeItem.id // 如果 row.teamId 为空，使用 treeItem.id
      }
      console.log(row.roadName, '555555555555555555')
      this.changePage('EditAddPage', payload)
    },
    // 删除
    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(_ => _)
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      // 传递当前选中的树节点信息
      const payload = row.id ? row : {
        catalogId: this.treeItem.id,
        roadName: this.treeItem.name,
        path: this.treeItem.path,
        roadId: this.treeItem.id, // 确保传递 teamId
        clearForm: true, // 清空表单标志
        // 确保传递当前treeItem
        treeItem: this.treeItem
      }
      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>
