<template>
  <div class="tab6Add">
    <div class="insideTop">
      校歌管理 > {{ruleForm.id?'编辑':'新增'}}音频
      <div class="add">
        <el-button type="primary" @click="goBack">返 回</el-button>
      </div>
    </div>
    <div class="obstruct"></div>
    <!-- 主要内容 -->
    <div class="conten">
      <div class="con_top">基本信息</div>
      <!-- 表单 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题：" prop="name">
          <el-input
            v-model="ruleForm.name"
            maxlength="25"
            show-word-limit
            style="width: 500px"
          ></el-input>
        </el-form-item>
        <!-- 图片和附件 -->
        <el-form-item label="图片：">
          <i class="biaoshi biaoshi1"></i>
          <el-upload
            class="avatar-uploader"
            :action="baseURL + '/cms/music/upload'"
            :headers="{
              token,
            }"
            :show-file-list="true"
            :before-upload="beforethumbUpload"
            :on-success="upload_thumb_success"
          >
            <div v-if="ruleForm.thumb" class="imgdiv">
              <img
                style="width: 100%; height: 100%"
                :src="baseURL + ruleForm.thumb"
              />
              <i
                class="el-icon-circle-close"
                @click.stop="ruleForm.thumb = ''"
              ></i>
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="upHint">格式要求：支持png、jpg、gif和jpeg的图片格式；最大支持20M。</p>
        </el-form-item>        <!-- 上传附件 -->
        <el-form-item label="音频文件：">
          <i class="biaoshi"></i>
          <el-upload
            multiple
            class="upload-demo"
            :file-list="fileList"
            :action="baseURL + '/cms/music/video/upload'"
            :headers="{ token }"
            :before-upload="beforeFujian"
            :on-success="successFujian"
            :before-remove="beforeRemove"
            :on-remove="handleRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :show-file-list="true"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div class="el-upload__tip" slot="tip">
              <p class="upHint">格式要求：</p>
              <p class="upHint">1、支持音频格式文件（例如：mp3、wav）。</p>
              <p class="upHint">2、最大支持5M的音频文件。</p>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="歌词：">
          <i class="biaoshi biaoshi1"></i>
          <div id="div1" style="z-index: 1"></div>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <div class="con_btn">
        <el-button type="primary" @click="saveGood">保 存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { musicSave, musicDetail } from '@/apis/tab6'
import axios from '@/utils/request'
import E from 'wangeditor'
export default {
  name: 'tab6Add',
  components: {},
  data () {
    return {
      fileList: [],
      // 服务器前缀地址
      baseURL: '',
      token: '',
      ruleForm: {
        name: '',
        filePath: '',
        fileName: '',
        thumb: ''
      },
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  methods: {
    // 点击保存
    async saveGood () {
      if (this.ruleForm.name.trim() === '') { return this.$message.warning('标题不能为空') }
      if (this.ruleForm.thumb === '') { return this.$message.warning('图片不能为空') }
      if (this.ruleForm.filePath === '') { return this.$message.warning('音频不能为空') }
      if (this.editor.txt.html() === '') { return this.$message.warning('歌词不能为空') }
      const obj = { ...this.ruleForm, description: this.editor.txt.html() }
      const res = await musicSave(obj)
      if (res.code === 0) {
        this.$message.success('操作成功')
        this.$router.push('/layout/tab6')
      } else this.$message.warning(res.msg)
    },
    // 点击返回
    goBack () {
      this.$confirm('点击返回后，编辑的信息将无法保存，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$router.push('/layout/tab6')
        })
        .catch(() => {
          this.$message.info('已取消')
        })
    },
    // 上传图片
    beforethumbUpload (file) {
      // console.log(998, file)
      // 限制图片大小和格式
      const sizeOk = file.size / 1024 / 1024 < 20
      const typeOk =
        file.type === 'image/png' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/gif'

      return new Promise((resolve, reject) => {
        if (!typeOk) {
          this.$message.error('照片格式有误！')
          reject(file)
        } else if (!sizeOk) {
          this.$message.error('照片大小超过20M！')
          reject(file)
        } else if (file.name.length > 32) {
          this.$message.error('照片名字不能超过32个字！')
          reject(file)
        } else {
          this.$message.success('上传成功')
          resolve(file)
        }
      })
    },
    upload_thumb_success (data) {
      // console.log('图片上传成功', data.data.urlPath)
      this.ruleForm.thumb = data.data.urlPath
    },
    // 上传附件
    beforeFujian (file) {
      console.log('附件上传前', file)
      const sizeOk = file.size / 1024 / 1024 < 10
      const typeOk =
        file.type === 'audio/mpeg' ||
        file.type === 'audio/wav'
      return new Promise((resolve, reject) => {
        if (file.name.length > 32) {
          this.$message.error('音频名字不能超过32个字')
          reject(file)
        } else if (!sizeOk) {
          this.$message.error('音频大小超过10M！')
          reject(file)
        } else if (!typeOk) {
          this.$message.error('音频格式有误！')
          reject(file)
        } else {
          resolve(file)
        }
      })
    },
    successFujian (file) {
      console.log('上传附件成功', file)
      if (file.code === 0) {
        this.ruleForm.filePath = file.data.urlPath
        this.ruleForm.fileName = file.data.fileName
        this.$message.success('上传成功')
      } else if (file.code === -1) {
        this.$message.warning('上传失败，不支持的文件格式')
      }
    },
    beforeRemove (file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`)
      }
    },
    handleRemove (file, fileList) {
      this.ruleForm.filePath = ''
      this.ruleForm.fileName = ''
    },
    handleExceed (files, fileList) {
      this.$message.warning('只能上传一个音频，请删除原音频后操作')
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // 获取服务器前缀地址
    this.baseURL = axios.defaults.baseURL
    // 获取用户token
    this.token = localStorage.getItem('CQLJXU_token')
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  async mounted () {
    // 初始化富文本
    // 富文本
    this.editor = new E('#div1')
    // 配置字体
    this.editor.config.fontNames = [
      '黑体',
      '仿宋',
      '楷体',
      '标楷体',
      '华文仿宋',
      '华文楷体',
      '宋体',
      '微软雅黑',
      'Arial',
      'Tahoma',
      'Verdana',
      'Times New Roman'
    ]
    this.editor.config.uploadImgShowBase64 = true // 图片地址
    this.editor.config.showLinkVideo = false
    this.editor.create()
    // 如果是编辑
    if (this.$route.query.id) {
      const res = await musicDetail(Number(this.$route.query.id))
      this.ruleForm = res.data
      console.log(998, res)
      // 富文本回显
      this.editor.txt.html(res.data.description)
      // 附件回显
      this.fileList = [{ name: res.data.fileName }]
    }
  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='less' scoped>
.tab6Add {
  height: 100%;
  .conten {
    overflow-y: auto;
    position: relative;
    /deep/.el-icon-plus {
      border: 1px dashed #ccc;
    }
    height: calc(100% - 32px);
    .con_top {
      margin-bottom: 12px;
      height: 40px;
      line-height: 40px;
      padding-left: 20px;
      background-color: #fbfbfb;
    }
    .biaoshi1::before {
      left: -64px;
    }
    .avatar-uploader .el-upload {
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #3e5eb3;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .con_btn {
      width: 80px;
      margin: 0 auto;
      margin-bottom: 20px;
    }
    #div1{
      width: 1200px;
    }
    .imgdiv {
      max-width: 200px;
      max-height: 200px;
      & > img {
        border: 10px solid #ccc;
      }
    }
    .el-icon-circle-close {
      font-size: 24px;
    }
  }
}
</style>
