<template>
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" :loading="handlerLoading" @click="saveLevelHandler" :priv="this.levelID==='new'?'Member.Level.Add':'Member.Level.Edit'">
        <span>
          <i class="fa fa-save"></i>保存</span>
      </el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel">
        <div class="panel-header">
          <div class="title">
            {{levelID!='new' ? '编辑会员等级':'添加会员等级'}}
          </div>
        </div>
        <el-form :model="tmpLevel" :rules="levelrules" ref="saveLevelForm" label-width="180px" label-suffix="：" v-loading="formDataLoading">
          <el-form-item label="图标" prop="iconPath">
            <img :src="tmpLevel.iconPath" @error="setErrorImg" style="max-height:64px;max-width: 300px" />
            <el-button class="through-btn" @click="uploadIcon">上传会员等级图标</el-button>
          </el-form-item>
          <el-form-item label="类型" prop="levelType">
            <el-select v-model="tmpLevel.levelType" style="width:auto;" :disabled="levelID!='new'">
              <el-option v-for="item in levelTypeNames" :key="item.value" :label="item.text" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="tmpLevel.name" style="width:80%;"></el-input>
          </el-form-item>
          <el-form-item label="晋级规则">
            <el-select v-model="tmpLevel.scoreType" style="width:auto;">
              <el-option v-for="item in scoreTypes" :key="item.value" :label="item.text" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-input-number v-model="tmpLevel.minScore" :min="0" :max="100000"></el-input-number>&nbsp;~&nbsp;
            <el-input-number v-model="tmpLevel.maxScore" :min="tmpLevel.minScore" :max="100000"></el-input-number>
          </el-form-item>
          <el-form-item label="备注" prop="memo" >
            <el-input v-model="tmpLevel.memo" style="width:80%;"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!--上传图标框-->
    <el-dialog title="上传会员等级图标" :visible.sync="uploadIconModal" class="upload-icon-dialog">
      <el-form label-width="100px">
        <el-form-item label="图标：" prop="icon">
          <el-upload class="avatar-uploader" action="" :file-list="fileList" :on-change="uploadFileChangeHandler" :multiple="false"
            ref="upload" :auto-upload="false" accept=".jpeg,.bmp,.gif,.jpg,.png">
            <el-button slot="trigger" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传*.jpg,*.jpeg,*.bmp,*.png,*.gif文件，且不超过10K</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="uploadIconModal = false">取 消</el-button>
        <el-button type="primary" @click="confrimUpload" v-loading="uploadLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import util from '@src/common/util.js'
export default {
  props: {
    levelID: {
      type: String,
      required: true
    }
  },
  data() {
    let nameLengthEXCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入名称'))
      } else {
        let lengthEx = util.getLengthEx(value, true)
        if (lengthEx > 50) {
          callback(new Error('名称必须小于等于16个汉字或者50个字母'))
        } else {
          callback()
        }
      }
    }
    let memoLengthEXCheck = (rule, value, callback) => {
      let lengthEx = util.getLengthEx(value, true)
      if (lengthEx > 400) {
        callback(new Error('备注必须小于等于133个汉字或者400个字母'))
      } else {
        callback()
      }
    }
    return {
      uploadLoading: false,
      formDataLoading: false,
      uploadIconModal: false,
      handlerLoading: false,
      fileList: [],
      levelrules: {
        name: [
          { validator: nameLengthEXCheck, trigger: 'blur change' }
        ],
        memo: [
          { validator: memoLengthEXCheck, trigger: 'blur change' }
        ]
      },
      tmpLevel: {},
      levelTypeNames: [],
      scoreTypes: []
    }
  },
  mounted() {
    this.getLevelTypes()
    this.getScoreTypes()
    this.beforeTurnToPage()
  },
  methods: {
    goBack() {
      this.$router.push('/member/level')
    },
    async beforeTurnToPage() {
      this.tmpLevel = {
        icon: '',
        iconPath: '',
        name: '',
        levelType: '',
        scoreType: '',
        memo: '',
        minScore: 0,
        maxScore: 0
      }
      if (this.levelID !== 'new') {
        await this.getOneLevel()
      }
    },
    async getOneLevel() {
      this.formDataLoading = true
      let res = await axios.get(`/ui/memberlevel/${this.levelID}`)
      this.tmpLevel = res.data.data
      this.tmpLevel.addTime = util.formatDate(this.tmpLevel.addTime, 'yyyy-MM-dd HH:mm:ss')
      this.formDataLoading = false
    },
    async getLevelTypes() {
      let data = await axios.get('/ui/memberlevel/leveltypes', {})
      this.levelTypeNames = data.data.data
      if (this.levelTypeNames.length > 0 && !this.tmpLevel.levelType) {
        this.tmpLevel.levelType = this.levelTypeNames[0].value || ''
      }
    },
    async getScoreTypes() {
      let data = await axios.get('/ui/memberlevel/scoretypes', {})
      this.scoreTypes = data.data.data
      if (this.scoreTypes.length > 0 && !this.tmpLevel.scoreType) {
        this.tmpLevel.scoreType = this.scoreTypes[0].value || ''
      }
    },
    setErrorImg(e) {
      e.target.src = './assets/images/icon401a10.png'
    },
    uploadIcon() {
      this.fileList = []
      this.uploadIconModal = true
    },
    uploadFileChangeHandler(file, files) {
      if (file.size / 1024 > 10) {
        this.fileList = this.fileList.length > 0 ? [this.fileList[0]] : []
        this.$message('单个文件大小限制为10.00K')
        return
      }
      this.fileList = [files[0]]
      if (files.length > 1) {
        this.$message('上传文件限制为1')
      }
    },
    async confrimUpload() {
      if (this.fileList.length === 0) {
        util.showError('请选择要上传的文件')
        return
      }
      const formData = new FormData()
      formData.append('file', this.fileList[0].raw)
      this.uploadLoading = true
      try {
        let res = await axios.post('/ui/memberlevel/uploadicons', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        this.uploadLoading = false
        if (res.data.status === 1) {
          this.tmpLevel.icon = res.data.storePath
          this.tmpLevel.iconPath = res.data.previewPath
          this.uploadIconModal = false
        }
      } catch (e) {
        this.uploadLoading = false
      }
    },
    // 保存等级
    async saveLevelHandler() {
      if (this.tmpLevel.maxScore < this.tmpLevel.minScore) {
        util.showErrorMessageBox('请填写合理的积分值')
        return
      }
      this.handlerLoading = true
      try {
        await util.validateForm(this.$refs['saveLevelForm'])
        let res
        if (this.levelID !== 'new') {
          res = await axios.put(`/ui/memberlevel/${this.levelID}`, this.tmpLevel)
        } else {
          res = await axios.post('/ui/memberlevel', this.tmpLevel)
        }
        if (res.data.status === 1 && this.levelID === 'new' && res.data.levelID) {
          this.$router.replace({path: `/member/level/${res.data.levelID}`})
        }
        util.showResponseMessage(res.data)
        this.handlerLoading = false
      } catch (e) {
        util.showErrorMessageBox(e)
        this.handlerLoading = false
      }
    }
  }
}
</script>
<style>
  .upload-icon-dialog .el-dialog {
    width: 500px;
  }

  @media (max-width: 480px) {
    .upload-icon-dialog .el-dialog {
      width: 96%;
    }
  }
</style>
<style scoped>
  .through-btn {
    margin-left: -3px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
