<template>
  <div>
    <div class="info-header">
      <p class="info-title">基本玩法</p>
    </div>
    <el-divider class="mini-divider-table" />
    <div class="play-container">
      <el-button
        class="play-option-edit"
        size="mini"
        icon="el-icon-plus"
        type="primary"
        :disabled="localToyPlayList && localToyPlayList.length > 5"
        @click="handleAddTab"
      >添加玩法</el-button>
      <el-tabs
        v-model="activeTab"
        class="tabs-play"
        type="border-card"
        closable
        @tab-add="handleAddTab"
        @tab-remove="handleRemoveTab"
      >
        <el-tab-pane v-for="(item, index) in localToyPlayList" :key="index" :label="`玩法${index + 1}`" :name="index + ''">
          <el-form :ref="`form${index}`" class="standard-form" :model="item" size="mini" label-width="80px">
            <el-form-item
              label="玩法名称"
              prop="gameplayName"
              :rules="{
                required: true, message: '玩法名称不能为空', trigger: 'blur'
              }"
            >
              <el-input v-model="item.gameplayName" placeholder="请输入玩法名称" clearable />
            </el-form-item>
            <el-form-item
              label="玩法类型"
              prop="gameplayType"
              :rules="{
                required: true, message: '玩法类型不能为空', trigger: 'blur'
              }"
            >
              <el-radio-group v-model="item.gameplayType">
                <el-radio
                  v-for="(item, index) in dict.type[DictType.toy_gameplay_type]"
                  :key="index"
                  :label="item.value"
                  :value="item.value"
                >
                  {{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="玩法水平" porp="gameplayLevel">
              <el-radio-group v-model="item.gameplayLevel">
                <el-radio
                  v-for="level in dict.type[DictType.toy_gameplay_level]"
                  :key="level.value"
                  :label="level.value"
                >{{ level.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="相关视频">
              <div class="video-form-item">
                <upload-button
                  v-loading="uplaodVideoloading"
                  list-type="picture-card"
                  class="upload-video"
                  accept=".mp4"
                  :limit="6"
                  :disabled="fileList[index] && fileList[index].length > 5"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :on-progress="onProgress"
                  :on-success="({ code, msg, data }) => handleUploadSuccess({ code, msg, data }, index)"
                >
                  <el-button
                    size="small"
                    type="text"
                    :disabled="fileList[index] && fileList[index].length > 5"
                  >点击上传</el-button>
                </upload-button>
                <span class="form-tip ml10">注：仅支持.mp4格式，不超过 1G，可上传1~6个视频</span>
              </div>

              <div class="video-container">
                <div v-for="video in fileList[index]" :key="video.id" class="video-position">
                  <video class="video-wrapper" :src="video.url" controls="controls">
                    您的浏览器不支持该格式的视频
                  </video>
                  <i class="remove-icon el-icon-circle-close text-danger" @click="handleRemoveVideo(index, video.id)" />
                </div>
              </div>
            </el-form-item>
            <el-form-item label="玩法说明" prop="description">
              <editor v-model="item.description" :min-height="192" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>

import DictType from '@/utils/dict/DictType'
import { fetchFileUrl } from '@/utils'
import UploadButton from '@/components/Upload/UploadButton'
const initPlay = () => {
  return {
    gameplayNumber: '',
    gameplayName: '',
    gameplayType: null,
    gameplayLevel: '',
    description: ''
  }
}
export default {
  name: 'EditPlay',
  dicts: [DictType.toy_gameplay_type, DictType.toy_gameplay_level],
  components: {
    UploadButton
  },
  props: {
    toyPlayList: {
      type: Array,
      default: () => [initPlay()]
    }
  },
  data() {
    return {
      DictType,
      fileList: {},
      activeTab: '0',
      uplaodVideoloading: false
    }
  },
  computed: {
    localToyPlayList() {
      return this.toyPlayList
    }
  },
  watch: {
    localToyPlayList: {
      handler(val) {
        if (val && val.length > 0) {
          val.forEach((item, index) => {
            if (item.fileId) {
              fetchFileUrl(item.fileId).then(data => {
                this.fileList[index] = data
                this.$forceUpdate()
              })
            }
          })
        }
      },
      immediate: true
    }
  },
  methods: {
    handleAddTab() {
      const index = this.localToyPlayList.length - 1
      this.$refs[`form${index}`][0].validate(valid => {
        if (valid && this.localToyPlayList.length < 6) {
          this.localToyPlayList.push(initPlay())
          this.activeTab = index + 1 + ''
        }
      })
    },
    handleRemoveTab(targetName) {
      const index = Number(targetName)
      if (index !== 0) {
        this.$modal.confirm(`是否确认 刪除玩法${index + 1}？`).then(() => {
          const removePlay = this.localToyPlayList[index]
          if (removePlay.id) {
            this.$emit('remove-play', removePlay)
            this.activeTab = '0'
          } else {
            this.localToyPlayList.splice(index, 1)
            this.activeTab = this.localToyPlayList.length - 1 + ''
          }
        })
      }
    },
    beforeUpload(file) {
      const isLt2G = file.size / 1024 / 1024 / 1024 < 1
      if (!isLt2G) this.$message.error('上传头像视频大小不能超过 1G!')
      return isLt2G
    },
    onProgress(event, file, fileList) {
      this.uplaodVideoloading = true
    },
    handleUploadSuccess({ code, msg, data }, index) {
      if (code !== 200) {
        this.$modal.msgError(`${msg}`)
      } else {
        this.uplaodVideoloading = false
        data.name = data.fileName
        data.url = data.fileUrl
        this.fileList[index] = (this.fileList[index] || []).concat(data)
        this.localToyPlayList[index].gameplayUrl = data.fileUrl
        this.localToyPlayList[index].fileId = this.fileList[index].map(file => file.id).join(',')
        this.$forceUpdate()
      }
    },
    onSubmit() {
      return new Promise(resolve => {
        const validateTag = []
        this.localToyPlayList.forEach((item, index) => {
          this.$refs[`form${index}`][0].validate(valid => {
            validateTag.push(valid)
          })
        })
        const validate = validateTag.every(item => item)
        resolve({
          valid: validate,
          values: this.localToyPlayList
        })
      })
    },
    onInit() {
      this.fileList = {}
      this.activeTab = '0'
    },
    handleRemoveVideo(index, id) {
      this.fileList[index] = this.fileList[index].filter(item => item.id !== id)
      this.localToyPlayList[index].fileId = this.fileList[index].map(file => file.id).join(',')
      this.$forceUpdate()
    }
  }
}
</script>

<style scoped lang="scss">
.tabs-play {
  ::v-deep .el-tabs__new-tab {
    margin-right: 12px;
  }

  ::v-deep .el-tabs__nav-wrap.is-scrollable.is-top {
    width: 90%
  }
}

.upload-card {
  width: 80px;
  height: 80px;
  line-height: 80px;
}

.video-container {
  margin-top: 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.video-position {
  position: relative;

  .remove-icon {
    position: absolute;
    top: -10px;
    right: 0;
    font-size: 18px;
  }
}

.video-form-item {
  display: flex;
  align-items: center;

  //.upload-video {
  //  height: 80px;
  //  width: 80px;
  //}
  .el-loading-spinner .circular {
    height: 30px;
  }
}

.play-container {
  position: relative;

  .play-option-edit {
    position: absolute;
    z-index: 2;
    right: 6px;
    top: 6px;
  }
}
</style>
