<template>
  <div class="table-page">
    <!--  四级路由切换  -->
    <page-route-tab />
    <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="isAddShow"
                  class="btn btn-plus"
                  icon="el-icon-plus"
                  size="small"
                  type="primary"
                  @click="changePage('EditAddPage', {orgId: treeItem.id})"
                >
                  添加
                </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(10 ,38 ,61, 0.9)"
                  row-key="id"
                  stripe
                  @select="handleSelection"
                  @selection-change="handleSelectionChange"
                  @row-dblclick="handleDbClick"
                >
                  <el-table-column align="center" type="selection" width="55" />
                  <el-table-column
                    align="center"
                    label="序号"
                    type="index"
                    width="60"
                  />
                  <el-table-column
                    align="center"
                    label="班种"
                    min-width="80"
                    prop="name"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="上班时间"
                    min-width="80"
                    prop="workStartTime"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="下班时间"
                    min-width="80"
                    prop="workEndTime"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="休息开始时间"
                    min-width="80"
                    prop="restStartTime"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="休息结束时间"
                    min-width="80"
                    prop="restEndTime"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="显示颜色"
                    min-width="80"
                    prop="markColor"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <div
                        :style="{background: row.markColor}"
                        class="markColor"
                      ></div>
                    </template>
                  </el-table-column>
                  <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>
                      <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 treeSide from '@/components/treeSide/index.vue'
import SearchCommon from '@/components/SearchCommon/index.vue'
import PageRouteTab from '@/components/PageRouteTab/index.vue'

import {
  getTableData,
  orgTree,
  tableDelete
} from '@/api/patrolAndRescue/roadWatch/inspectScheduling/inspectWorkGroupContent'
import PubSub from 'pubsub-js'
import {dictionaryEscape} from '@/utils/dictionary'

export default {
  name: 'TablePage',
  components: {
    pagination,
    treeSide,
    SearchCommon,
    PageRouteTab
  },
  mixins: [TableMixin],
  data() {
    return {
      isAddShow: true,
      pubSub: null,
      tableMaxHeight: '600px',
      loading: false,
      treeLoading: true,
      tableLoading: false,
      treeData: [], //左边树
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      currentDataDel: [],
      optionList: [{title: '班种', prop: 'name', type: 'input', default: true}],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {
            operation: 'LIKE',
            property: 'name'
          },
          {
            operation: 'IN',
            property: 'orgId'
          }
        ],
        sorter: []
      },
      treeDialog: false, // 科目信息弹层
      treeItemId: '', // 树形目录id
      treeItem: {} // 树形节点选中对象
    }
  },
  created() {
    // 获取树形目录-
    this.getOrgTreeData()
  },
  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,
    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 orgTree() // 调用 API 获取树形数据
        this.treeData = [value]
        // 回调中默认选中第一项并将其id作为参数请求表格
        this.treeItem = this.treeData[0] || {}
        let array = []
        if (this.treeItem.children.length > 0) {
          array = this.extractIds(this.treeItem)
        }
        this.$nextTick((_) => {
          this.$refs.treeSide?.setCurrentKey(this.treeData[0]?.id) //通过 $refs 获取treeSide组件引用，并调用 setCurrentKey方法设置当前选中的树节点。
          this.$refs.treeSide?.expandHandle(true, 2)
        })
        setQueryValue(this.params, 'orgId', array)
        this.loadData() //加载表格数据
      } finally {
        this.treeLoading = false // 无论成功或失败，都关闭加载状态
        callback && callback(this.treeData) // 如果提供了回调函数，则调用它并传入树形数据
      }
    },
    transformTreeData(data) {
      return data.map(item => ({
        id: item.id,
        name: item.name, // 一级目录的 label
        children: item.teamList.map(grid => ({
          id: grid.id,
          name: grid.name, // 二级目录的 label
          path: grid.path,
          roadId: grid.roadId,
          roadName: grid.roadName
        }))
      }))
    },
    //左边树节点
    currentChange(nodeItem) {
      if (nodeItem.id === '1766017468444450816') {
        this.isAddShow = true
        setQueryValue(this.params, 'orgId', this.extractIds(nodeItem))
      } else if (nodeItem.children && nodeItem.children.length > 0) {
        this.isAddShow = true
        const array = nodeItem.children.map(item => item.id)
        setQueryValue(this.params, 'orgId', array)
      } else {
        this.isAddShow = false
        setQueryValue(this.params, 'orgId', [nodeItem?.id] || [])
      }
      // if (nodeItem.roadId) {
      //   this.isAddShow = false
      // } else {
      //   this.isAddShow = true
      // }
      // // 判断是否是一级目录（有 children 属性）
      // setQueryValue(this.params, 'orgId ', nodeItem?.id || '')
      this.treeItem = nodeItem || {}
      this.calcTableHeight(500)
      this.params.pageBean.page = 1
      this.loadData()
    },
    //获取数据
    async loadData() {
      this.tableLoading = true
      const {total = 0, rows = []} = await getTableData(
        refineRequestBody(this.params)
      )
      this.params.pageBean.total = total
      this.tableData = rows.map((row) => ({
        ...row
      }))
      this.tableLoading = false
    },

    // 删除
    handleDelete(row) {
      this.clickTimer = true
      this.$confirm('确定删除选中班组吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let ids = row ? [row.id] : this.currentDataDel
          console.log(ids, 'ids')
          // 创建 FormData 对象
          const formData = new FormData()
          formData.append('ids', ids.join(','))
          console.log(formData, 'formData')
          try {
            let {state, message} = await tableDelete(formData)
            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 (error) {
            console.log(error)
          }
        })
        .catch((_) => _)
    },

    //修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      const payload = {
        ...row,
        roadName: row.roadName || this.treeItem.name
      }
      this.changePage('EditAddPage', payload)
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      const payload = row.id
        ? row
        : {
          orgId: this.treeItem.id
        }
      this.$emit(
        'changePage',
        pageName,
        (_) => {
          PubSub.publish(pageName, payload)
        },
        row.id ? '编辑' : '添加'
      )
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
.markColor {
  width: 50%;
  height: 20px;
  margin-left: 40px;
}
</style>
