<template>
  <div class="game-form-edite">
    <el-drawer
      :title="textOptTitle"
      :visible="true"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div v-loading="submitLoading">
        <div class="drawer-form">
          <el-form ref="form" :model="form" :rules="rules" label-width="50px">
            <div class="blockquote">基本信息</div>
            <el-form-item label="封面">
              <el-col :span="12">
                <el-form-item prop="cover" label-width="0">
                  <el-upload
                    ref="uploadCover"
                    :disabled="coverUploadLoading"
                    :file-list="coverFileList"
                    :class="{'upload-but-hide': !isShowCoverUpload}"
                    action=""
                    list-type="picture-card"
                    :http-request="uploadCover"
                    :show-file-list="!isShowCoverUpload"
                    :on-remove="handleCoverFileRemove"
                    accept="image/*"
                    :on-change="changeUploadCover"
                  >
                    <i slot="default" v-loading="coverUploadLoading" class="el-icon-plus" />
                    <div slot="tip" class="el-upload__tip">封面icon</div>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="backgroundCover" label-width="0">
                  <el-upload
                    ref="uploadBagCover"
                    :disabled="bagCoverUploadLoading"
                    :file-list="bagCoverFileList"
                    :class="{'upload-but-hide': !isShowBagCoverUpload}"
                    action=""
                    list-type="picture-card"
                    :http-request="uploadBagCover"
                    :show-file-list="!isShowBagCoverUpload"
                    :on-remove="handleBagCoverFileRemove"
                    accept="image/*"
                    :on-change="changeUploadBgCover"
                  >
                    <i slot="default" v-loading="bagCoverUploadLoading" class="el-icon-plus" />
                    <div slot="tip" class="el-upload__tip">背景图</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-form-item>

            <el-form-item label="系统" prop="sysOrigin">
              <el-select
                v-model="form.sysOrigin"
                placeholder="选择系统"
                style="width:100%;"
                class="filter-item"
              >
                <el-option
                  v-for="item in permissionsSysOriginPlatforms"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left;"> <sys-origin-icon :icon="item.value" :desc="item.value" /></span>
                  <span style="float: left;margin-left:10px">{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model.trim="form.name" type="text" placeholder="请输入名称" minlength="1" maxlength="150" show-word-limit />
            </el-form-item>
            <el-form-item label="编号" prop="gameCode">
              <el-input v-model.trim="form.gameCode" type="text" placeholder="请输入编号" minlength="1" maxlength="150" show-word-limit />
            </el-form-item>
            <el-form-item label="状态" prop="showcase">
              <el-select
                v-model="form.showcase"
                placeholder="状态"
                clearable
                style="width:100%;"
                class="filter-item"
              >
                <el-option label="下架" :value="false" />
                <el-option label="上架" :value="true" />
              </el-select>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model.trim="form.sort" v-number style="width: 100%;" :min="0" :max="99999" placeholder="降序排列(数字越大越靠前)" />
            </el-form-item>
            <div class="blockquote">模式配置</div>
            <el-form-item label-width="0px">
              <div v-for="(item, index) in form.models" :key="index" class="model-row">
                <el-form-item label="封面">
                  <el-upload
                    :ref="'modelBgCover_'+index"
                    :disabled="item.uploadLoading"
                    :file-list="item.uploadFileList"
                    :class="{'upload-but-hide': !!item.backgroundCover}"
                    action=""
                    list-type="picture-card"
                    :http-request="(file) => uploadModelBgCover({file, row:item, index})"
                    :show-file-list="!!item.backgroundCover"
                    :on-remove="(file, fileList) => handleModelCoverFileRemove({ file, fileList, row:item, index })"
                    :on-change="(file, fileList)=>changeModelUploadCover({ file, fileList, row:item,index })"
                    accept="image/*"
                  >
                    <i slot="default" v-loading="item.uploadLoading" class="el-icon-plus" />
                  </el-upload>
                </el-form-item>
                <el-form-item
                  class="model-item"
                  label="玩家"
                  :prop="'models.' + index + '.players'"
                  :rules="commonRules"
                >
                  <el-select v-model="item.players" placeholder="请选择" style="width: 100%;">
                    <el-option
                      v-for="(pItem, pIndex) in players"
                      :key="pIndex"
                      :label="pItem"
                      :value="pItem"
                      :disabled="form.models.some(m => m.players === pItem)"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  class="model-item"
                  label="金额"
                  :prop="'models.' + index + '.amounts'"
                  :rules="commonRules"
                >
                  <el-input-number v-model.trim="item.amounts" v-number style="width: 100%;" :min="0" :max="99999" placeholder="降序排列(数字越大越靠前)" />
                </el-form-item>
                <div class="model-del font-danger" @click="clickRemoveModel(item, index)">
                  移除 <i class="el-icon-delete-solid" />
                </div>
              </div>
            </el-form-item>
            <div v-if="form.models.length < 3" class="add-model" @click="clickAddModel">
              <i class="el-icon-plus" />
            </div>
          </el-form>
        </div>
        <div class="drawer-footer" style="text-align: right;">
          <el-button @click="handleClose()">取消</el-button>
          <el-button type="primary" @click="submitForm()">保存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>

import { upsertGameMatchConfig } from '@/api/sys'
import { getElementUiUploadFile, deepClone } from '@/utils'
import { mapGetters } from 'vuex'
export default {
  props: {
    row: {
      type: Object,
      default: null
    }
  },
  data() {
    const commonRules = [{ required: true, message: '必填字段', trigger: 'blur' }]
    return {
      commonRules,
      players: [2, 4, 6, 9],
      coverUploadLoading: false,
      coverFileList: [],

      bagCoverUploadLoading: false,
      bagCoverFileList: [],
      //
      form: {
        id: '',
        cover: '',
        backgroundCover: '',
        sysOrigin: '',
        name: '',
        gameCode: '',
        showcase: false,
        sort: 0,
        models: []
      },
      submitLoading: false,
      uploadLoading: false,
      rules: {
        cover: commonRules,
        backgroundCover: commonRules,
        sysOrigin: commonRules,
        name: commonRules,
        gameCode: commonRules,
        showcase: commonRules,
        sort: commonRules,
        amounts: commonRules
      }
    }
  },
  computed: {
    textOptTitle() {
      return this.row && this.row.id ? '修改' : '新增'
    },
    isShowCoverUpload() {
      return !this.form.cover
    },
    isShowBagCoverUpload() {
      return !this.form.backgroundCover
    },
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  watch: {
    row: {
      handler(val) {
        if (!val) {
          return
        }
        const form = deepClone(val)
        this.coverFileList = getElementUiUploadFile(form.cover)
        this.bagCoverFileList = getElementUiUploadFile(form.backgroundCover)
        form.models.forEach(item => {
          item.uploadLoading = false
          item.uploadFileList = getElementUiUploadFile(item.backgroundCover)
        })
        this.form = form
      },
      immediate: true
    }
  },
  methods: {
    clickAddModel() {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          that.$opsMessage.warn('请先完善现有表单参数!')
          return
        }

        if (that.form.models.length === 3) {
          that.$opsMessage.warn('一个游戏最多运行添加 3 种模式!')
          return
        }
        that.form.models.push(that.createModel())
      })
    },
    clickRemoveModel(row, index) {
      this.form.models.splice(index, 1)
    },
    createModel() {
      return {
        players: '',
        amounts: '',
        backgroundCover: '',

        // 文件上传
        uploadLoading: false,
        uploadFileList: []
      }
    },
    uploadCover(file) {
      const that = this
      that.coverUploadLoading = true
      that.$simpleUploadFlie(file, that.$application.fileBucket.other).then(res => {
        that.coverUploadLoading = false
        that.form.cover = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        that.coverUploadLoading = false
      })
    },
    handleCoverFileRemove(file, fileList) {
      this.form.cover = ''
      this.coverUploadLoading = false
    },
    changeUploadCover(file, fileList) {
      if (fileList.length > 1) {
        this.$refs.uploadCover.clearFiles()
        this.coverFileList = getElementUiUploadFile(fileList[fileList.length - 1].url)
      }
    },
    handleClose() {
      this.$emit('close')
    },
    uploadBagCover(file) {
      const that = this
      that.bagCoverUploadLoading = true
      that.$simpleUploadFlie(file, that.$application.fileBucket.other).then(res => {
        that.bagCoverUploadLoading = false
        that.form.backgroundCover = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        that.bagCoverUploadLoading = false
      })
    },
    handleBagCoverFileRemove(file, fileList) {
      this.form.backgroundCover = ''
      this.coverUploadLoading = false
    },
    changeUploadBgCover(file, fileList) {
      if (fileList.length > 1) {
        this.$refs.uploadBagCover.clearFiles()
        this.bagCoverFileList = getElementUiUploadFile(fileList[fileList.length - 1].url)
      }
    },
    uploadModelBgCover({ file, row }) {
      const that = this
      row.uploadLoading = true
      that.$simpleUploadFlie(file, that.$application.fileBucket.other).then(res => {
        row.uploadLoading = false
        row.backgroundCover = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        row.uploadLoading = false
      })
    },
    handleModelCoverFileRemove({ file, fileList, row }) {
      row.backgroundCover = ''
      row.uploadLoading = false
    },
    changeModelUploadCover({ file, fileList, row, index }) {
      if (fileList.length > 1) {
        this.$refs['modelBgCover_' + index].clearFiles()
        row.uploadFileList = getElementUiUploadFile(fileList[fileList.length - 1].url)
      }
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        if (that.form.models.length <= 0) {
          that.$opsMessage.warn('最少,必须配置一种游戏模式!')
          return
        }
        const submitForm = Object.assign({}, that.form)
        that.submitLoading = true
        upsertGameMatchConfig(submitForm).then(res => {
          that.submitLoading = false
          that.$emit('success', res)
        }).catch(er => {
          that.submitLoading = false
          that.$emit('fial', er)
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.add-model {
  border: 1px dashed #b9b6b6;
  border-radius: 5px;
  padding: 10px;
  text-align: center;
  cursor: pointer;
  i {
    font-size: 30px;
    font-weight: bold;
    color: #999999;
  }
}
.model-row {
  position: relative;
  border: 1px dashed #b9b6b6;
  padding: 20px 10px;
  margin-bottom: 20px;
  .model-item {
    margin: 20px 0px;
  }
  .model-del {
    font-size: 22px;
    border: 1px dashed #b9b6b6;
    text-align: center;
    cursor: pointer;
    padding: 5px;
  }
}
</style>
