<template>
  <div class="table-page">
    <div class="table-page-content">
      <!-- 引入左侧列表组件，传递 statsClassify 数据，监听 classifyChange 事件 -->
      <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">
              <el-date-picker
                v-model="timeValue"
                :clearable="false"
                end-placeholder="结束日期"
                range-separator="至"
                start-placeholder="开始日期"
                type="daterange"
                value-format="yyyy-MM-dd"
                @change="timeChange"
              >
              </el-date-picker>
              <!-- 引入搜索组件，传递 optionList 数据，监听 search 事件 -->
              <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
                  :loading="downloadLoading"
                  class="btn btn-plus"
                  icon="el-icon-download"
                  size="mini"
                  type="success"
                  @click="exportData"
                >导出
                </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"
                >
                  <el-table-column
                    align="center"
                    label="序号"
                    type="index"
                    width="70"
                  />
                  <!-- 动态列 -->
                  <el-table-column
                    v-for="(column, index) in tableColumn"
                    :key="index"
                    :label="column.label"
                    :prop="column.prop"
                    :width="column.minWidth"
                    align="center"
                  >
                  </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 moment from 'moment'
import SearchCommon from '@/components/SearchCommon/index.vue' // 引入搜索组件
import PubSub from 'pubsub-js' // 引入事件发布-订阅库
import {TableMixin} from '@/mixins/tableMixin' // 引入表格混入
import {getSorterDirection} from '@/utils/requestWrappers' // 引入请求处理工具函数
import {dictionaryEscape} from '@/utils/dictionary' // 引入字典处理工具函数
import leftLsit from '../LeftList' // 引入左侧列表组件
import {classifyDataInJs, tableColumnInJs} from '../../classifyData' // 引入分类数据和表格列配置
import {
  accidentStatistics,
  emergencyStatistics,
  exportDataFile,
  exportDataFileEventNum,
  exportDataFileOtEventNum,
  exportDataFileTaskLedgerNum,
  exportDataFileTraffic,
  getTree,
  patrolAndRescueStatistics,
  trafficCongestionStatistics,
  trafficControlStatistics
} from '@/api/patrolAndRescue/commandDispatch/statisticalReports'

export default {
  name: 'TablePage',
  components: {
    SearchCommon,
    leftLsit
  },
  mixins: [TableMixin],
  data() {
    return {
      timeValue: [],
      typeShow: '2',
      downloadLoading: false,
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      btnLoading: false,
      tableData: [],
      optionList: [
        {
          title: '所属路段',
          prop: 'orgList',
          type: 'select',
          option: [],
          default: true
        }
      ],
      // 请求参数
      params: {
        pageBean: {pageSize: -1},
        querys: [
          {operation: 'EQUAL', property: 'startTime'},
          {operation: 'EQUAL', property: 'endTime'},
          {operation: 'IN', property: 'orgList', value: []}
        ],
        sorter: []
      },
      statsClassify: [], // 分类数据
      tableColumn: [] // 表格列配置
    }
  },
  created() {
    this.$nextTick(() => {
      const currentYear = moment().year()
      this.params.querys[0].value = moment(`${currentYear}-01-01`).format(
        'YYYY-MM-DD'
      )
      this.params.querys[1].value = moment(`${currentYear}-12-31`).format(
        'YYYY-MM-DD'
      )
      // this.params.querys[0].value = moment().subtract(1, 'weeks').format('YYYY-MM-DD')
      // this.params.querys[1].value = moment().format('YYYY-MM-DD')
      this.timeValue = [
        this.params.querys[0].value,
        this.params.querys[1].value
      ]
      this.getOrgTreeData()
      this.statsClassify = classifyDataInJs() // 初始化分类数据
      this.typeShow = this.statsClassify[0].type
      this.tableColumn = tableColumnInJs(this.statsClassify[0].type) // 初始化表格列配置
      this.$refs.classifyList?.classifyChange(this.statsClassify[0]) // 触发分类变更事件
    })
  },
  // 组件挂载时的钩子函数
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          this.handleCurrentChange(1) // 添加数据后刷新第一页
          break
        case 'edit':
          this.loadData() // 编辑数据后刷新表格
          break
      }
    })
  },
  // 组件更新前的钩子函数
  beforeUpdate() {
    this.$nextTick(() => {
      // 重新布局表格
      this.$refs['multipleSelection'].doLayout()
    })
  },
  methods: {
    //字典
    dictionaryEscape,
    // 获取排序方向方法
    getSorterDirection,

    async exportData() {
      let param = {
        startTime: this.params.querys[0].value,
        endTime: this.params.querys[1].value,
        orgList: this.params.querys[2].value || []
      }
      this.downloadLoading = true
      try {
        this.typeShow === '1'
          ? await exportDataFile(param)
          : this.typeShow === '2'
            ? await exportDataFileTaskLedgerNum(param)
            : this.typeShow === '3'
              ? await exportDataFileTraffic(param)
              : this.typeShow === '4'
                ? await exportDataFileOtEventNum(param)
                : await exportDataFileEventNum(param)
        this.$message.success(`数据导出成功`)
      } finally {
        this.downloadLoading = false
      }
    },

    // 获取路段
    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
        }
      })
    },

    timeChange() {
      this.params.querys[0].value = this.timeValue[0]
      this.params.querys[1].value = this.timeValue[1]
      this.loadData()
    },
    // 分类变更处理方法
    classifyChange(item) {
      this.typeShow = item.type
      // 更新表格列配置
      this.tableColumn = tableColumnInJs(item.type)
      // 加载数据
      this.loadData()
    },
    //获取数据
    async loadData() {
      try {
        let param = {
          startTime: this.params.querys[0].value,
          endTime: this.params.querys[1].value,
          orgList: this.params.querys[2].value || []
        }
        this.tableLoading = true
        const {value = []} =
          this.typeShow === '1'
            ? await trafficCongestionStatistics(param)
            : this.typeShow === '2'
              ? await patrolAndRescueStatistics(param)
              : this.typeShow === '3'
                ? await trafficControlStatistics(param)
                : this.typeShow === '4'
                  ? await emergencyStatistics(param)
                  : await accidentStatistics(param)
        this.tableData = value
      } finally {
        this.tableLoading = false
      }
    },

    // 改变页面
    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;
}

.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;
  }
}
</style>
