<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
                  :disabled="isAddDisabled"
                  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>
              </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="50" />
                  <el-table-column
                    :index="
                      index =>
                        index +
                        1 +
                        (params.pageBean.page - 1) * params.pageBean.pageSize
                    "
                    align="center"
                    label="序号"
                    type="index"
                    width="60"
                  />
                  <el-table-column
                    :formatter="({roadName}) => roadName || '-'"
                    align="center"
                    label="所属路段"
                    min-width="70"
                    prop="roadName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({teamName}) => teamName || '-'"
                    align="center"
                    label="巡检队伍"
                    min-width="70"
                    prop="teamName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({startPatrolName}) => startPatrolName || '-'"
                    align="center"
                    label="开始巡检站"
                    min-width="70"
                    prop="startPatrolName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({endPatrolName}) => endPatrolName || '-'"
                    align="center"
                    label="结束巡检站"
                    min-width="70"
                    prop="endPatrolName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="
                      ({inspectType}) =>
                        dictionaryEscape('wflx-xjrw', inspectType) || '-'
                    "
                    align="center"
                    label="往返类型"
                    min-width="70"
                    prop="inspectType"
                    show-overflow-tooltip
                    sortable="custom"
                  />
                  <el-table-column
                    :formatter="
                      ({planType}) =>
                        dictionaryEscape('xjlx-xjrw', planType) || '-'
                    "
                    align="center"
                    label="巡检类型"
                    min-width="70"
                    prop="planType"
                    show-overflow-tooltip
                    sortable="custom"
                  />
                  <el-table-column
                    :formatter="
                      ({workclass}) =>
                        dictionaryEscape('bc-xjrw', workclass) || '-'
                    "
                    align="center"
                    label="班次"
                    min-width="60"
                    prop="workclass"
                    show-overflow-tooltip
                    sortable="custom"
                  />
                  <el-table-column
                    :formatter="
                      ({frequency}) => dictionaryEscape('xjzqc', frequency)
                    "
                    align="center"
                    label="任务频率"
                    min-width="70"
                    prop="frequency"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="暂停/运行计划"
                    min-width="80"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <el-switch
                        v-model="row.isEnable"
                        @change="val => enableDisable(val, row)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    min-width="140"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <el-link
                        :underline="false"
                        type="warning"
                        @click.stop="executeConfiguration(row)"
                      >
                        执行单次计划
                      </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 pagination from '@/components/SuperPagination/index.vue'
