<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">
            <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 :disabled="isAddDisabled" class="btn btn-plus" icon="el-icon-plus" size="small"
                           type="primary"
                           @click="changePage('EditAddPage')">
                  添加
                </el-button>
                <el-button :disabled="!currentDataDel.length" 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"
                          :max-height="tableMaxHeight" border class="table-list"
                          element-loading-background="rgba(0, 0, 0, 0.6)"
                          element-loading-spinner="el-icon-loading" row-key="id" stripe @select="handleSelection"
                          @selection-change="handleSelectionChange" @row-dblclick="handleDbClick">
                  <el-table-column align="center" type="selection" width="55" />
                  <el-table-column :index="(index) =>
                    index +
                    1 +
                    (params.pageBean.page - 1) *
                    params.pageBean.pageSize
                    " align="center" label="序号" type="index" width="60" />
                  <el-table-column align="center" label="巡查点名称" min-width="100" prop="name"
                                   show-overflow-tooltip />
                  <el-table-column :formatter="({ roadName }) => roadName || '-'" align="center" label="所属路段"
                                   min-width="80" prop="roadName" show-overflow-tooltip />
                  <el-table-column align="center" label="驻点类型" min-width="140" prop="type"
                                   show-overflow-tooltip>
                    <template v-slot="{ row }">
                      {{ row.type === 1 ? '巡查驻点' : '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column :formatter="({classType}) => dictionaryEscape('jyd-cslx', String(classType)) || '-'"
                                   align="center" label="场所类型" min-width="100" prop="classType"
                                   show-overflow-tooltip />
                  <!--                  <el-table-column align="center" label="所属路段" min-width="100" prop="name" show-overflow-tooltip />-->
                  <el-table-column align="center" label="所属监控中心电话" min-width="140" prop="monitorTel"
                                   show-overflow-tooltip />
                  <el-table-column align="center" label="所属巡查队" min-width="140" prop="teamId"
                                   show-overflow-tooltip>
                    <template slot-scope="scope">
                      <div v-if="scope.row.teamName">
                        {{ scope.row.teamName }}
                      </div>
                      <div v-else>-</div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="负责人" min-width="140" prop="linkName"
                                   show-overflow-tooltip />
                  <el-table-column align="center" label="操作" min-width="120" show-overflow-tooltip>
                    <template v-slot="{ row }">
                      <el-link :underline="false" type="primary" @click="handleDetailPage(row)">
                        详情
                      </el-link>
                      <el-link :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 {refineRequestBody, setQueryValue} from '@/utils/requestWrappers'
import pagination from '@/components/SuperPagination/index.vue'
import {TableMixin} from '@/mixins/tableMixin'
import SearchCommon from '@/components/SearchCommon/index.vue'
import {tableData, tableDelete} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/infoMgmtPatrolsManage'
import PubSub from 'pubsub-js'
import treeSide from '@/components/treeSide/index.vue'
import {tableData as teamData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {getTree} from '@/api/tree'

export default {
  name: 'TablePage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  components: {
    treeSide,
    pagination,
    SearchCommon
  },
  mixins: [TableMixin], // 基础公共方法（如：双击修改、查看详情等）在mixin中，在实例中重写可覆盖。
  data() {
    return {
      isAddDisabled: true, // 新增按钮是否禁用
      pubSub: null,
      tableMaxHeight: '600px',
      loading: false,
      tableLoading: false,
      treeLoading: true,
      treeData: [], //左边树
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      currentDataDel: [],
      optionList: [
        {title: '巡查点名称', prop: 's.name_', type: 'input', default: true},
        {
          title: '场所类型',
          prop: 'CLASS_TYPE_',
          type: 'select',
          option: getDictionaryByCode('jyd-cslx'),
          multiple: true
        },
        {title: '所属巡查队', prop: 't.name_', type: 'input'}
        // {title: '所属巡查队', prop: 'team_Id_', type: 'select', option: [], multiple: false}
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 's.road_id_'},
          // {group: 'quick', operation: 'LIKE', relation: 'OR', property: 's.name_'},
          {group: 'quick', operation: 'LIKE', relation: 'OR', property: 'link_Name_'},
          {operation: 'EQUAL', property: 'road_Id_'},
          {operation: 'EQUAL', property: 'manage_Unit_Id_'},
          {operation: 'EQUAL', property: 'monitor_Id_'},
          {operation: 'LIKE', property: 't.name_'},
          {operation: 'IN', property: 'CLASS_TYPE_'},
          {operation: 'IN', property: 's.type_', value: '1'},
          {group: 'quick', operation: 'LIKE', property: 's.name_'}

        ],
        sorter: []
      },
      treeDialog: false, // 科目信息弹层
      treeItemId: '', // 树形目录id
      treeItem: {}, // 树形节点选中对象
      treeItemParentId: '' // 树形目录父级id
    }
  },
  created() {
    this.getTeamData()
    // 获取树形目录
    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, 's.road_id_', array)
      this.loadData()
    })
  },
  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
      }
    })
    this.calcTableHeight()
    this.$root.$on('resize', () => {
      this.calcTableHeight(500)
    })
  },
  methods: {
    dictionaryEscape,
    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
    },
    managerChange(id) {
      return this.teamOptions.filter(item => item.id === id)[0].name
    },
    // 通过路段信息获取巡查救援队伍信息
    async getTeamData(value) {
      const {rows = []} = await teamData(refineRequestBody({
        querys: [{operation: 'IN', property: 'r.id_', value}]
      }), 'addEdit')
      this.teamOptions = rows
      console.log(rows, '救援队伍')
    },
    // 获取公司树
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true
        let {value} = await getTree()
        this.treeData = [value]
      } finally {
        this.treeLoading = false
        callback && callback(this.treeData)
        this.tableLoading = false
      }
    },
    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, 's.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, 's.road_id_', array)
      } else {
        this.isAddDisabled = false
        setQueryValue(this.params, 's.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, 's.road_id_ ', array)
      //   this.$message.warning('请选择二级目录进行新增操作')
      // } else {
      //   this.isAddDisabled = false // 启用新增按钮
      //   // 修改对应的字段值
      //   setQueryValue(this.params, 's.road_id_ ', [nodeItem?.id] || [])
      // }
      // 修改对应的字段值
      // setQueryValue(this.params, 'catalog_full_id_ ', nodeItem?.id || '')
      this.treeItem = nodeItem || {}
      this.calcTableHeight(500)
      PubSub.publish('TreeItemSelected', {
        id: nodeItem?.id || '',
        name: nodeItem?.name || '',
        path: nodeItem?.path || ''
      })
      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
    },

    // 删除
    handleDelete(row) {
      this.clickTimer = true
      setTimeout(_ => this.clickTimer = false)
      this.$confirm('确定删除选中救援点位吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let ids = row ? row.id : this.currentDataDel.join()
          let {state, message} = 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()
          } else {
            this.$message.error(message)
          }
        })
        .catch((_) => _)
    },
    //双击修改
    handleDbClick(row) {
      console.log(row, 's飒飒大大大')
      console.log(row, '修改时的值')
      if (this.clickTimer) return (this.clickTimer = false)
      // 确保 row 中包含 orgName
      const payload = {
        ...row,
        roadName: row.roadName || this.treeItem.name // 如果 row.orgName 为空，使用 treeItem.name
      }
      this.changePage('EditAddPage', payload)
    },
    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      // 传递当前选中的树节点信息
      const payload = row.id ? row : {
        catalogId: this.treeItem.id,
        roadName: 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>
.search-box-combination {
  display: flex;
  column-gap: 16px;
  align-items: center;

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