<template>
  <div class="table-page">
    <div class="table-page-content">
      <leftLsit
        ref="classifyList"
        :statsClassify="statsClassify"
        @classifyChange="classifyChange"
      ></leftLsit>
      <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[0].value"
                  end-placeholder="任务时间"
                  range-separator="至"
                  start-placeholder="任务时间"
                  style="width: 280px"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  @change="datePickerChange"
                >
                </el-date-picker>
              </div>
              <SearchCommon
                v-if="!loading"
                :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
                  :loading="downloadLoading"
                  class="btn btn-plus"
                  icon="el-icon-download"
                  size="small"
                  type="success"
                  @click="exportData"
                >导出Excel
                </el-button>
              </div>
              <div ref="tableRef" class="table-content">
                <el-table
                  id="fixRowIndexTable"
                  ref="multipleSelection"
                  v-loading="tableLoading"
                  :data="tableData"
                  :default-sort="getSorterDirection(params, true)"
                  :max-height="
                    customPagination ? tableMaxHeight - 20 : tableMaxHeight + 32
                  "
                  :row-style="checkRowIndex"
                  :summary-method="getSummaries"
                  border
                  class="table-list"
                  element-loading-background="rgba(10 ,38 ,61, 0.9)"
                  row-key="id"
                  show-summary
                  stripe
                  @select="handleSelection"
                  @selection-change="handleSelectionChange"
                  @sort-change="sortChange"
                >
                  <template v-if="hasPagination && customPagination">
                    <el-table-column
                      :index="
                        index =>
                          index +
                          1 +
                          (params.pageBeanShow.page - 1) *
                            params.pageBeanShow.pageSize
                      "
                      align="center"
                      label="序号"
                      type="index"
                      width="70"
                    />
                  </template>
                  <template v-else>
                    <el-table-column
                      :index="
                        index =>
                          index +
                          1 +
                          (params.pageBean.page - 1) * params.pageBean.pageSize
                      "
                      align="center"
                      label="序号"
                      type="index"
                      width="70"
                    />
                  </template>
                  <el-table-column
                    v-for="column in tableColumn"
                    :key="column.prop"
                    :formatter="
                      column.formatter
                        ? row => column.formatter(row)
                        : row =>
                            row[column.prop] || row[column.prop] === 0
                              ? row[column.prop]
                              : '-'
                    "
                    :label="column.label"
                    :min-width="column.minWidth"
                    :prop="column.prop"
                    align="center"
                  >
                    <template v-if="column.children">
                      <el-table-column
                        v-for="column1 in column.children"
                        :key="column1.prop"
                        :formatter="
                          column1.formatter
                            ? row => column1.formatter(row)
                            : row =>
                                row[column1.prop] || row[column1.prop] === 0
                                  ? row[column1.prop]
                                  : '-'
                        "
                        :label="column1.label"
                        :min-width="column1.minWidth"
                        :prop="column1.prop"
                        align="center"
                      ></el-table-column>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination
                  v-if="hasPagination && !customPagination"
                  ref="paginationPanel"
                  :pageResult="params.pageBean"
                  style="margin-top: 10px"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
                <pagination
                  v-if="hasPagination && customPagination"
                  ref="paginationPanel"
                  :pageResult="params.pageBeanShow"
                  style="margin-top: 10px"
                  @size-change="handleSizeChangeCustom"
                  @current-change="handleCurrentChangeCustom"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  InspectionContent,
  InspectionContentExport,
  InspectionDept,
  InspectionDeptExport,
  InspectionTaskCompletion,
  InspectionTaskCompletionExport,
  InspectionUser,
  InspectionUserExport
} from '@/api/patrolAndRescue/roadWatch/inspectionStats'
import {getTree} from '@/api/patrolAndRescue/commandDispatch/statisticalReports'
import pagination from '@/components/SuperPagination/index.vue'
import SearchCommon from '@/components/SearchCommon/index.vue'
import PubSub from 'pubsub-js'
import {TableMixin} from '@/mixins/tableMixin'
import {getSorterDirection, refineRequestBody, setQueryValue} from '@/utils/requestWrappers'
import {dictionaryEscape} from '@/utils/dictionary'
import leftLsit from '../LeftList'
import {classifyDataInJs, optionListInJs, paramsListInJs, tableColumnInJs} from '../../classifyData'

