<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" @close="close">
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="音乐名称" prop="name">
        <el-input v-model="form.name" autocomplete="off" placeholder="请输入音乐名称" />
      </el-form-item>
      <el-form-item label="场景" prop="scene">
        <el-select v-model="form.scene" clearable placeholder="请选择场景(可为空)" style="width: 100%">
          <el-option v-for="item in sceneList" :key="item.scene" :label="item.sceneName" :value="item.scene" />
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tag">
        <el-input v-model="form.tag" autocomplete="off" placeholder="请输入标签(可选)" />
      </el-form-item>
      <el-form-item label="音乐文件" prop="musicUrl">
        <el-upload
          accept="audio/*"
          :action="uploadUrl"
          :before-upload="beforeUpload"
          :headers="uploadHeaders"
          :on-error="handleUploadError"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传音频文件，且不超过 10MB</div>
        </el-upload>
        <div v-if="form.musicUrl" style="margin-top: 10px">
          <audio controls :src="form.musicUrl" style="width: 100%"></audio>
        </div>
      </el-form-item>
      <el-form-item v-if="!form.id" label="是否启用" prop="isEnabled">
        <el-switch v-model="form.isEnabled" active-text="启用" :active-value="true" inactive-text="禁用" :inactive-value="false" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doEdit, doAdd } from '@/api/spring/blessing/music/index'
  import { getAll as getAllScenes } from '@/api/spring/blessing/scene'
  import { getAccessToken } from '@/utils/accessToken'

  export default {
    name: 'MusicManagementEdit',
    data() {
      return {
        id: '',
        form: {
          name: '',
          scene: '',
          musicUrl: '',
          tag: '',
          isEnabled: true,
        },
        rules: {
          name: [{ required: true, trigger: 'blur', message: '请输入音乐名称' }],
          musicUrl: [{ required: true, trigger: 'change', message: '请上传音乐文件' }],
        },
        title: '',
        dialogFormVisible: false,
        sceneList: [],
        token: getAccessToken() || '',
        loading: false,
      }
    },
    computed: {
      uploadUrl() {
        return `${process.env.VUE_APP_API_BASE_URL}/management/api/common/upload`
      },
      uploadHeaders() {
        let userId = ''
        let appId = ''
        if (this.$store.state?.user?.userId) {
          userId = this.$store.state?.user?.userId
        }
        if (this.$store.state?.user?.appId) {
          appId = this.$store.state?.user?.appId
        }
        return {
          Authorization: `${this.token}`,
          'x-user-id': userId,
          'x-app-id': appId,
        }
      },
    },
    created() {
      this.fetchSceneList()
    },
    methods: {
      async fetchSceneList() {
        try {
          const { data } = await getAllScenes()
          this.sceneList = data || []
        } catch (error) {
          console.error(error)
        }
      },
      beforeUpload(file) {
        const isValidSize = file.size / 1024 / 1024 < 10
        if (!isValidSize) {
          this.$message.error('文件大小不能超过 10MB！')
          return false
        }
        this.loading = true
        return true
      },
      handleUploadSuccess(response) {
        this.loading = false
        if (response.code === 200) {
          this.form.musicUrl = `https://file.lihailezzc.com/${response.data.key}`
          this.$message.success('上传成功！')
        } else {
          this.$message.error('上传失败，请重试！')
        }
      },
      handleUploadError() {
        this.loading = false
        this.$message.error('上传失败，请重试！')
      },
      showEdit(row) {
        if (!row) {
          this.title = '添加'
          this.id = ''
          this.form = {
            name: '',
            scene: '',
            musicUrl: '',
            tag: '',
            isEnabled: true,
          }
        } else {
          this.title = '编辑'
          this.id = row.id
          this.form = {
            id: row.id,
            name: row.name,
            scene: row.scene,
            musicUrl: row.musicUrl,
            tag: row.tag,
            isEnabled: row.isEnabled,
          }
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.id = ''
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            try {
              if (this.id) {
                const { msg } = await doEdit(this.id, this.form)
                this.$baseMessage(msg, 'success')
              } else {
                const { msg } = await doAdd(this.form)
                this.$baseMessage(msg, 'success')
              }
              this.$emit('fetch-data')
              this.close()
            } catch (error) {
              console.error(error)
            } finally {
              this.loading = false
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
