<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 :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
                  class="btn btn-plus"
                  icon="el-icon-plus"
                  size="small"
                  type="primary"
                  @click="changePage('EditAddPage', {catalogId: treeItem.id})"
                >
                  添加
                </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>
                <el-button
                  class="btn"
                  icon="el-icon-upload2"
                  plain
                  size="small"
                  type="success"
                  @click="handleFile()"
                >
                  收费文档
                </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="({subjectName}) => subjectName || '-'"
                    align="center"
                    label="项目明细名称"
                    min-width="80"
                    prop="subjectName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="所属组织"
                    min-width="80"
                    prop="orgName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({subjectCode}) => subjectCode || '-'"
                    align="center"
                    label="项目明细编码"
                    min-width="80"
                    prop="subjectCode"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="
                      ({typeId}) => dictionaryEscape('lsxmlx', typeId) || '-'
                    "
                    align="center"
                    label="项目明细类型"
                    min-width="80"
                    prop="typeId"
                    show-overflow-tooltip
                    sortable="custom"
                  />
                  <el-table-column
                    :formatter="({model}) => model || '-'"
                    align="center"
                    label="规格型号"
                    min-width="80"
                    prop="model"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="formatPrice"
                    align="center"
                    label="收费单价"
                    min-width="80"
                    prop="price"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({unit}) => unit || '-'"
                    align="center"
                    label="计费单位"
                    min-width="80"
                    prop="unit"
                    show-overflow-tooltip
                  />
                  <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>
    <!--  附件弹层 -->
    <file-dialog :biz-id.sync="treeItem.id" :is-show-detail.sync="fileDialog" />
  </div>
</template>

<script>
import {getSorterDirection, 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/roadDamageProjectDetails'
import PubSub from 'pubsub-js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import treeSide from '@/components/treeSide/index.vue'
import FileDialog from '../FileDialog/index.vue'
import {getTree} from '@/api/tree'

export default {
  name: 'TablePage',
  components: {
    FileDialog,
    treeSide,
    pagination,
    SearchCommon
  },
  mixins: [TableMixin],
  data() {
    return {
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      treeLoading: true,
      btnLoading: false,
      treeData: [], //左边树
      tabList: ['政策法规'], //左边tab
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      optionList: [
        {
          title: '项目明细名称、编码',
          prop: ['subjectName', 'subjectCode'],
          type: 'input',
          default: true
        },
        {
          title: '项目明细类型',
          prop: 'typeId',
          type: 'select',
          option: getDictionaryByCode('lsxmlx'),
          multiple: true
        },
        {title: '计费单位', prop: 'unit', type: 'input'}
        // {title: '所在路段', prop: 'roadSegmentName', type: 'input'}
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'LIKE', property: 'TEAM_FULL_ID_'},
          {
            group: 'subjectNameCode',
            operation: 'LIKE',
            relation: 'OR',
            property: 'subjectName'
          },
          {
            group: 'subjectNameCode',
            operation: 'LIKE',
            relation: 'OR',
            property: 'subjectCode'
          },
          {operation: 'IN', property: 'typeId'},
          {operation: 'LIKE', property: 'unit'},
          {operation: 'LIKE', property: 'roadSegmentName'},
          {operation: 'IN', property: 'orgId', value: ''}
        ],
        sorter: [{direction: '', property: 'typeId'}]
      },
      treeItem: {}, // 树形节点选中对象
      fileDialog: 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) //通过 $refs 获取treeSide组件引用，并调用 setCurrentKey方法设置当前选中的树节点。
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 'orgId', array) //将选中的树节点的 path 设置为查询参数的一部分，用于后续的表格数据请求。
      this.loadData() //加载表格数据
    })
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          this.params.pageBean.page = 1
          this.loadData()
          // this.handleCurrentChange(1)
          break
        case 'edit':
          this.loadData()
          break
      }
    })
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    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
    },
    formatPrice(row) {
      if (row.minPrice && row.maxPrice) {
        if (row.minPrice === row.maxPrice) {
          return row.minPrice + ' 元'
        }
        return `${row.minPrice + ' 元'} - ${row.maxPrice + ' 元'}`
      } else if (row.minPrice) {
        return row.minPrice + ' 元'
      } else if (row.maxPrice) {
        return row.maxPrice + ' 元'
      } else {
        return '-'
      }
    },
    // 获取公司树-异步方法，用于从后端获取树形数据
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true //开始加载时显示加载状态
        // let treeList = await orgTree()
        let {value} = await getTree() // 调用 API 获取树形数据
        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
        }, [])
      }
    },
    //左边树节点，点击选择
    currentChange(nodeItem) {
      if (nodeItem.id === '1766017468444450816') {
        setQueryValue(this.params, 'orgId', this.extractIds(nodeItem))
      } else if (nodeItem.children && nodeItem.children.length > 0) {
        const array = nodeItem.children.map(item => item.id)
        setQueryValue(this.params, 'orgId', [...array, nodeItem.id])
      } else {
        setQueryValue(this.params, 'orgId', [nodeItem?.id] || [])
      }
      // 修改对应的字段值--重点-点击选择传id
      // setQueryValue(this.params, 'orgId', nodeItem?.id || '') //将选中的树节点的 id 设置为查询参数的一部分。
      this.treeItem = nodeItem || {}
      this.calcTableHeight(500)
      // 触发 TreeItemSelected 事件，并传递节点数据
      PubSub.publish('TreeItemSelected', nodeItem)
      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
      this.tableLoading = false
    },

    // 删除
    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(_ => _)
    },

    handleFile() {
      this.fileDialog = true
    },

    //双击修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      this.changePage('EditAddPage', row)
    },
    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return

      // 传递当前选中的树节点信息
      const payload = row.id
        ? row
        : {
          catalogId: this.treeItem.id,
          orgName: 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>
.table-page {
  .basis {
    min-width: 240px !important;
  }
}
</style>