export default {
  name: 'TablePage',
  components: {
    pagination,
    SearchCommon,
    leftLsit
  },
  mixins: [TableMixin],
  data() {
    return {
      downloadLoading: false,
      pubSub: null,
      tableMaxHeight: '500px',
      tableLoading: true,
      btnLoading: false,
      tableData: [],
      optionList: [],
      params: {
        pageBean: {pageSize: -1, page: 1, total: 0},
        pageBeanShow: {pageSize: 20, page: 1, total: 0},
        querys: [{operation: 'BETWEEN', property: 'taskDate'}]
      },
      statsClassify: [],
      tableColumn: [],
      loading: false,
      hasPagination: true,
      customPagination: false,
      activeType: 'InspectionDept',
      originalData: [],
      aggregate: {}
    }
  },
  created() {
  },
  mounted() {
    this.loading = true
    this.$nextTick(() => {
      this.statsClassify = classifyDataInJs()
      this.$refs.classifyList?.classifyChange(this.statsClassify[0])
      this.loading = false
    })
  },
  beforeUpdate() {
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    InspectionDept,
    InspectionUser,
    InspectionContent,
    InspectionDeptExport,
    InspectionUserExport,
    InspectionContentExport,
    InspectionTaskCompletion,
    InspectionTaskCompletionExport,
    classifyChange(item, index) {
      this.$nextTick(() => {
        // 使用组件根元素的 querySelector 更安全
        const tableWrapper = this.$el?.querySelector('.el-table__body-wrapper')
        if (tableWrapper) {
          // 移除可能存在的旧样式类
          tableWrapper.classList.remove('custom-height-140', 'custom-height-180')
          // 根据类型添加新样式类
          if (item.type === 'InspectionUser' || item.type === 'InspectionDept') {
            tableWrapper.classList.add('custom-height-140')
          } else {
            tableWrapper.classList.add('custom-height-100')
          }
        }
      })

      // if (item.type === 'InspectionTaskCompletion') {
      this.getOrgTreeData()
      // }
      this.loading = true
      this.activeType = item.type
      this.tableColumn = tableColumnInJs(item.type)
      this.optionList = optionListInJs(item.type)
      this.params = paramsListInJs(item.type)
      this.hasPagination = this.statsClassify[index].hasPagination
      this.customPagination = this.statsClassify[index].customPagination
      this.loading = false
      this.loadData()
      this.$nextTick(() => {
        this.$refs['multipleSelection'].doLayout()
      })
      // 重置分页
    },
    checkRowIndex({row, rowIndex}) {
      // 监听行索引，手动处理合并
      this.$nextTick(() => {
        const table = document.querySelector('#fixRowIndexTable')
        if (table && rowIndex === this.tableData.length - 1) {
          const lastRow = table.querySelector('.el-table__footer-wrapper tr')
          if (lastRow) {
            if (this.activeType === 'InspectionDept') {
              lastRow.cells[0].colSpan = 3
              lastRow.cells[1].style.display = 'none'
              lastRow.cells[2].style.display = 'none'
              lastRow.cells[3].style.display = 'revert'
            } else if (this.activeType === 'InspectionUser') {
              lastRow.cells[0].colSpan = 4
              lastRow.cells[1].style.display = 'none'
              lastRow.cells[2].style.display = 'none'
              lastRow.cells[3].style.display = 'none'
            } else if (this.activeType === 'InspectionContent') {
              lastRow.cells[0].colSpan = 2
              lastRow.cells[1].style.display = 'none'
              lastRow.cells[2].style.display = 'revert'
              lastRow.cells[3].style.display = 'revert'
            } else {
              lastRow.cells[0].colSpan = 2
              lastRow.cells[1].style.display = 'none'
              lastRow.cells[2].style.display = 'revert'
              lastRow.cells[3].style.display = 'revert'
            }
          }
        }
      })
    },
    getSummaries(param) {
      // console.log(this.activeType, '000000', this.aggregate)
      if (this.aggregate && JSON.stringify(this.aggregate) !== '{}') {
        if (this.activeType === 'InspectionDept') {
          const {taskMileage, taskTime, taskNum, outlierPoint, handleAll, handleCenter, handleScene} = this.aggregate
          return ['合计', '', '', taskMileage, taskTime, taskNum, outlierPoint, handleAll, handleCenter, handleScene]
        } else if (this.activeType === 'InspectionUser') {
          const {taskMileage, taskTime, taskNum, outlierPoint, handleAll, handleCenter, handleScene} = this.aggregate
          return ['合计', '', '', '', taskMileage, taskTime, taskNum, outlierPoint, handleAll, handleCenter, handleScene]
        } else if (this.activeType === 'InspectionContent') {
          const {taskNum, outlierPoint, handleAll, disposalAll} = this.aggregate
          return ['合计', '', taskNum, outlierPoint, handleAll, disposalAll]
        } else {
          const {taskNum, taskFinishNum, taskFinishRate, pointNum, pointFinishNum, pointFinishRate} = this.aggregate
          return ['合计', '', taskNum, taskFinishNum, taskFinishRate + '%', pointNum, pointFinishNum, pointFinishRate + '%']
        }
      } else {
        return []
      }
    },
    // 获取路段
    async getOrgTreeData() {
      let {value} = await getTree()
      let array = value.reduce((acc, item) => acc.concat(item.roadList), [])
      this.optionList[0].option = array.map((item, index) => {
        return {
          value: item.id,
          ...item
        }
      })
    },
    // 导出
    async exportData() {
      this.params.pageBean.total = 0
      if (this.customPagination) {
        this.params.pageBeanShow.total = 0
        this.originalData = []
      }
      const API = this[this.activeType + 'Export']
      try {
        this.downloadLoading = true
        await API(refineRequestBody(this.params))
        this.$message.success('数据导出成功')
      } finally {
        this.downloadLoading = false
      }
    },

    //获取数据
    async loadData() {
      // 重置数据
      this.tableData = []
      this.params.pageBean.total = 0
      if (this.customPagination) {
        this.params.pageBeanShow.total = 0
        this.originalData = []
      }
      const API = this[this.activeType]
      try {
        this.tableLoading = true
        const {value = {}, urlKey = ''} = await API(
          refineRequestBody(this.params)
        )
        this.aggregate = value.total
        if (urlKey === this.activeType) {
          this.params.pageBean.total = value.data?.length || 0
          if (this.customPagination) {
            // 手动分页数据
            this.params.pageBeanShow.total = value.data?.length || 0
            this.customPickerData(value.data)
          } else {
            this.tableData = value.data
          }
        }
      } finally {
        this.tableLoading = false
      }
    },
    customPickerData(originalData) {
      this.originalData = originalData
      this.tableData = originalData.slice(
        (this.params.pageBeanShow.page - 1) * this.params.pageBeanShow.pageSize,
        this.params.pageBeanShow.page * this.params.pageBeanShow.pageSize
      )
    },
    // 时间范围切换
    datePickerChange(val) {
      setQueryValue(this.params, 'inspectTime', val)
      this.params.pageBean.page = 1
      this.loadData()
    },

    handleSizeChangeCustom(val) {
      // 自定义分页
      this.params.pageBeanShow.pageSize = val
      this.customPickerData(this.originalData)
    },
    handleCurrentChangeCustom(val) {
      // 自定义分页
      this.params.pageBeanShow.page = val
      this.customPickerData(this.originalData)
    },
    // 改变页面
    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>
::v-deep .el-table__footer-wrapper tbody td.el-table__cell {
  border-top: 1px solid #1f5a8f;
  border-right: 1px solid #1f5a8f;
}

::v-deep .el-table .el-table__row .el-table__cell {
  border-right: 1px solid #1f5a8f;
  border-bottom: 1px solid #1f5a8f;
}

::v-deep .el-table .el-table__header-wrapper .el-table__header .el-table__cell {
  border-color: #1f5a8f !important;
}

::v-deep .el-table th.el-table__cell > .cell {
  white-space: pre !important;
}

.stats-classify {
  padding: 10px 16px;
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;

  .classify-item {
    height: 40px;
    line-height: 40px;
    cursor: pointer;
    padding-bottom: 10px;
    font-size: 14px;
    text-align: center;
    border: 1px solid #205e94;
    border-radius: 5px;
    box-sizing: border-box;
    margin-bottom: 10px;

    &:hover {
      color: #43a1ff;
      box-shadow: 0px 3px 10px rgba(0, 0, 0, 0.2);
    }
  }

  .active {
    color: #43a1ff;
  }
}

.table-page {
  .basis {
    min-width: 240px !important;
  }

  .search-box-label {
    width: 100px;
    font-size: 14px;
  }
}
</style>
