<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: 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
                v-if="!loading"
                :optionList="optionList"
                @search="handleSearch"
              />
            </div>
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <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 {getTree} from '@/api/patrolAndRescue/commandDispatch/statisticalReports'
import {EventDept, EventHandleTime} from '@/api/patrolAndRescue/commandDispatch/eventStatistics'
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 {
      pubSub: null,
      tableMaxHeight: '600px',
      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: 'EventDept',
      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,
    EventDept,
    EventHandleTime,
    classifyChange(item, index) {
      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) {
            lastRow.cells[0].colSpan = 2
            lastRow.cells[1].style.display = 'none'
          }
        }
      })
    },
    getSummaries(param) {
      if (this.aggregate && JSON.stringify(this.aggregate) !== '{}') {
        const {
          roadAssetLoss,
          accidentDisaster,
          constructEvent,
          geologicalDisaster,
          meteorologicalDisaster,
          socialSecurityEvent,
          otherEvent
        } = this.aggregate
        return ['合计', '', roadAssetLoss, accidentDisaster, constructEvent, geologicalDisaster, meteorologicalDisaster, socialSecurityEvent, otherEvent]
      } 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 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__body-wrapper {
  height: calc(100% - 120px) !important;
}

::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 {
  .search-box-label {
    width: 120px;
    font-size: 14px;
  }
}
</style>
