<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="$t('main.shop')" prop="key" v-if="userLevel === 1">
        <el-select
            v-model="filterForm.shop"
            :placeholder="'选择'+$t('main.shop')"
            name="shop"
            required
            class="w100"
        >
          <el-option
              v-for="item in allDepts"
              :key="item._id"
              :label="item.name"
              :value="item._id"
          />
        </el-select>
      </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="/shop/exam_new">
      <el-button
          type="primary"
          icon="el-icon-edit"
          v-permission="['shopexam:edit']"
      >
        添加
      </el-button>
    </router-link>
    <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        stripe
        highlight-current-row
        style="width: 100%;margin-top:30px;"
    >
      <el-table-column
          width="180px"
          align="center"
          label="添加时间"
      >
        <template slot-scope="{row}">
          <span>{{ row.createdAt | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
          :label="$t('main.shop')"
          prop="shop"
          v-if="userLevel === 1"
          :formatter = "formatDept"
      >
      </el-table-column>
      <el-table-column
          min-width="200px"
          label="名称"
      >
        <template slot-scope="{row}">
          <router-link
              :to="'/shop/exam_edit/'+row._id"
              class="link-type"
          >
            <span>{{ row.name }}</span>
          </router-link>
        </template>
      </el-table-column>

      <el-table-column
          label="是否启用"
          prop="active"
          :formatter="formatBool"
      >
      </el-table-column>

      <el-table-column
          label="题目类型"
          prop="source"
          :formatter="formatSource"
      >
      </el-table-column>

      <el-table-column
          align="center"
          width="180"
          label="操作"
          fixed="right"
      >
        <template slot-scope="scope">
          <router-link :to="'/shop/exam_edit/'+scope.row._id">
            <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                v-permission="['shopexam:edit']"
            >
              编辑
            </el-button>
          </router-link>
          <el-button
              type="danger"
              size="small"
              style="margin-left: 10px"
              v-permission="['shopexam:delete']"
              @click="handleDelete(scope)"
          >
            {{ $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 { IShopData } from '@/api/types'
import Pagination from '@/components/Pagination/index.vue'
import { getShops } from '@/api/shop'
import { parseTime } from '@/utils'
import { getAllCategory, getAllTags, IQuestionData } from '@/api/question'
import { deleteExam, getExams } from '@/api/exam'
import { UserModule } from '@/store/modules/user'

@Component({
  name: 'ExamList',
  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: IShopData[] = []
  private listQuery = {
    page: 1,
    limit: 20,
    key: '',
    shop: ''
  }

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

  $refs!: {
    filterForm: HTMLFormElement
  }

  get userLevel() {
    return UserModule.level
  }

  async created() {
    if (UserModule.level === 1) {
      await this.getRemoteDeptList()
    } else {
      this.filterForm.shop = UserModule.department
      this.listQuery.shop = UserModule.department
    }
    await this.getRemoteCategory()
    await this.getList()
  }

  private async getList() {
    this.listLoading = true
    const { data } = await getExams(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 deleteExam(row._id)
    this.list.splice($index, 1)
    this.$message({
      type: 'success',
      message: '删除成功!'
    })
  }

  private search() {
    this.filterData()
  }

  private filterData() {
    this.listQuery.key = this.filterForm.key
    this.listQuery.shop = this.filterForm.shop
    this.listQuery.page = 1
    this.getList()
  }

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

  private async getRemoteDeptList() {
    const { data } = await getShops({ })
    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
      })
    }
  }

  private formatDept(row: number, column: number, cellValue: string) {
    let result = '未指定'
    for (const dep of this.allDepts) {
      if (dep._id === cellValue) {
        result = dep.name
        break
      }
    }
    return result
  }

  private formatBool(row: number, column: number, cellValue: boolean) {
    return cellValue ? '是' : '否'
  }

  private formatSource(row: number, column: number, cellValue: boolean) {
    return cellValue ? '自定义' : '系统'
  }
}
</script>
