<template>
  <div class="layout-no-flex">
    <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 @click="confirm" :loading="confirmLoading" :priv="faceID ? 'CommentFaceManage.Edit':'CommentFaceManage.Add'">
        <i class="fa fa-save"></i>保存</el-button>
    </el-toolbar>
    <div class="detail-panel">
      <div class="panel-header">
        <div class="title">
          {{panelTitle}}
        </div>
      </div>
      <el-form :model="tmpFace" :rules="faceRules" ref="addFaceForm" label-width="200px" v-loading="dataLoading">
        <el-form-item label="表情名称：" prop="faceName">
          <el-input type="text" v-model="tmpFace.faceName" auto-complete="off" style="max-width:300px;"></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-switch v-model="tmpFace.status" active-value="Y" inactive-value="N"></el-switch>
        </el-form-item>
        <el-form-item label="表情图片：">
          <el-row>
            <el-col :span="1" v-if="tmpFace.facePath">
              <img  :src="pathPrefix+tmpFace.facePath" onerror="this.src='assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png';" width="24" height="24"/>
            </el-col>
             <el-col :span="23">
              <el-upload class="upload-face" :limit="1" action="" :multiple="false" :on-change="selectFileChangeHandler" :http-request="fileUploadSuccessHandler" :before-upload="beforeFileUpload" :file-list="fileList" accept=".jpg,.gif">
              <el-input disabled v-model="acceptType" :style="tmpFace.facePath?'width:190px;':'width:220px;'"></el-input>
              <el-button type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传 .jpg .gif 文件</div>
            </el-upload>
            </el-col>
          </el-row>

        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import util from '@src/common/util.js'
export default {
  props: {
    ID: [String, Number]
  },
  data() {
    return {
      pathPrefix: this.$root.prefix,
      faceID: '',
      panelTitle: '',
      confirmLoading: false,
      dataLoading: true,
      faceRules: {
        faceName: [
          { required: true, message: '请输入表情名称', trigger: 'blur' },
          { max: 16, message: '名称不能超过16个字符', trigger: 'blur' }
        ]
      }, // 保存格式规则
      tmpFace: {
        faceName: '',
        status: 'Y',
        facePath: ''
      }, // data模板
      fileList: [],
      acceptType: '.jpg,.gif'

    }
  },
  async mounted() {
    this.faceID = this.$route.params.ID === 'new' ? null : this.$route.params.ID
    this.panelTitle = this.$route.params.ID === 'new' ? '添加表情' : '编辑表情'
    if (this.faceID) {
      try {
        let res = await axios.get(`/ui/faces/${this.faceID}`)
        this.tmpFace = res.data.data
      } catch (e) {}
      this.dataLoading = false
    } else {
      this.dataLoading = false
    }
  },
  methods: {
    goBack() {
      this.$router.back()
    },
    selectFileChangeHandler(file, files) {
      if (!this.beforeFileUpload(file)) {
        return
      }
      this.fileList = files.slice(-1)
    },
    async fileUploadSuccessHandler(event) {
      if (!this.fileList.length) {
        this.$message.error('请选择文件')
        return
      }
      if (!this.beforeFileUpload(this.fileList[0])) {
        return
      }
      const { file, onProgress } = event
      const formData = new FormData()
      formData.append('file', file)
      try {
        let res = await axios.post(
          '/ui/faces/upload',
          formData,
          event => {
            onProgress(event, file)
          },
          { headers: { 'Content-Type': 'multipart/form-data' } }
        )
        if (res.data.status === 1) {
          this.tmpFace.facePath = res.data.facePath
        }
      } catch (e) {
        util.showErrorMessageBox(e)
      }
    },
    beforeFileUpload(file) {
      let isJpeg = ''
      let isGif = ''
      if (file.raw) {
        isJpeg = file.raw.type === 'image/jpeg'
        isGif = file.raw.type === 'image/gif'
      } else {
        isJpeg = file.type === 'image/jpeg'
        isGif = file.type === 'image/gif'
      }
      if (!(isJpeg || isGif)) {
        this.$message.error('上传文件只能是jpg或gif格式')
      }
      return isJpeg || isGif
    },
    // 判断进行操作是添加还是编辑，并执行对应的方法
    async confirm() {
      this.confirmLoading = true
      try {
        await util.validateForm(this.$refs['addFaceForm'])
      } catch (e) {
        this.confirmLoading = false
        util.showErrorMessageBox(e)
        return
      }
      if (!this.tmpFace.facePath) {
        this.$alert('请选择要上传的表情图片！', '提示', {
          type: 'info'
        })
        this.confirmLoading = false
        return
      }
      if (!this.faceID) {
        let res = await axios.post('/ui/faces', this.tmpFace)
        util.showResponseMessage(res.data)
        this.confirmLoading = false
        if (res.data.status === 1) {
          this.faceID = res.data.ID
          this.panelTitle = '编辑表情'
          this.$router.replace(`/plugins/face/${this.faceID}`)
        }
      } else {
        let res = await axios.put(`/ui/faces/${this.faceID}`, this.tmpFace)
        util.showResponseMessage(res.data)
        this.confirmLoading = false
      }
    }
  }
}
</script>

<style scoped>
.upload-face .el-upload__input {
  display: none !important;
  margin-bottom: -20px;
}
</style>