import {TableMixin} from '@/mixins/tableMixin'
import SearchCommon from '@/components/SearchCommon/index.vue'
import PubSub from 'pubsub-js'
import {getSorterDirection, refineRequestBody, setQueryValue} from '@/utils/requestWrappers'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {executeJob, tableData, tableDelete, toggleTriggerRun} from '@/api/patrolAndRescue/roadWatch/inspectionPlan'
import {tableData as alongRouteInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/alongRouteInfo'
import treeSide from '@/components/treeSide/index.vue'
import {getTree} from '@/api/tree'

export default {
  name: 'TablePage',
  components: {
    treeSide,
    pagination,
    SearchCommon
  },
  mixins: [TableMixin],
  data() {
    return {
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      btnLoading: false,
      treeLoading: true,
      treeItem: {},
      treeData: [], //左边树
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      optionList: [
        {title: '所属路段编码', prop: 'roadCode', type: 'input', default: true},
        {
          title: '巡检类型',
          prop: 'planType',
          type: 'select',
          option: getDictionaryByCode('xjlx-xjrw'),
          multiple: true
        },
        {
          title: '班次',
          prop: 'workclass',
          type: 'select',
          option: getDictionaryByCode('bc-xjrw'),
          multiple: true
        },
        {
          title: '开始巡检站',
          prop: 'startPatrolId',
          type: 'select',
          option: [],
          multiple: true
        },
        {
          title: '结束巡检站',
          prop: 'endPatrolId',
          type: 'select',
          option: [],
          multiple: true
        },
        {
          title: '往返类型',
          prop: 'inspectType',
          type: 'select',
          option: getDictionaryByCode('wflx-xjrw'),
          multiple: true
        }
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 'roadId'},
          {operation: 'LIKE', property: 'roadCode'},
          {operation: 'IN', property: 'planType'},
          {operation: 'IN', property: 'workclass'},
          {operation: 'IN', property: 'startPatrolId'},
          {operation: 'IN', property: 'endPatrolId'},
          {operation: 'IN', property: 'inspectType'}
        ],
        sorter: [
          {direction: 'DESC', property: 'createTime'},
          {direction: '', property: 'inspectType'},
          {direction: '', property: 'planType'},
          {direction: '', property: 'workclass'}
        ]
      },
      isAddDisabled: true
    }
  },
  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)
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 'roadId ', array)
      // setQueryValue(this.params, 'roadId', this.treeItem?.id || '')
      this.getAlongRouteInfo()
      this.loadData()
    })
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          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
    },
    // 获取路段树
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true
        let {value} = await getTree()
        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') {
        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] || [])
      }
      // 判断是否是一级目录（有 children 属性）
      // if (nodeItem.children && nodeItem.children.length > 0) {
      //   this.isAddDisabled = true // 禁用新增按钮
      //   // this.$message.warning('请选择二级目录进行新增操作')
      //   const array = nodeItem.children.map(item => item.id)
      //   setQueryValue(this.params, 'roadId ', array)
      // } else {
      //   this.isAddDisabled = false // 启用新增按钮
      //   // 修改对应的字段值
      //   setQueryValue(this.params, 'roadId ', [nodeItem?.id] || [])
      // }
      this.params.pageBean.page = 1
      this.calcTableHeight(500)
      PubSub.publish('TreeItemSelected', nodeItem)
      this.treeItem = nodeItem || {}
      this.loadData()
    },

    //获取数据
    async loadData() {
      try {
        this.tableLoading = true
        const {total = 0, rows = []} = await tableData(
          refineRequestBody(this.params)
        )
        this.params.pageBean.total = total
        this.tableData = rows.map(i => ({
          isEnable: i.taskStatus === 'NORMAL',
          ...i
        }))
      } finally {
        this.tableLoading = false
      }
    },

    // 开启暂停计划
    async enableDisable(val, row) {
      this.clickTimer = true
      setTimeout(_ => (this.clickTimer = false))
      try {
        const {state} = await toggleTriggerRun(row.id)
        if (state) {
          row.taskStatus = val ? 'NORMAL' : 'PAUSED'
          this.$message[val ? 'success' : 'warning'](
            `巡检计划已${val ? '运行' : '暂停'}`
          )
        } else {
          row.isEnable = !val
        }
      } catch {
        row.isEnable = !val
      }
    },

    // 执行巡检计划
    executeConfiguration(row) {
      this.clickTimer = true
      setTimeout(_ => (this.clickTimer = false))
      if (!row.id) return
      this.$confirm(`是否执行单次当前巡检计划`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const {state} = await executeJob(row.id)
          if (state) {
            this.$message.success(`巡检计划执行成功`)
            await this.loadData()
          }
        })
        .catch(_ => _)
    },

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

    //修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      if (row.taskStatus === 'NORMAL')
        return this.$message.warning('需暂停当前巡检计划')
      this.changePage('EditAddPage', row)
    },

    //获取沿线设备信息
    async getAlongRouteInfo() {
      // 获取沿线设施
      let {rows = []} = await alongRouteInfoInter(refineRequestBody(), 'table')
      rows = rows.map(i => ({
        ...i,
        value: i.id
      }))
      this.optionList[3].option = rows
      this.optionList[4].option = rows
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      // 传递当前选中的树节点信息
      const payload = row.id
        ? row
        : {
          catalogId: this.treeItem.id,
          orgName: this.treeItem.name,
          path: this.treeItem.path,
          code: this.treeItem.code,
          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>
