<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="rangeTime"
                  :default-time="['00:00:00', '23:59:59']"
                  end-placeholder="巡检时间（结束）"
                  range-separator="至"
                  start-placeholder="巡检时间（开始）"
                  style="width: 360px"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @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="isAablesd"
                  class="btn btn-plus"
                  icon="el-icon-plus"
                  size="small"
                  type="primary"
                  @click="handleAddPage"
                >
                  添加
                </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"
                  :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"
                  @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
                    :formatter="({roadName}) => roadName || '-'"
                    align="center"
                    label="路段名称"
                    min-width="100"
                    prop="confName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="
                      ({checkType}) =>
                        dictionaryEscape('spxj-jclx', checkType, {
                          congruent: false,
                        }) || '-'
                    "
                    align="center"
                    label="检查类型"
                    min-width="70"
                    prop="checkType"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="
                      ({inspectionType}) =>
                        dictionaryEscape('spxj-xjlx', inspectionType, {
                          congruent: false,
                        }) || '-'
                    "
                    align="center"
                    label="巡检类型"
                    min-width="70"
                    prop="inspectionType"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="巡检地点"
                    min-width="100"
                    prop="placeName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="巡检结果"
                    min-width="70"
                    prop="inspectionResult"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <i
                        v-if="row.inspectionResult === '2'"
                        class="el-icon-close"
                        style="color: #f56c6c; font-size: 15px"
                        title="异常"
                      ></i>
                      <i
                        v-if="row.inspectionResult === '1'"
                        class="el-icon-check"
                        style="color: #67c23a; font-size: 15px"
                        title="正常"
                      ></i>
                    </template>
                  </el-table-column>
                  <el-table-column
                    :formatter="
                      ({inspectionDate, inspectionTime}) =>
                        inspectionDate + ' ' + inspectionTime
                    "
                    align="center"
                    label="巡检时间"
                    min-width="120"
                    prop="inspectionDate"
                    show-overflow-tooltip
                    sortable
                  />
                  <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>
                    </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 {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 treeSide from '@/components/treeSide/index.vue'
import {tableData, taskDelete} from '@/api/patrolAndRescue/videoPatrol/videoPatrolRecord'
import PubSub from 'pubsub-js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {orgTree} from '@/api/tree'
import moment from 'moment'

export default {
  name: 'TablePage',
  components: {
    pagination,
    SearchCommon,
    treeSide
  },
  mixins: [TableMixin],
  data() {
    return {
      isAablesd: true,
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      treeLoading: true,
      treeData: [], //左边树
      treeItem: {}, //左边树选中的节点
      defaultProps: {
        children: 'children', //子节点
        label: 'name' //节点标签
      },
      btnLoading: false,
      tableData: [],
      rangeTime: [
        moment().format('YYYY-MM-DD 00:00:00'),
        moment().format('YYYY-MM-DD 23:59:59')
      ],
      optionList: [
        {
          title: '路段名称',
          prop: 'roadName',
          type: 'input',
          default: true
        },
        {
          title: '巡检结果',
          prop: 'inspectionResult',
          type: 'select',
          multiple: true,
          option: getDictionaryByCode('spxj-xjjg')
        },
        {
          title: '检查类型',
          prop: 'checkType',
          type: 'select',
          option: getDictionaryByCode('spxj-xjlx'),
          multiple: true
        },
        {
          title: '巡检类型',
          prop: 'inspectionType',
          type: 'select',
          option: getDictionaryByCode('spxj-jclx'),
          multiple: true
        }
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'LIKE', property: 'roadName'},
          {operation: 'IN', property: 'checkType'},
          {operation: 'IN', property: 'inspectionType'},
          {operation: 'IN', property: 'inspectionResult'},
          {
            operation: 'BETWEEN',
            property: 'inspectionDate',
            relation: 'AND',
            value: [
              moment().format('YYYY-MM-DD'),
              moment().format('YYYY-MM-DD')
            ]
          },
          {
            operation: 'BETWEEN',
            property: 'inspectionTime',
            relation: 'AND',
            value: [moment().format('00:00:00'), moment().format('23:59:59')]
          },
          {operation: 'IN', property: 'regionId'}
        ],
        sorter: [
          {direction: 'DESC', property: 'inspectionDate'},
          {direction: 'DESC', property: 'inspectionTime'}
        ]
      }
    }
  },
  created() {
    // 获取树形目录-
    this.getOrgTreeData()
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          this.handleCurrentChange(1)
          break
        case 'edit':
          this.loadData()
          break
      }
    })
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    // 时间范围切换
    datePickerChange(val) {
      let date = '',
        time = ''
      if (val && val.length > 0) {
        let [start, end] = val
        const startDate = moment(start).format('YYYY-MM-DD')
        const endDate = moment(end).format('YYYY-MM-DD')
        const startTime = moment(start).format('HH:mm:ss')
        const endTime = moment(end).format('HH:mm:ss')
        date = [startDate, endDate]
        time = [startTime, endTime]
      }
      setQueryValue(this.params, 'inspectionDate', date)
      setQueryValue(this.params, 'inspectionTime', time)
      this.params.pageBean.page = 1
      this.loadData()
    },
    // 获取公司树-异步方法，用于从后端获取树形数据
    async getOrgTreeData() {
      try {
        this.treeLoading = true
        let {value} = await orgTree() // 调用 API 获取树形数据
        this.treeData = [value]
      } finally {
        this.loadDataPre()
        this.treeLoading = false // 无论成功或失败，都关闭加载状态
      }
    },
    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
    },
    loadDataPre() {
      // 回调中默认选中第一项并将其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.treeItem?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 'regionId', array)
      this.loadData() //加载表格数据
    },
    //左边树节点，点击选择
    currentChange(nodeItem) {
      if (nodeItem.id === '1766017468444450816') {
        this.isAablesd = true
        setQueryValue(this.params, 'regionId ', this.extractIds(nodeItem))
      } else if (nodeItem.children && nodeItem.children.length > 0) {
        this.isAablesd = true
        const array = nodeItem.children.map(item => item.id)
        setQueryValue(this.params, 'regionId ', array)
      } else {
        this.isAablesd = false
        setQueryValue(this.params, 'regionId ', [nodeItem?.id] || [])
      }
      // 修改对应的字段值--重点-点击选择传id
      // setQueryValue(this.params, 'regionId', nodeItem?.id || '') //将选中的树节点的 id 设置为查询参数的一部分。
      this.treeItem = nodeItem || {}
      this.calcTableHeight(500)
      this.params.pageBean.page = 1
      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) => ({
          ...i
        }))
      } finally {
        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 taskDelete(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((_) => _)
    },
    //
    handleAddPage() {
      this.changePage('EditAddPage', {
        regionId: this.treeItem.id,
        regionName: this.treeItem.name
      })
    },
    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return

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

<style lang="scss" scoped>
.table-page {
  .basis {
    min-width: 400px !important;
  }
}
</style>
