<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 label="分类" prop="key">
        <el-select
            v-model="filterForm.typeSelect"
            placeholder="选择"
            name="typeSelect"
            required
            class="w100"
            multiple
            v-loading="cateLoading"
        >
          <el-option
              v-for="item in typeOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </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>
    <div class="action-bar">
      <input
          ref="excel-upload-input"
          class="excel-upload-input"
          type="file"
          accept=".xlsx, .xls"
          @change="handleClick"
      >
      <router-link :to="'/question/newshoppuzzle/' + filterForm.shop" style="margin-right: 10px;">
        <el-button
            type="primary"
            icon="el-icon-edit"
            v-permission="['shoppuzzle:edit']"
        >
          添加
        </el-button>
      </router-link>
      <el-button
          type="success"
          icon="el-icon-upload2"
          @click="handleImport"
      >
        导入Excel
      </el-button>
      <el-button
          type="warning"
          icon="el-icon-download"
          :loading="downloadLoading"
          @click="handleExport"
          v-if="multipleSelection.length>0"
      >
        {{exportBtnName}}
      </el-button>
      <el-button
          type="danger"
          icon="el-icon-delete-solid"
          @click="handleRemoveAll"
          v-if="multipleSelection.length>0"
      >
        {{deleteBtnName}}
      </el-button>
    </div>
    <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        stripe
        row-key="question"
        ref="question_table"
        @selection-change="handleSelectionChange"
        style="width: 100%;margin-top:30px;"
    >
      <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55">
      </el-table-column>
      <el-table-column
          width="180px"
          align="center"
          label="添加时间"
      >
        <template slot-scope="{row}">
          <span>{{ row.createtime | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
          min-width="200px"
          label="名称"
      >
        <template slot-scope="{row}">
          <router-link
              :to="'/question/shoppuzzle/'+row.shop+'/'+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}">
          <el-tag type="info" v-if="row.a2">{{row.a2}}</el-tag>
          <el-tag type="info" v-if="row.a3">{{row.a3}}</el-tag>
          <el-tag type="info" v-if="row.a4">{{row.a4}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          label="题目类型"
      >
        <template slot-scope="{row}">
          <span>{{ puzzleType(row.type) }}</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/shoppuzzle/'+scope.row.shop+'/'+scope.row._id">
            <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                v-permission="['shoppuzzle:edit']"
            >
              编辑
            </el-button>
          </router-link>
          <el-button
              type="danger"
              size="small"
              style="margin-left: 10px"
              @click="handleDelete(scope)"
              v-permission="['shoppuzzle: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, Watch } from 'vue-property-decorator'
import Pagination from '@/components/Pagination/index.vue'
import { getShops } from '@/api/shop'
import { formatJson, parseTime } from '@/utils'
import { IQuestionData, formatQType } from '@/api/question'
import { UserModule } from '@/store/modules/user'
import { deleteShopQuestion, getShopCategory, getShopQuestions, importQuestions } from '@/api/shoppuzzle'
import { IShopData } from '@/api/types'
import { EVENT_SHOP_PUZZLES_UPDATE, EVENT_SHOP_UPDATE, EventBus } from '@/utils/event-bus'
import { exportJson2Excel } from '@/utils/excel'
import XLSX from 'xlsx'
import { IExamQuerstion } from '@/api/exam'

@Component({
  name: 'ShopPuzzles',
  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 = false
  private cateLoading = false
  private allDepts: IShopData[] = []
  private listQuery = {
    page: 1,
    limit: 20,
    key: '',
    tag: '',
    sub_tag: '',
    groups: [],
    shop: ''
  }

  private typeOptions: any[] = []
  private filterForm = {
    key: '',
    typeSelect: [],
    shop: ''
  }

  private excelData = {
    header: null,
    results: null
  }

  private deleteBtnName = '删除所有'
  private exportBtnName = '导出所有'
  private downloadLoading = false
  private multipleSelection : IExamQuerstion[] = []

  $refs!: {
    filterForm: HTMLFormElement
    'excel-upload-input': HTMLFormElement
  }

  get userLevel() {
    return UserModule.level
  }

  private puzzleType(val: number) {
    return formatQType(val)
  }

  async created() {
    if (UserModule.level === 1) {
      await this.getRemoteDeptList()
      EventBus.$on(EVENT_SHOP_UPDATE, () => {
        this.getRemoteDeptList()
      })
    } else {
      this.filterForm.shop = UserModule.department
      this.listQuery.shop = UserModule.department
      await this.getList()
    }
    // this.getList()
    EventBus.$on(EVENT_SHOP_PUZZLES_UPDATE, () => {
      this.getList()
    })
  }

  beforeDestory() {
    EventBus.$off(EVENT_SHOP_PUZZLES_UPDATE)
    if (UserModule.level === 1) {
      EventBus.$off(EVENT_SHOP_UPDATE)
    }
  }

  private async getList() {
    this.listLoading = true
    const { data } = await getShopQuestions(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 deleteShopQuestion(this.listQuery.shop, 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
    if (this.allDepts.length > 0) {
      this.filterForm.shop = this.allDepts[0]._id!
    }
  }

  @Watch('filterForm.shop')
  private filterShopChange(val: string) {
    console.log('filterForm.shop: ', val)
    this.listQuery.shop = this.filterForm.shop
    this.getRemoteCategory()
    this.getList()
  }

  @Watch('filterForm.')
  private filerTypeChange(val: string) {
    this.listQuery.groups = this.filterForm.typeSelect
    this.getList()
  }

  private async getRemoteCategory() {
    this.cateLoading = true
    try {
      const { data } = await getShopCategory(this.listQuery.shop)
      this.typeOptions = data
      this.cateLoading = false
      this.$forceUpdate()
    } catch (err) {
      this.cateLoading = false
    }
  }

  // begin of excel

  private handleSelectionChange(val: any) {
    this.multipleSelection = val
    console.log(this.multipleSelection)
  }

  @Watch('multipleSelection')
  private selectChange() {
    this.deleteBtnName = this.multipleSelection.length > 0 ? '删除选中项' : '删除所有'
    this.exportBtnName = this.multipleSelection.length > 0 ? '导出选中项' : '导出所有'
  }

  private handleClick(e: MouseEvent) {
    const files = (e.target as HTMLInputElement).files
    if (files) {
      const rawFile = files[0] // only use files[0]
      this.upload(rawFile)
    }
  }

  private handleImport() {
    (this.$refs['excel-upload-input']).click()
  }

  private handleExport() {
    this.handleDownload()
  }

  private upload(rawFile: File) {
    this.$refs['excel-upload-input'].value = '' // Fixes can't select the same excel

    this.readerData(rawFile)
  }

  private async handleRemoveAll() {
    try {
      const str = this.multipleSelection.length > 0 ? '确定删除选中的题目' : '确定删除所有题目'
      await this.$confirm(str, 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (this.multipleSelection.length > 0) {
        for (const s of this.multipleSelection) {
          this.questions.splice(this.questions.indexOf(s), 1)
        }
        (this.$refs.question_table as any).clearSelection()
      } else {
        this.questions.length = 0
      }
      this.sliceData()
      this.$message({
        type: 'success',
        message: 'Deleted!'
      })
    } catch (err) {
      console.log(err)
    }
  }

  private handleDownload() {
    this.downloadLoading = true
    const tHeader = ['question', 'a1', 'a2', 'a3', 'a4', 'type', 'tags']
    const list = this.multipleSelection.length > 0 ? this.multipleSelection.slice(0) : this.questions.slice(0)
    this.filename = parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')
    const dataHeader = ['question', 'a1', 'a2', 'a3', 'a4', 'type', 'groups']
    const data = formatJson(dataHeader, list)
    console.log('begin generate excel')
    exportJson2Excel(tHeader, data, this.filename ? this.filename : undefined, undefined, undefined, true, 'xlsx')
    this.downloadLoading = false
  }

  private readerData(rawFile: File) {
    this.loading = true
    const reader = new FileReader()
    reader.onload = e => {
      const data = (e.target as FileReader).result
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const results = XLSX.utils.sheet_to_json(worksheet)
      this.generateData(results)
      this.loading = false
    }
    reader.readAsArrayBuffer(rawFile)
  }

  private getHeaderRow(sheet: { [key: string]: any }) {
    const headers: string[] = []
    const range = XLSX.utils.decode_range(sheet['!ref'])
    const R = range.s.r
    // start in the first row
    for (let C = range.s.c; C <= range.e.c; ++C) { // walk every column in the range
      const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
      // find the cell in the first row
      let hdr = ''
      if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
      if (hdr === '') {
        hdr = 'UNKNOWN ' + C // replace with your desired default
      }
      headers.push(hdr)
    }
    return headers
  }

  private async generateData(results: any) {
    const datas = []
    for (const _q of results) {
      if (_q.tags) {
        _q.groups = _q.tags.split(',')
        delete _q.tags
      }
      datas.push(_q)
    }
    const { data } = await importQuestions(this.filterForm.shop, { datas })
    console.log(data)
    const msg = `操作成功, 共新增${data.insert || 0}个题目, 更新${data.update || 0}个题目`
    this.$message({
      type: 'success',
      message: msg
    })
    this.getList()
  }
}
</script>

<style lang="scss" scoped>
  .el-tag{
    margin-right: 5px;
  }
  .action-bar {
    margin-bottom: 15px;
  }

  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .el-form-item{
    margin-bottom: 22px;
  }
</style>
