<template>
  <div class="app-container">
    <!-- filter -->
    <el-form ref="filterForm" :inline="true" :model="filterForm" class="filter">
      <el-form-item label="关键字" prop="key">
        <el-input v-model="filterForm.key" placeholder="关键字"/>
      </el-form-item>
      <el-form-item label="分类" prop="key">
        <el-cascader
            :options="typeOptions"
            v-model="filterForm.typeSelect"
            filterable
            clearable
            size="medium"
            >
        </el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetFilterForm">重置</el-button>
      </el-form-item>
    </el-form>
    <router-link to="/question/create">
      <el-button
          type="primary"
          icon="el-icon-edit"
          v-permission="['question:edit']"
      >
        添加
      </el-button>
    </router-link>
    <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-top:30px;"
    >
      <el-table-column
          width="180px"
          align="center"
          label="添加时间"
      >
        <template slot-scope="{row}">
          <span>{{ row.createtime | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="分类"
      >
        <template slot-scope="{row}">
          <span>{{ row.category }}</span>
        </template>
      </el-table-column>
      <el-table-column
          min-width="200px"
          label="名称"
      >
        <template slot-scope="{row}">
          <router-link
              :to="'/question/edit/'+row._id"
              class="link-type"
          >
            <span>{{ row.question }}</span>
          </router-link>
        </template>
      </el-table-column>

      <el-table-column
          label="答案"
      >
        <template slot-scope="{row}">
            <span>{{ row.a1 }}</span>
        </template>
      </el-table-column>

      <el-table-column
          label="混淆答案"
      >
        <template slot-scope="{row}">
          <span>{{ row.a2 || '' }} {{ row.a3 || '' }} {{ row.a4 || '' }}</span>
        </template>
      </el-table-column>

      <el-table-column
          label="Tags"
      >
        <template slot-scope="{row}">
          <el-tag v-for="item in row.groups" :key="item">{{ item }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
          align="center"
          width="180"
          label="操作"
          fixed="right"
      >
        <template slot-scope="scope">
          <router-link :to="'/question/edit/'+scope.row._id">
            <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                v-permission="['question:edit']"
            >
              编辑
            </el-button>
          </router-link>
          <el-button
              type="danger"
              size="small"
              style="margin-left: 10px"
              @click="handleDelete(scope)"
              v-permission="['question:delete']"
          >
            {{ $t('permission.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import Pagination from '@/components/Pagination/index.vue'
import { getShops } from '@/api/shop'
import { parseTime } from '@/utils'
import {
  deleteQuestion,
  getAllCategory,
  getAllTags,
  getQuestions,
  IQuestionData
} from '@/api/question'
import { EVENT_PUZZLE_UPDATE, EVENT_SHOP_PUZZLES_UPDATE, EventBus } from '@/utils/event-bus'

@Component({
  name: 'QuestionList',
  components: {
    Pagination
  },
  filters: {
    parseTime: (timestamp: string) => {
      return parseTime(timestamp)
    },
    parseDate: (timestamp: string) => {
      if (!timestamp) {
        return '-'
      }
      return parseTime(timestamp, '{y}-{m}-{d}')
    },
    formatCount: (count: string) => {
      if (!count) {
        return 0
      }
      return count
    }
  }
})

export default class extends Vue {
  private total = 0
  private list: IQuestionData[] = []
  private listLoading = true
  private allDepts = []
  private listQuery = {
    page: 1,
    limit: 20,
    key: '',
    tag: '',
    sub_tag: '',
    groups: ''
  }

  private typeOptions: any[] = []
  private tagSet: Set<string> = new Set()
  private tagOptions: string[] = []
  private filterForm = {
    key: '',
    typeSelect: []
  }

  $refs!: {
    filterForm: HTMLFormElement
  }

  created() {
    this.getList()
    this.getRemoteTags()
    this.getRemoteCategory()
    EventBus.$on(EVENT_PUZZLE_UPDATE, () => {
      this.getList()
    })
  }

  beforeDestory() {
    EventBus.$off(EVENT_PUZZLE_UPDATE)
  }

  private async getList() {
    this.listLoading = true
    const { data } = await getQuestions(this.listQuery)
    this.listLoading = false
    this.list = data.records
    this.total = data.total
  }

  private async handleDelete(scope: any) {
    const { $index, row } = scope
    await this.$confirm('确认删除该记录?', 'Warning', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteQuestion(row._id)
    this.list.splice($index, 1)
    this.$message({
      type: 'success',
      message: '删除成功!'
    })
  }

  private search() {
    this.filterData()
  }

  private filterData() {
    this.listQuery.key = this.filterForm.key
    if (this.filterForm.typeSelect.length > 0) {
      this.listQuery.tag = this.filterForm.typeSelect[0]
    }
    if (this.filterForm.typeSelect.length > 1) {
      this.listQuery.sub_tag = this.filterForm.typeSelect[1]
    }
    this.listQuery.page = 1
    this.getList()
  }

  private resetFilterForm() {
    this.$refs.filterForm.resetFields()
  }

  private async getRemoteDeptList(name: string) {
    const { data } = await getShops({ key: name })
    if (!data.records) return
    this.allDepts = data.records
  }

  private async getRemoteTags() {
    const { data } = await getAllTags()
    console.log(data)
    this.tagSet = new Set(data)
    this.tagOptions = data
  }

  private async getRemoteCategory() {
    const { data } = await getAllCategory()
    for (const cat of data) {
      const subArr = []
      for (const s of cat.children) {
        subArr.push({
          value: s._id,
          label: s.name
        })
      }
      this.typeOptions.push({
        value: cat._id,
        label: cat.name,
        children: subArr
      })
    }
  }
}
</script>
