<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input
        v-model="listQuery.keyword"
        style="width:200px;margin-right:10px"
        class="filter-item"
        placeholder="请输入关键字"
        clearable
      /> -->
      <el-select v-model="listQuery.source" clearable class="filter-item" style="margin-right: 10px" placeholder="请选择积分来源">
        <el-option v-for="item of sourceOptions" :key="item.value" v-bind="item" />
      </el-select>
      <el-date-picker
        v-model="listQuery.dateArr"
        type="datetimerange"
        class="filter-item"
        style="margin-right: 10px"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="timestamp"
        align="right"
        clearable
      />
      <el-cascader
        v-model="listQuery.regionIds"
        class="filter-item"
        style="width:240px"
        :options="regions"
        :props="{ checkStrictly: true }"
        placeholder="行政区域"
        clearable
      />
      <el-button
        type="primary"
        style="margin-left:10px"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        :loading="exportLoading"
        icon="el-icon-download"
        type="primary"
        style="margin-left:10px"
        @click="handleExport"
      >导出</el-button>
    </div>
    <el-table :data="list" border style="width: 100%">
      <el-table-column label="用户名" prop="residentInformation.name" />
      <el-table-column label="积分来源" prop="source">
        <template slot-scope="scope">
          <span>{{
            scope.row.source | optionsFilter(sourceOptions)
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="获取积分数" prop="num" />

      <el-table-column label="获取时间">
        <template slot-scope="scope">
          <span>{{
            scope.row.createDate | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="listQuery.lastPageIndex"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { recordList } from '@/api/fingertipIntegral'
import { getRegions } from '@/api/region'
import { sourceOptions } from './options'
export default {
  components: { Pagination },
  filters: {
    optionsFilter(value, options = []) {
      const findItem = options.find((option) => option.value === value)
      if (findItem) {
        return findItem.label
      }
      return ''
    }
  },
  data() {
    return {
      total: 0,
      listQuery: {
        lastPageIndex: 1,
        // params: {},
        size: 10,
        category: undefined,
        id: undefined,
        innerCategory: undefined,
        keyword: undefined,
        source: undefined,
        status: undefined,
        userId: undefined,
        dateArr: [],
        regionIds: []
      },
      list: undefined,

      regionSearchVal: undefined,
      regions: [],
      exportLoading: false,

      sourceOptions
    }
  },
  watch: {
    'listQuery.lastPageIndex': {
      handler(val) {
        this.getList()
      },
      deep: true // true 深度监听
    }
  },
  created() {
    this.getList()
    this.getRegions()
  },
  methods: {
    getList() {
      const listQuery = JSON.parse(JSON.stringify(this.listQuery))
      const { dateArr, regionIds } = listQuery
      if (dateArr) {
        listQuery.startDate = dateArr[0] / 1000
        listQuery.endDate = dateArr[1] / 1000
      }
      listQuery.regionIds = regionIds.join(',')
      recordList(listQuery).then(res => {
        this.list = res.d.records
        this.total = res.d.total
        // this.pageSize = res.d.pageSize
      })
    },
    getRegions() {
      getRegions().then(res => {
        const tempData = res.d
        const countyArr = [] // 县,1
        tempData.map(county => {
          const countyObj = {
            value: county.root.id,
            label: county.root.name,
            disabled: !county.root.check,
            children: []
          }
          countyArr.push(countyObj)
          county.node.map(town => {
            const townObj = {
              value: town.root.id,
              label: town.root.name,
              disabled: !town.root.check,
              children: []
            }
            countyObj.children.push(townObj)
            town.node.map(country => {
              townObj.children.push({
                value: country.root.id,
                label: country.root.name,
                disabled: !country.root.check
              })
            })
          })
        })
        this.regions = countyArr
      })
    },
    handleExport() {
      const that = this
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['用户名', '积分来源', '获取积分数', '获取时间']
        const filterVal = ['residentInformation.name', 'source', 'num', 'createDate']
        this.exportLoading = true
        const listQuery = JSON.parse(JSON.stringify(this.listQuery))
        const { dateArr, regionIds } = listQuery
        if (dateArr) {
          listQuery.startDate = dateArr[0] / 1000
          listQuery.endDate = dateArr[1] / 1000
        }
        listQuery.regionIds = regionIds.join(',')
        listQuery.size = 999999
        recordList(listQuery).then(res => {
          setTimeout(() => {
            this.exportLoading = false
          }, 3000)

          const data = that.formatJson(filterVal, res.d.records)
          excel.export_json_to_excel({
            header: tHeader,
            data: data,
            filename: '积分流水'
          })
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          let value
          if (j === 'createDate') {
            value = this.$options.filters['parseTime'](v[j])
          } else if (j === 'residentInformation.name') {
            value = v['residentInformation']['name']
          } else if (j === 'source') {
            value = this.$options.filters['optionsFilter'](v[j], sourceOptions)
          } else {
            value = v[j]
          }
          // if (!value && value !== 0) value = "N/A";
          return value
        })
      )
    },
    handleSearch() {
      const { listQuery } = this
      this.listQuery.lastPageIndex = 1
      Object.keys(listQuery).forEach(key => {
        if (listQuery[key] === '') listQuery[key] = undefined
      })
      this.getList()
    }
  }
}
</script>

<style></style>
