<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
        prop="rankIdType"
        label="是否收费"
        :rules="[{required: true, message: '请选择是否收费'}]"
      >
        <el-select style="width: 100%!important;" v-model="form.rankIdType" placeholder="请选择是否收费" @change="rankChange">
          <!-- <el-option
            :value="item.id"
            :label="item.name"
            v-for="item in memberRankList"
            :key="item.id"
          ></el-option> -->
          <el-option
            :value="0"
            label="免费"
          ></el-option>
          <el-option
            :value="1"
            label="收费"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="sysMusicScore.clientType"
        label="客户端类型"
        :rules="[{required: true, message: '请选择客户端类型'}]"
      >
        <el-select style="width: 100%!important;" v-model="form.sysMusicScore.clientType" placeholder="请选择客户端类型">
          <el-option
            value="NETWORK_ROOM"
            label="网络教室"
          ></el-option>
          <el-option
            value="SMART_PRACTICE"
            label="智能陪练"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="sysMusicScore.order"
        label="排序"
        :rules="[{required: true, message: '请输入排序'}]"
      >
        <el-input placeholder="请输入排序" v-model="form.sysMusicScore.order"/>
      </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" clearable 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
              :prop="`sysMusicScoreAccompaniments.${index}.isShowFingering`"
              label="指法展示"
              :rules="[{required: true, message: '请选择是否展示指法'}]"
            >
              <el-select style="width: 100%!important;" v-model="song.isShowFingering" placeholder="请选择是否展示指法">
                <el-option
                  :value="true"
                  label="是"
                ></el-option>
                <el-option
                  :value="false"
                  label="否"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :prop="`sysMusicScoreAccompaniments.${index}.memo`"
              label="描述"
            >
              <el-input placeholder="请输入描述" v-model="song.memo"/>
            </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'
import { getAllmemberRank } from "@/views/resetTeaming/api";
export default {
  props: ['detail', 'type'],
  data() {
    return {
      tree: [],
      memberRankList: [], // 会员列表
      form: {
        rankIdType: 0, // 收费会员类型 默认免费
        sysMusicScore: {
          name: '',
          rankIds: '', // 收费会员编号
          url: '',
          order: '',
          musicScoreCategoriesId: [],
          clientType: '',
        },
        sysMusicScoreAccompaniments: [
          {
            subjectId: '',
            speed: '',
            mp3Url: '',
            xmlUrl: '',
            isShowFingering: null,
            mome: '',
          },
        ],
        delExamSongAccompanimentIds: []
      },
      treeProps: {
        value: 'id',
        label: 'name',
        children: 'sysMusicScoreCategoriesList',
      }
    }
  },
  async mounted() {
    this.$store.dispatch('setSubjects')
    await this.FetchTree()
    await this.memberRank()
    if (this.detail) {
      // console.log(this.detail)
      this.$set(this.form, 'sysMusicScore', {
        name: this.detail.name,
        url: this.detail.url,
        rankIds: this.detail.rankIds,
        order: this.detail.order,
        clientType: this.detail.clientType,
        musicScoreCategoriesId: this.detail.categoriesId ? this.formatParentId(this.detail.categoriesId, this.tree) : [],
      })
      if(this.detail.rankIds) {
        this.form.rankIdType = 1
      } else {
        this.form.rankIdType = 0
      }
      this.FeatchDetailList()
    }
  },
  methods: {
    rankChange(value) {
      if(value) {
        let tempIds = []
        this.memberRankList.forEach(item => {
          tempIds.push(item.id)
        })
        this.form.sysMusicScore.rankIds = tempIds.join(',')
      } else {
        // 会员购买重置
        this.form.sysMusicScore.rankIds = ''
      }
    },
    async memberRank() {
      try {
        const res = await getAllmemberRank({ isDefault: 0 });
        this.memberRankList = res.data || [];
      } catch (e) {
        console.log(e);
      }
    },
    formatParentId(id, list, ids = []) {
      for (const item of list) {
        if (item.sysMusicScoreCategoriesList) {
          const cIds = this.formatParentId(id, item.sysMusicScoreCategoriesList, [...ids, item.id])
          if(cIds.includes(id)) {
            return cIds
          }
        }
        if (item.id === id) {
          return [...ids, id]
        }
      }
      return ids
    },
    async FetchTree() {
      try {
        const res = await queryTree()
        this.tree = res.data
      } catch (error) {

      }
    },
    async FeatchDetailList() {
      try {
        const res = await queryPageSysExam({
          sysMusicScoreId: this.detail.id
        })
        const result = res.data || []
        result.forEach(item => {
          if(!item.subjectId) {
            item.subjectId = null
          }
        })
        this.$set(this.form, 'sysMusicScoreAccompaniments', result)
      } 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',
                showFlag: 0,
                musicScoreCategoriesId: (this.form.sysMusicScore.musicScoreCategoriesId || []).pop(),
              }
            })
            this.$message.success('提交成功')
          } else {
            await Update({
              ...this.form,
              sysMusicScore: {
                ...this.form.sysMusicScore,
                type: 'COMMON',
                id: this.detail.id,
                showFlag: this.detail.showFlag,
                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>
