<template>
  <div class="createPost-container">
    <el-form
        ref="postForm"
        :model="postForm"
        :rules="rules"
        label-width="120px"
        class="form-container"
    >

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item
                style="margin-bottom: 40px;"
                prop="question"
            >
              <material-input
                  v-model="postForm.question"
                  :maxlength="100"
                  name="question"
                  required
              >
                题目
              </material-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item
                style="margin-bottom: 40px;"
                label="答案:"
                prop="a1"
            >
              <el-input
                  v-model="postForm.a1"
                  placeholder="输入答案"
                  name="a1"
                  required
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
                label="评分:"
                class="postInfo-container-item"
            >
              <el-rate
                  v-model="postForm.quality"
                  :max="3"
                  :colors="['#99A9BF', '#F7BA2A', '#ff5900']"
                  :low-threshold="1"
                  :high-threshold="3"
                  style="display:inline-block"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item
                style="margin-bottom: 40px;"
                label="混淆答案1:"
            >
              <el-input
                  v-model="postForm.a2"
                  :rows="1"
                  placeholder="输入答案"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
                style="margin-bottom: 40px;"
                label="混淆答案2:"
            >
              <el-input
                  v-model="postForm.a3"
                  :rows="1"
                  placeholder="输入答案"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
                style="margin-bottom: 40px;"
                label="混淆答案3:"
            >
              <el-input
                  v-model="postForm.a4"
                  :rows="1"
                  placeholder="输入答案"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
                label="分类:"
            >
              <el-cascader-panel
                  :options="typeOptions"
                  v-model="typeSelect"
                  filterable
                  size="medium"
                  style="width: 50%"
                  v-on:change="typechange">
              </el-cascader-panel>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
                label="TAGS:"
            >
              <el-select
                  v-model="postForm.groups"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  style="width: 50%"
                  @change="tagChange"
                  placeholder="请选择">
                <el-option
                    v-for="item in tagOptions"
                    :key="item"
                    :label="item"
                    :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button
                  type="primary"
                  v-loading="loading"
                  @click="submitForm"
              >
                保存
              </el-button>
              <el-button
                  v-loading="loading"
                  style="margin-left: 10px;"
                  type="warning"
                  @click="saveNext"
              >
                保存&下一题
              </el-button>
              <el-button
                  v-loading="loading"
                  style="margin-left: 10px;"
                  type="danger"
                  @click="deleteRecord"
              >
                删除
              </el-button>
              <el-button @click="onCancel">
                取消
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { AppModule } from '@/store/modules/app'
import { ITagView, TagsViewModule } from '@/store/modules/tags-view'
import MaterialInput from '@/components/MaterialInput/index.vue'
import Sticky from '@/components/Sticky/index.vue'
import Tinymce from '@/components/Tinymce/index.vue'
import UploadImage from '@/components/UploadImage/index.vue'
import { Form } from 'element-ui'
import {
  defaultQuestionData, deleteQuestion, getAllCategory,
  getAllTags,
  getQuestion, nextQuestion,
  saveQuestion, saveTag
} from '@/api/question'

@Component({
  name: 'QuestionPrepare',
  components: {
    MaterialInput,
    Sticky,
    Tinymce,
    UploadImage
  }
})
export default class extends Vue {

  private validateRequire = (rule: any, value: string, callback: Function) => {
    if (value === '') {
      if (rule.field === 'imageURL') {
        this.$message({
          message: 'Upload cover image is required',
          type: 'error'
        })
      } else {
        this.$message({
          message: rule.field + ' 是必填的',
          type: 'error'
        })
      }
      callback(new Error(rule.field + ' 是必填的'))
    } else {
      callback()
    }
  }


  private postForm = Object.assign({}, defaultQuestionData)
  private loading = false
  private rules = {
    question: [{ validator: this.validateRequire }],
    a1: [{ validator: this.validateRequire }],
  }
  private typeOptions: any[] = []
  private typeSelect: string[] = []
  private tagSet: Set<string> = new Set()
  private tagOptions: string[] = []

  private tempTagView?: ITagView


  get lang() {
    return AppModule.language
  }


  created() {
    const id = this.$route.params && this.$route.params.id
    if (id) {
      this.fetchData(id)
    }
    this.tempTagView = Object.assign({}, this.$route)
    this.getRemoteTags()
    this.getRemoteCategory()
  }

  deactivated() {
  }

  activated() {
  }

  private async fetchData(id: string) {
    try {
      const { data } = await getQuestion(id, { /* Your params here */ })
      this.postForm = data
      this.typeSelect = [this.postForm.tag || '', this.postForm.sub_tag || '']
      // Just for test
      const title = this.lang === 'zh' ? '编辑题目' : 'Edit Question'
      // Set tagsview title
      this.setTagsViewTitle(title)
      // Set page title
      this.setPageTitle(title)
    } catch (err) {
      console.error(err)
    }
  }

  private setTagsViewTitle(title: string) {
    const tagView = this.tempTagView
    if (tagView) {
      tagView.title = `${title}-${this.postForm._id}`
      TagsViewModule.updateVisitedView(tagView)
    }
  }

  private setPageTitle(title: string) {
    document.title = `${title} - ${this.postForm._id}`
  }

  private typechange(val: string[]) {
    this.postForm.tag = this.typeSelect[0]
    this.postForm.sub_tag = this.typeSelect[1]
  }

  private async tagChange(tags: string[]) {
    console.log(`tagchange: `, tags)
    for(let tag of tags) {
      if (!this.tagSet.has(tag)) {
        this.tagSet.add(tag)
        this.tagOptions.push(tag)
        await saveTag(tag)
      }
    }
  }
  private async getRemoteTags() {
    let { data } = await getAllTags()
    console.log(data)
    this.tagSet = new Set(data)
    this.tagOptions = data
  }

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

  private async submitForm() {
    await this.saveRecord(false)
  }
  private async saveNext() {
    await this.saveRecord(true)
  }
  private async saveRecord(withNext: boolean) {
    const form = <Form>this.$refs.postForm
    try {
      await form.validate()
      this.loading = true
      this.postForm.withNext = withNext
      const {data} = await saveQuestion(this.postForm)
      this.postForm = data
      this.loading = false
      this.$notify({
        title: 'Success',
        message: '题目保存成功',
        type: 'success',
        duration: 2000
      })
    } catch (err) {
      console.error('Submit Error!')
      this.loading = false
      return false
    }
  }
  private async deleteRecord() {
    try {
      this.loading = true
      await this.$confirm('确认删除当前记录?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await deleteQuestion(this.postForm._id!)
      const {data} = await nextQuestion(this.postForm._id!)
      this.postForm = data
      this.loading = false
    } catch(e) {
      this.loading = false
    }
  }
  private async onCancel() {
    try {
      await this.$confirm('确认不保存当前记录?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      this.$store.dispatch("delView", this.$route)
      this.$router.go(-1)
    } catch(e) {

    }

  }

}
</script>


<style lang="scss" scoped>
.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}
</style>
