<template>
  <div>
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item
        prop="sysMusicScore.name"
        label="曲名"
        :rules="[{required: true, message: '请输入曲名'}]"
      >
        <el-input placeholder="请输入曲名" v-model="form.sysMusicScore.name"/>
      </el-form-item>
      <el-form-item
        prop="sysMusicScore.musicScoreCategoriesId"
        label="分类"
        :rules="[{required: true, message: '请选择分类'}]"
      >
      <el-cascader v-model="form.sysMusicScore.musicScoreCategoriesId"
                    style="width:100%"
                    :options="tree"
                     placeholder="请选择分类"
                    :props="treeProps"></el-cascader>
        <!-- <el-select style="width: 100%!important;" v-model="form.sysMusicScore.musicScoreCategoriesId" placeholder="请选择声部">
          <el-option
            v-for="item in selects.subjects"
            :value="item.id"
            :label="item.name"
            :key="item.id"
          ></el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item
        label="原音"
        prop="sysMusicScore.url"
      >
        <singe-file-upload
          tips="仅支持上传 mp3/aac 格式音频文件"
          accept=".mp3, .aac"
          v-model="form.sysMusicScore.url"
        />
      </el-form-item>
      <div class="files" v-for="(song, index) in form.sysMusicScoreAccompaniments" :key="index">
        <el-row>
          <el-col :span="12">
            <el-form-item
              :prop="`sysMusicScoreAccompaniments.${index}.subjectId`"
              label="声部"
              :rules="[{required: true, message: '请选择声部'}]"
            >
              <el-select style="width: 100%!important;" v-model="song.subjectId" placeholder="请选择声部">
                <el-option
                  v-for="item in selects.subjects"
                  :value="item.id"
                  :label="item.name"
                  :key="item.id"
                  :disabled="hasSubjectId(item.id)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :prop="`sysMusicScoreAccompaniments.${index}.speed`"
              label="速度"
              :rules="[{required: true, message: '请输入速度'}]"
            >
              <el-input type="number" placeholder="请输入速度" v-model="song.speed"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="mp3文件"
              :prop="`sysMusicScoreAccompaniments.${index}.mp3Url`"
            >
              <singe-file-upload
                tips="仅支持上传 mp3/aac 格式音频文件"
                accept=".mp3, .aac"
                v-model="song.mp3Url"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="MusicXML"
              :prop="`sysMusicScoreAccompaniments.${index}.xmlUrl`"
              :rules="[{required: true, message: '请选择MusicXML文件'}]"
            >
              <singe-file-upload
                tips="仅支持上传 xml 格式文件"
                accept=".xml"
                v-model="song.xmlUrl"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-button class="file-remove" type="text" @click="removeSys(index)" :disabled="form.sysMusicScoreAccompaniments.length == 1">删除</el-button>
      </div>
      <el-button @click="createSys" type="info" style="width: 100%;margin-bottom: 20px;" plain>添加伴奏</el-button>
      <div class="btns">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="$listeners.close">取消</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import { Add, Update, queryPageSysExam, queryTree } from '../api'
export default {
  props: ['detail', 'type'],
  data() {
    return {
      tree: [],
      form: {
        sysMusicScore: {
          name: '',
          url: '',
          musicScoreCategoriesId: [],
        },
        sysMusicScoreAccompaniments: [
          {
            subjectId: '',
            speed: '',
            mp3Url: '',
            xmlUrl: ''
          },
        ],
        delExamSongAccompanimentIds: []
      },
      treeProps: {
        value: 'id',
        label: 'name',
        children: 'sysMusicScoreCategoriesList',
      }
    }
  },
  async mounted() {
    this.$store.dispatch('setSubjects')
    await this.FetchTree()
    if (this.detail) {
      this.$set(this.form, 'sysMusicScore', {
        name: this.detail.name,
        url: this.detail.url,
        musicScoreCategoriesId: this.detail.categoriesId ? this.formatParentId(this.detail.categoriesId, this.tree) : [],
      })
      this.FeatchDetailList()
    }
  },
  methods: {
    formatParentId(id, list, ids = []) {
      for (const item of list) {
        if (item.sysMusicScoreCategoriesList) {
          return this.formatParentId(id, item.sysMusicScoreCategoriesList, [...ids, item.id])
        }
        if (item.id === id) {
          return [...ids, id]
        }
      }
      return ids
    },
    async FetchTree() {
      try {
        const res = await queryTree()
        this.tree = res.data
      } catch (error) {
        console.log(error)
      }
    },
    async FeatchDetailList() {
      try {
        const res = await queryPageSysExam({
          sysMusicScoreId: this.detail.id
        })
        this.$set(this.form, 'sysMusicScoreAccompaniments', res.data)
      } catch (error) {}
    },
    createSys() {
      this.form.sysMusicScoreAccompaniments.push({
        subjectId: '',
        speed: '',
        mp3Url: '',
        xmlUrl: ''
      })
    },
    async removeSys(index) {
      try {
        await this.$confirm('是否确认删除此伴奏?', '提示', {
          type: 'warning'
        })
        if (this.form.sysMusicScoreAccompaniments[index]) {
          this.form.delExamSongAccompanimentIds.push(this.form.sysMusicScoreAccompaniments[index].id)
        }

        this.form.sysMusicScoreAccompaniments.splice(index, 1)
      } catch (error) {}
    },
    hasSubjectId(id) {
      const ids = []
      for (const item of this.form.sysMusicScoreAccompaniments) {
        ids.push(item.subjectId)
      }
      return ids.includes(id)
    },
    async submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (!this.detail) {
            await Add({
              ...this.form,
              sysMusicScore: {
                ...this.form.sysMusicScore,
                type: 'COMMON',
                musicScoreCategoriesId: (this.form.sysMusicScore.musicScoreCategoriesId || []).pop(),
              }
            })
            this.$message.success('提交成功')
          } else {
            await Update({
              ...this.form,
              sysMusicScore: {
                ...this.form.sysMusicScore,
                type: 'COMMON',
                id: this.detail.id,
                musicScoreCategoriesId: (this.form.sysMusicScore.musicScoreCategoriesId || []).pop(),
              }
            })
            this.$message.success('修改成功')
          }
          this.$listeners.close()
          this.$listeners.submited()
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .btns{
    text-align: right;
  }
  .files{
    background-color: #f8f8f8;
    padding: 20px 0;
    padding-right: 20px;
    margin-bottom: 20px;
    border-radius: 5px;
    position: relative;
    .file-remove{
      position: absolute;
      right: 20px;
      bottom: 10px;
    }
  }
</style>
