<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">
              <div class="search-box-label">发生时间：</div>
              <div>
                <el-date-picker
                  v-model="params.querys[3].value"
                  end-placeholder="发生时间"
                  range-separator="至"
                  start-placeholder="发生时间"
                  style="width: 360px"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :default-time="['00:00:00', '23:59:59']"
                  @change="datePickerChange"
                >
                </el-date-picker>
              </div>
              <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="{ prop: 'eventTime', order: 'descending' }"
                  :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
                    :selectable="selectable"
                    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="roadName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="事件标题"
                    min-width="190"
                    prop="eventName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="事件类型"
                    min-width="80"
                    prop="eventType"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      {{ dictionaryEscape('lx_sjlxxq', row.eventType + '') || '-' }}
                    </template>
                  </el-table-column>
                  <!--                  <el-table-column-->
                  <!--                    align="center"-->
                  <!--                    label="事件来源"-->
                  <!--                    min-width="80"-->
                  <!--                    prop="eventSrc"-->
                  <!--                    show-overflow-tooltip-->
                  <!--                  >-->
                  <!--                    <template v-slot="{row}">-->
                  <!--                      {{ dictionaryEscape('sjly', row.eventSrc + '') || '-' }}-->
                  <!--                    </template>-->
                  <!--                  </el-table-column>-->
                  <!--                  <el-table-column-->
                  <!--                    align="center"-->
                  <!--                    label="事件等级"-->
                  <!--                    min-width="80"-->
                  <!--                    prop="eventLevel"-->
                  <!--                    show-overflow-tooltip-->
                  <!--                  >-->
                  <!--                    <template v-slot="{row}">-->
                  <!--                      {{ row.eventLevel ? row.eventLevel + '级' : '无等级' }}-->
                  <!--                    </template>-->
                  <!--                  </el-table-column>-->
                  <el-table-column
                    align="center"
                    label="事件发生时间"
                    min-width="100"
                    prop="eventTime"
                    show-overflow-tooltip
                    sortable
                  />
                  <!--                  <el-table-column-->
                  <!--                    align="center"-->
                  <!--                    label="路产损失"-->
                  <!--                    min-width="80"-->
                  <!--                    prop="loss"-->
                  <!--                    show-overflow-tooltip-->
                  <!--                  >-->
                  <!--                    <template v-slot="{row}">-->
                  <!--                      {{ row.loss || '-' }}-->
                  <!--                    </template>-->
                  <!--                  </el-table-column>-->

                  <el-table-column
                    align="center"
                    label="关联事件"
                    min-width="100"
                    prop="eventNo"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      {{ row.eventNo || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="是否补录"
                    prop="compensationStatus"
                    width="80"
                  >
                    <template v-slot="{row}">
                      <el-link
                        :type="row.compensationStatus? 'success': 'primary'"
                        :underline="false"
                      >
                        {{
                          row.compensationStatus ? '已补录' : '未补录'
                        }}
                      </el-link>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="补录条数"
                    min-width="80"
                    prop="compensationNum"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      {{ row.compensationNum || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="补录金额"
                    min-width="80"
                    prop="loss"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      {{ row.loss || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="事件状态"
                    prop="rescueStatus"
                    width="80"
                  >
                    <template v-slot="{row}">
                      <el-link
                        :type="
                          row.rescueStatus < 1
                            ? 'warning'
                            : row.rescueStatus == '1'
                            ? 'danger'
                            : row.rescueStatus == '2'
                            ? 'primary'
                            : 'success'
                        "
                        :underline="false"
                      >
                        {{
                          row.rescueStatus < 1
                            ? '未委派'
                            : row.rescueStatus == '1'
                              ? '未处置'
                              : row.rescueStatus == '2'
                                ? '处置中'
                                : '已完成'
                        }}
                      </el-link>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    show-overflow-tooltip
                    width="200"
                  >
                    <template v-slot="{row}">
                      <el-link
                        :underline="false"
                        type="primary"
                        @click="changePage('EditAddPage', row, row.compensationStatus ? '修改' : '补录')"
                      >
                        {{ row.compensationStatus ? '修改' : '补录' }}
                      </el-link>
                      <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 {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
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 {getTree} from '@/api/tree'
import {bulkDeletion, tableData, tableDelete} from '@/api/patrolAndRescue/roadDamageComp/roadDamageRegister'
import PubSub from 'pubsub-js'
import moment from 'moment'

export default {
  name: 'TablePage',
  components: {
    treeSide,
    pagination,
    SearchCommon
  },
  mixins: [TableMixin],
  data() {
    return {
      isAddDisabled: true,
      btnLoading: false,
      treeLoading: true,
      pubSub: null,
      tableMaxHeight: '600px',
      loading: false,
      tableLoading: false,
      treeData: [], //左边树
      tabList: ['政策法规'], //左边tab
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      currentDataDel: [],
      optionList: [
        {title: '事件标题', prop: ['event_name_'], type: 'input', default: true},
        {
          title: '事件类型',
          prop: ['event_Type_'],
          type: 'select',
          option: getDictionaryByCode('lx_sjlxxq'),
          multiple: true
        },
        {
          title: '事件来源',
          prop: ['event_Src_'],
          type: 'select',
          option: getDictionaryByCode('sjly'),
          multiple: true
        }
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 'event_Type_', value: ''},
          {operation: 'IN', property: 'event_Src_', value: ''},
          {operation: 'LIKE', property: 'event_name_', value: ''},
          {
            operation: 'BETWEEN',
            property: 'event_time_',
            value: [
              moment().subtract(1, 'month')
                .startOf('month')
                .format('YYYY-MM-DD HH:mm:ss'),
              moment()
                .endOf('month')
                .format('YYYY-MM-DD HH:mm:ss')
            ]
          },
          {operation: 'IN', property: 'roadId'}
        ],
        sorter: [
          {
            direction: 'DESC',
            property: 'createTime'
          }
        ]
      },
      treeDialog: false, // 科目信息弹层
      treeItemId: '', // 树形目录id
      treeItem: {}, // 树形节点选中对象
      treeItemParentId: '' // 树形目录父级id
    }
  },
  created() {
    // 获取树形目录
    this.getTreeData(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, 'roadId', array)
      this.loadData()
    })
    // 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
      }
    })
  },
  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
    },
    // 时间范围切换
    datePickerChange(val) {
      setQueryValue(this.params, 'event_time_', val)
      this.params.pageBean.page = 1
      this.loadData()
    },
    selectable(row, index) {
      return true
      // return !row.eventNo
    },
    // 删除
    handleDelete(row) {
      this.clickTimer = true
      this.$confirm('确定删除选中的路损信息吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.btnLoading = true
          if (row) {
            let {state} = await tableDelete(row.id)
            if (!state) {
              this.$message.error(message)
              return
            }
          } else {
            let ids = this.currentDataDel.join()
            let {state} = await bulkDeletion(ids)
            if (!state) {
              this.$message.error(message)
              return
            }
          }
          this.btnLoading = false
          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()
        })
        .catch(_ => _)
    },
    dictionaryEscape,
    //获取科目树
    async getTreeData(callback) {
      try {
        this.treeLoading = true   //开始加载时显示加载状态
        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
        }, [])
      }
    },

    //获取数据
    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
    },

    findParentId(tree, targetId) {
      // 辅助函数，递归搜索树
      function search(nodes, parentId) {
        for (const node of nodes) {
          // 如果找到目标节点，返回父节点ID
          if (node.id === targetId) {
            return parentId
          }
          // 如果有子节点，递归搜索
          if (node.children && node.children.length > 0) {
            const found = search(node.children, node.id)
            if (found) return found
          }
        }
        return null
      }

      return search(tree, null)
    },
    //左边树节点
    currentChange(nodeItem) {
      console.log(nodeItem, '999')
      if (nodeItem.id === '1766017468444450816') {
        this.isAddDisabled = true
        setQueryValue(this.params, 'roadId', 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, 'roadId', array)
      } else {
        this.isAddDisabled = false
        setQueryValue(this.params, 'roadId', [nodeItem?.id] || [])
      }
      this.treeItem = {
        ...nodeItem,
        fatherId: this.findParentId(this.treeData, nodeItem.id) || ''
      } || {}
      this.calcTableHeight(500)
      PubSub.publish('TreeItemSelected', {
        id: nodeItem?.id || '',
        name: nodeItem?.name || '',
        path: nodeItem?.path || ''
      })
      this.params.pageBean.page = 1
      this.loadData()
    },

    //修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      this.changePage('EditAddPage', row, row.compensationStatus ? '修改' : '补录')
    },

    // 改变页面
    changePage(pageName = '', row = {}, type = '') {
      if (!pageName) return
      if (!row.fatherId) {
        row.fatherId = this.findParentId(this.treeData, row.roadId) || ''
      }
      this.$emit(
        'changePage',
        pageName,
        _ => {
          PubSub.publish(pageName, row)
        },
        type || '详情'
      )
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped></style>
