<template>
  <div class="app-container">
    <el-form
        ref="postForm"
        :model="postForm"
        :rules="rules"
        label-width="121px"
        class="form-container"
    >
      <el-form-item
          label="游戏名"
          prop="name"
      >
        <el-input
            v-model="postForm.name"
            name="name"
            style="width: 50%"
            required
        />
      </el-form-item>

      <div class="one-block" v-for="(vdata, index) in postForm.versions" :key="vdata._id">
        <el-row>
          <el-col :span="12">
            <el-form-item
                label="版本名"
                :prop="'versions.'+index+'.name'"
                :rules="{
                  required: true, message: '版本名不能为空', trigger: 'blur'
                }"
            >
              <el-input
                  v-model="vdata.name"
                  style="width: 100%"
                  placeholder="用于后台区分不同版本"
                  required
              />
            </el-form-item>
            <el-form-item
                label="类型"
                :prop="'versions.'+index+'.type'"
            >
              <el-select
                  v-model="vdata.type"
                  placeholder="选择版本类型"
                  required
                  class="w100"
              >
                <el-option
                    v-for="item in versionTypes"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
                label="链接地址"
                :prop="'versions.'+index+'.url'"
                v-if="vdata.type === 0"
                :rules="{
                  required: true, message: '链接地址不能为空', trigger: 'blur'
                }"
            >
              <el-input
                  v-model="vdata.url"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item
                label="AppID"
                :prop="'versions.'+index+'.appid'"
                v-if="vdata.type === 1"
                :rules="{
                  required: true, message: 'AppID不能为空', trigger: 'blur'
                }"
            >
              <el-input
                  v-model="vdata.appid"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                  type="warning"
                  @click="removeVersion(vdata)"
              >
                移除此版本
              </el-button>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
                prop="versions.image"
                label="预览图"
            >
              <upload-image v-model="vdata.image" />
            </el-form-item>
          </el-col>
        </el-row>

      </div>

      <el-form-item>
        <el-button
            type="success"
            @click="addVersion"
        >
          添加版本
        </el-button>
        <el-button
            type="primary"
            @click="submitForm"
            v-permission="['sysgame:edit']"
        >
          保存
        </el-button>
        <el-button @click="onCancel">
          取消
        </el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import {
  defaultGameData,
  defaultGameVersionData,
  getGame,
  IGameVersion,
  saveGame
} from '@/api/game'
import { ITagView, TagsViewModule } from '@/store/modules/tags-view'
import UploadImage from '@/components/UploadImage/index.vue'
import { AppModule } from '@/store/modules/app'

@Component({
  name: 'GameEdit',
  components: {
    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({}, defaultGameData)
  private loading = false
  private rules = {
    name: [{ validator: this.validateRequire }]
  }

  private tempTagView?: ITagView
  private versionTypes = [{
    id: 0,
    name: '网页游戏'
  }, {
    id: 1,
    name: '微信小游戏'
  }]

  get lang() {
    return AppModule.language
  }

  $refs!: {
    postForm: HTMLFormElement
  }

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

  private async fetchData(id: string) {
    try {
      const { data } = await getGame(id, { /* Your params here */ })
      console.log(data)
      this.postForm = data
      // Just for test
      const title = this.lang === 'zh' ? '编辑游戏' : 'Edit Game'
      // 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 async submitForm() {
    try {
      await this.$refs.postForm.validate()
      this.loading = true
      const { data } = await saveGame(this.postForm)
      this.postForm = data
      this.loading = false
      this.$notify({
        title: 'Success',
        message: '保存成功',
        type: 'success',
        duration: 2000
      })
    } catch (err) {
      console.error('Submit Error!')
      return false
    }
  }

  private async onCancel() {
    try {
      await this.$confirm('确认不保存当前信息?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      this.$store.dispatch('delView', this.$route)
      this.$router.go(-1)
    } catch (err) {

    }
  }

  private async removeVersion(vdata: IGameVersion) {
    try {
      await this.$confirm('确认移除此版本?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      const idx = this.postForm.versions.indexOf(vdata)
      this.postForm.versions.splice(idx, 1)
      if (this.postForm.versions.length === 0) {
        this.addVersion()
      }
    } catch (err) {

    }
  }

  private addVersion() {
    this.postForm.versions.push(defaultGameVersionData)
  }
}
</script>

<style lang="scss" scoped>
.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.button {
  padding: 0;
  min-height: auto;
  float: right;
}

.image {
  width: 100%;
  display: block;
}
.one-block{
  border: 1px solid #ebebeb;
  border-radius: 3px;
  transition: .2s;
  padding: 24px;
  margin-bottom: 24px;
  margin-left: 60px;
  margin-right: 60px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
</style>
