<template>
    <div class="signUpLevel">
        <!-- <m-header /> -->
        <m-step :number="3" />

        <div class="title">报考专业</div>
        <van-field readonly required @click="onGetSheetList('examSubject')" name="subjectId" label="报考专业" placeholder="请选择" v-model="formText.subjectName" is-link />
        <van-field readonly required @click="onGetSheetList('level')" name="levelId" label="专业级别" placeholder="请选择" v-model="formText.levelName" is-link />
        <div class="title">报考曲目</div>
        <div v-if="form.levelId" class="van-hairline--bottom">
            <div class="van-hairline--bottom" v-if="practiceSongIdList" key="practiceNum">
                <van-field required readonly v-for="(item, index) in practiceNum" :key="index" :label="`练习曲${numberToCN(index)}名称及作者`" v-model.trim="practiceSelect[index]" @click="onChangePractice('practice', index)" placeholder="请选择" is-link />
            </div>
            <div class="van-hairline--bottom" v-else key="practiceNum">
                <van-field required readonly v-model.trim="practiceSelect[index]" v-for="(item, index) in practiceNum" :key="index" clearable name="code" :label="`练习曲${numberToCN(index)}名称及作者`" >
                    <template #button>
                        <span class="codeText" @click="onUploadSong('practiceNum', index)">上传曲目</span>
                    </template>
                </van-field>
            </div>

            <div v-if="performSongIdList" key="performNum">
                <van-field required readonly v-for="(item, index) in performNum" :key="index" :label="`演奏曲${numberToCN(index)}名称及作者`" v-model.trim="performNumSelect[index]" @click="onChangePractice('performNum', index)" placeholder="请选择" is-link />
            </div>
            <div v-else key="performNum">
                <van-field required readonly v-model.trim="performNumSelect[index]" v-for="(item, index) in performNum" :key="index" clearable name="code" :label="`演奏曲${numberToCN(index)}名称及作者`" >
                    <template #button>
                        <span class="codeText" @click="onUploadSong('performNum', index)">上传曲目</span>
                    </template>
                </van-field>
            </div>
        </div>
        <!-- <div class="title">上传证书</div> -->
        <!-- <van-field readonly clickable name="nation" label="上次考级级别" placeholder="请选择级别" is-link /> -->
        <van-field readonly clearable name="code" label="已获最高等级专业证书" >
            <template #input>
                <van-uploader
                    name="certificate"
                    :before-read="beforeRead"
                    :before-delete="beforeDelete"
                    :after-read="afterRead"
                    accept="image/*"
                    v-model="uploadCertificate"
                    :max-count="1" />
            </template>
        </van-field>
        <div class="title">乐理知识</div>
        <van-field required @click="onGetSheetList('examMusicTheory')" readonly clickable name="nation" label="乐理级别" v-model="formText.examMusicTheoryName" placeholder="请选择乐理级别" is-link />
        <!-- <van-field readonly clickable name="nation" label="上次考级级别" placeholder="请选择" is-link /> -->
        <!-- 乐理级别为免考 和 专业级别大于2级 -->
        <!-- :required="form.examMusicTheoryId == 999 &&  form.levelId > 2? true : false" -->
        <van-field readonly clearable name="code" label="已获最高等级乐理证书" >
            <template #input>
                <van-uploader
                    name="certificate2"
                    :before-read="beforeRead"
                    :before-delete="beforeDelete"
                    :after-read="afterRead"
                    v-model="uploadCertificate2"
                    accept="image/*"
                    :max-count="1" />
            </template>
        </van-field>
        <div class="title">指导老师</div>
        <van-field name="adviserName" v-model="form.adviserName" label="老师姓名" placeholder="请输入老师姓名" />
        <van-field name="adviserPhone" maxlength="11" v-model="form.adviserPhone" type="tel" label="联系方式" placeholder="请输入联系方式" />
        <div class="m-btn-group">
            <van-button class="btn_prev" round color="#2DC7AA" @click="onBack" style="background-color: transparent" plain>上一步</van-button>
            <van-button round color="#2DC7AA" @click="onSubmit">确认报名</van-button>
        </div>

        <!-- 报考专业弹窗 -->
        <van-popup v-model="sheetForm.sheetStatus" position="bottom">
            <van-picker :loading="sheetForm.loading" :default-index="sheetForm.index" :columns="sheetForm.columns" show-toolbar @cancel="sheetForm.sheetStatus = false" @confirm="onSheetConfirm" />
        </van-popup>

        <!-- 曲目弹窗 -->
        <van-popup v-model="sheetSong.status" position="bottom">
            <van-picker :default-index="sheetSong.index" :columns="sheetSong.columns" show-toolbar @cancel="sheetSong.status = false" @confirm="onPracticeConfirm" />
        </van-popup>

        <van-popup class="van-popup-song" v-model="songUpload.songStatus" :close-on-click-overlay="false">
            <div class="song-popup">
                <div class="title">自定义曲目</div>
                <van-field name="songName" v-model="songUpload.name" label="曲名" placeholder="请输入曲名" >
                    <template #label><i style="color: #ee0a24">*</i>曲名</template>
                </van-field>
                <van-field name="songAuthor" v-model="songUpload.author" label="作者" placeholder="请输入作者" >
                    <template #label><i style="color: #ffffff">*</i>作者</template>
                </van-field>
                <van-field readonly clearable >
                    <template #input>
                        <van-uploader
                            v-if="songUpload.indexName == 'practiceNum'"
                            :name="songUpload.indexName + '-' + songUpload.index"
                            :before-read="beforeRead"
                            :before-delete="beforeDelete"
                            :after-read="afterRead"
                            v-model.trim="practiceUpload[songUpload.index]"
                            multiple
                            accept="image/*"
                            :max-count="5" >
                        </van-uploader>
                        <van-uploader
                            v-if="songUpload.indexName == 'performNum'"
                            :name="songUpload.indexName + '-' + songUpload.index"
                            :before-read="beforeRead"
                            :before-delete="beforeDelete"
                            :after-read="afterRead"
                            v-model.trim="performNumUpload[songUpload.index]"
                            multiple
                            accept="image/*"
                            :max-count="5" >
                        </van-uploader>
                    </template>
                </van-field>
                <p class="song-popup-tips"><i style="color: #ee0a24">*</i>支持格式：png，jpg，bmp</p>

                <div class="popup-group">
                    <span @click="onSaveCancel">取消</span>
                    <span class="popup-sure" @click="onSaveUpload">确定</span>
                </div>
            </div>
        </van-popup>
    </div>
</template>
<script>
import MStep from '@/components/MStep'
import setLoading from '@/utils/loading'
import { patternPhone } from '@/utils/validateRules'
import { getExamSubjects, getExamSubjectLevel, getExamSubjectSong, uploadFile, getTheoryLevelList, getExamIngOrder, closeOrder } from './SignUpApi'
// import fileUtil from '@/utils/fileUtil'
const levelToCN = {
    1: "壹级",
    2: "贰级",
    3: "叁级",
    4: "肆级",
    5: "伍级",
    6: "陆级",
    7: "柒级",
    8: "捌级",
    9: "玖级",
    10: "拾级",
}
export default {
    name: 'signUpLevel',
	components: { MStep },
    data () {
        const examId = localStorage.getItem('examId')
        const organId = localStorage.getItem('organId')
        const examRegistrationParams = localStorage.getItem("examRegistrationParams") ? JSON.parse(localStorage.getItem("examRegistrationParams")) : null
        return {
            examId: examId,
            organId: organId,
            examRegistrationParams: examRegistrationParams,
            patternPhone: patternPhone,
            sheetForm: { // 上拉弹窗
                currentType: null, // 当前选择的类型
                sheetStatus: false,
                loading: false, // 加载数据
                index: 0, // 选中的索引值
                columns: []
            },
            examSubjectList: [], // 报考专业
            examSubjectIndex: 0, // 报考专业选择项目索引
            levelList: [], // 专业级别
            levelIndex: 0, // 专业级别选择项目索引
            practiceNum: 0, // 练习曲数量
            practiceSongIdList: null,
            performNum: 0, // 演奏曲数量
            performSongIdList: null,
            songList: [], //歌曲数量（包括练习曲和演奏曲）
            songUpload: {
                songStatus: false, // 曲目状态
                indexName: null,
                index: null, // 索引
                name: null, // 曲名
                author: null // 作者
            },
            form: {
                subjectId: null,
                levelId: null, // 级别
                examSubjectSongId: null, // 级别编号
                adviserName: null, // 老师姓名
                adviserPhone: null, // 联系电话
                lastExamCertificateUrl: null,
                lastMusicTheoryCertificateUrl: null,
                examMusicTheoryId: null,
                examMusicTheoryLevel: null,
                levelFee: 0,// 级别费用
                theoryLevelFee: 0, // 乐理费用
            },
            formText: {
                subjectName: null,
                levelName: null,
                examMusicTheoryName: null
            },
            sheetSong: { // 上拉弹窗
                status: false,
                index: 0, // 选中的索引值
                columns: []
            },
            practiceSelect: [], // 练习曲循环列表
            practiceSelectUploadList: [],
            practiceSelectList: [], // 弹窗练习曲列表
            practiceSelectIds: [], // 选中练习曲编号
            performNumSelect: [], // 演奏曲循环列表
            performNumSelectUploadList: [],
            performNumSelectList: [], // 弹窗演奏曲列表
            performNumSelectIds: [], // 选中演奏曲编号
            songSelectIndex: null, // 选中的哪个
            uploadCertificate: [],  // 上传证书
            uploadCertificate2: [], // 上传乐理证书
            practiceUpload: [],
            practiceUploadTemp: [],
            performNumUpload: [],
            performNumUploadTemp: [],
            examMusicTheoryList: [], // 乐理列表
            examMusicTheoryIndex: 0, // 乐理索引
        }
    },
    mounted() {
        // 插入token
        // let params = this.$route.query
        // if(params.Authorization) {
        //     localStorage.setItem('Authorization', decodeURI(params.Authorization))
        //     localStorage.setItem('userInfo', decodeURI(params.Authorization))
        // }
        this.__init()
        if(this.examRegistrationParams) {
            this.getRegisterInfo(this.examRegistrationParams)
        } else {
            this.getTheoryLevelList()
        }

        this.onCheckOrder() // 查询有没有待支付订单
        // this.form.levelId = 1
        // this.practiceNum = 2
        // this.practiceSongIdList = ""
        // this.performNum = 2
        // this.performSongIdList = ""
        // this.getExamSubjectSong()
    },
    methods: {
        async onCheckOrder() {
            const order = await getExamIngOrder({ examinationBasicId: this.examId })
            const resultOrder = order.data
            if(resultOrder.code == 200 && resultOrder.data) {
                this.$dialog.confirm({
                    title: '提示',
                    message: "您当前有待支付订单",
                    confirmButtonColor: '#269a93',
                    cancelButtonText: '取消订单',
                    confirmButtonText: '去支付'
                }).then(() => {
                    this.$router.push({
                        path: '/signUpPayment',
                        query: {
                            orderNo: resultOrder.data.orderNo,
                            examRegistrationId: resultOrder.data.examRegistrationId
                        }
                    })
                }).catch(() => {
                    const orderNo = resultOrder.data.orderNo
                    this.$dialog.close()
                    if(!orderNo) {
                        return
                    }
                    localStorage.removeItem("examRegistrationParams")
                    this.onCloseOrder(orderNo)
                })
            } else {
                localStorage.removeItem("examRegistrationParams")
            }
        },
        async onCloseOrder(orderNo) {
            setLoading(true)
            await closeOrder({ orderNo: orderNo })
            setLoading(false)
        },
        async getRegisterInfo(data) {
            if(!data) { // 判断是否有数据
                return
            }
            let form = this.form,
                formText = this.formText
            form.subjectId = data.subjectId // 报考专业专业
            formText.subjectName = data.subjectName // 报考专业名称
            form.levelFee = data.levelFee,// 级别费用
            form.theoryLevelFee = data.theoryLevelFee, // 乐理费用
            this.getExamSubjectLevel((tempList) => {
                //
                tempList.forEach(item => {
                    if(item.level == data.level) {
                        form.levelId = item.value
                        form.examSubjectSongId = item.id
                        formText.levelName = levelToCN[data.level]
                        this.practiceNum = item.practiceNum
                        this.practiceSongIdList = item.practiceSongIdList
                        this.performNum = item.performNum
                        this.performSongIdList = item.performSongIdList
                    }
                })

                // 报考曲目
                this.getExamSubjectSong()

                const songJsonParse = data.songJson ? JSON.parse(data.songJson) : []
                let tempPracticeArr = [],
                    tempPracticeStr = [],
                    tempPerformArr = [],
                    tempPerformStr = []
                songJsonParse.forEach(item => {
                    const str = item.songName + (item.songAuthor ? "-" + item.songAuthor : "")
                    if(item.type == "PERFORM") {
                        tempPerformArr.push(item)
                        tempPerformStr.push(str)
                        this.performNumSelectIds.push(item.id)
                    } else if(item.type == "PRACTICE") {
                        tempPracticeArr.push(item)
                        tempPracticeStr.push(str)
                        this.practiceSelectIds.push(item.id)
                    }
                })
                // 练习课 "PRACTICE"
                this.practiceSelect = tempPracticeStr
                if(this.practiceSongIdList) {
                    this.practiceSelectList = tempPracticeArr
                } else {
                    tempPracticeArr.forEach(item => {
                        item.name = item.songName
                        item.author = item.songAuthor
                        const urlList = item.uploadUrl ? item.uploadUrl.split(',') : []
                        let tempUrl = []
                        urlList.forEach(url => {
                            tempUrl.push({
                                url: url
                            })
                        })
                        this.practiceUpload.push(tempUrl)
                        this.practiceUploadTemp.push(tempUrl)
                    })
                    this.practiceSelectUploadList = tempPracticeArr
                }
                // 演奏课 "PERFORM"
                this.performNumSelect = tempPerformStr
                if(this.performSongIdList) {
                    this.performNumSelectList = tempPerformArr
                } else {
                    tempPerformArr.forEach(item => {
                        item.name = item.songName
                        item.author = item.songAuthor
                        const urlList = item.uploadUrl ? item.uploadUrl.split(',') : []
                        let tempUrl = []
                        urlList.forEach(url => {
                            tempUrl.push({
                                url: url
                            })
                        })
                        this.performNumUpload.push(tempUrl)
                        this.performNumUploadTemp.push(tempUrl)
                    })
                    this.performNumSelectUploadList = tempPerformArr
                }
            }) // 获取专业级别

            // 上传证书（上次考级证书）
            if(data.lastExamCertificateUrl) {
                form.lastExamCertificateUrl = data.lastExamCertificateUrl
                this.uploadCertificate = [{ url: data.lastExamCertificateUrl }]
            }
            // 乐理知识
            this.getTheoryLevelList((tempList) => {
                tempList.forEach(item => {
                    if(!data.examMusicTheoryId && !data.examMusicTheoryLevel) {
                        form.examMusicTheoryId = 999
                        form.examMusicTheoryLevel = 999
                        formText.examMusicTheoryName = "免考"
                    } else if(item.level == data.examMusicTheoryLevel) {
                        form.examMusicTheoryId = item.id
                        form.examMusicTheoryLevel = item.level
                        formText.examMusicTheoryName = item.text
                    }
                })
            })

            if(data.lastMusicTheoryCertificateUrl) {
                form.lastMusicTheoryCertificateUrl = data.lastMusicTheoryCertificateUrl
                this.uploadCertificate2 = [{ url: data.lastMusicTheoryCertificateUrl }]
            }
            form.adviserName = data.adviserName
            form.adviserPhone = data.adviserPhone
        },
        async __init() {
            setLoading(true)
            try {
                // 获取报考专业
                const res = await getExamSubjects({ examId: this.examId })
                const result = res.data
                if(result.code == 200 && result.data.length > 0) {
                    let tempArr = []
                    result.data.forEach(item => {
                        item.value = item.id
                        item.text = item.name
                        tempArr.push(item)
                    })
                    this.examSubjectList = tempArr
                }
            } catch(err) {
                //
            }
            setLoading(false)
        },
        async getTheoryLevelList(callBack) {
            setLoading(true)
            try {
                const resTheory = await getTheoryLevelList({ examId: this.examId })
                const resultTheory = resTheory.data
                if(resultTheory.code == 200 && resultTheory.data.length > 0) {
                    let tempArr2 = [{
                        id: 999,
                        value: 999,
                        text: "免考",
                        level: 999,
                        fee: 0
                    }]
                    resultTheory.data.forEach(item => {
                        item.value = item.id
                        item.text = levelToCN[item.level]
                        tempArr2.push(item)
                    })
                    this.examMusicTheoryList = tempArr2
                    callBack && callBack(tempArr2)
                }
            } catch(err) {
                //
            }
            setLoading(false)
        },
        onGetSheetList(type) {
            let sheetForm = this.sheetForm
            let form = this.form
            sheetForm.columns = []
            sheetForm.currentType = type
            sheetForm.index = 0
            // 报考专业
            if(type === "examSubject") {
                if(this.examSubjectList.length > 0) {
                    sheetForm.sheetStatus = true
                    sheetForm.columns = this.examSubjectList
                    sheetForm.index = this.examSubjectIndex
                } else {
                    this.$toast("暂无报考专业")
                    return
                }
            } else if(type === "level") {
                if(!form.subjectId) {
                    this.$toast("请选择报考专业")
                    return
                }
                if(this.levelList.length > 0) {
                    sheetForm.sheetStatus = true
                    sheetForm.columns = this.levelList
                    sheetForm.index = this.levelIndex
                } else {
                    this.$toast("暂无报专业级别")
                    return
                }
            } else if(type == "examMusicTheory") {
                if(this.examMusicTheoryList.length > 0) {
                    sheetForm.sheetStatus = true
                    sheetForm.columns = this.examMusicTheoryList
                    sheetForm.index = this.examMusicTheoryIndex
                } else {
                    this.$toast("暂无乐理级别")
                    return
                }
            }
        },
        onSheetConfirm(value, index) {
            let sheetForm = this.sheetForm,
                form = this.form,
                formText = this.formText
            if(!value) { // 判断是否在选中的值
                sheetForm.sheetStatus = false
                return
            }
            if(sheetForm.currentType == "examSubject") {
                if(form.subjectId != value.id) {
                    form.subjectId = value.id
                    formText.subjectName = value.name
                    this.examSubjectIndex = index

                    // 清除专业级别
                    form.levelId = null
                    formText.levelName = null
                    form.examSubjectSongId = null
                    form.levelFee = 0
                    this.levelIndex = 0
                    this.practiceNum = 0 // 练习曲数量
                    this.practiceSongIdList = null
                    this.performNum = 0 // 演奏曲数量
                    this.performSongIdList = null
                    this.onResetSong()
                    this.getExamSubjectLevel() // 请求专业级别
                }
                sheetForm.sheetStatus = false
            } else if(sheetForm.currentType == 'level') {
                sheetForm.sheetStatus = false
                if(form.levelId === value.value) { // 判断两次选择是否是一样
                    return
                }
                form.levelId = value.value
                form.examSubjectSongId = value.id
                form.levelFee = value.registrationFee // 级别费用
                formText.levelName = value.text
                this.levelIndex = index
                this.practiceNum = value.practiceNum
                this.practiceSongIdList = value.practiceSongIdList
                this.performNum = value.performNum
                this.performSongIdList = value.performSongIdList

                this.onResetSong()
                this.getExamSubjectSong()
            } else if(sheetForm.currentType == "examMusicTheory") {
                form.examMusicTheoryId = value.value
                form.theoryLevelFee = value.fee
                form.examMusicTheoryLevel = value.level
                formText.examMusicTheoryName = value.text
                this.examMusicTheoryIndex = index
                sheetForm.sheetStatus = false
            }
        },
        onResetSong() { // 重置报考曲目数据
            this.practiceSelect = []
            this.practiceUpload = []
            this.practiceUploadTemp = []
            this.practiceSelectUploadList = []
			this.practiceSelectIds = []
            this.performNumSelectUploadList = []
            this.performNumSelect = []
            this.performNumUpload = []
            this.performNumUploadTemp = []
			this.performNumSelectIds = []
        },
        async getExamSubjectLevel(callBack) {
            setLoading(true)
            try {
                const form = this.form
                const res = await getExamSubjectLevel({ examSubjectId: form.subjectId, examinationBasicId: this.examId })
                const result = res.data
                if(result.code == 200 && result.data.length > 0) {
                    let tempArr = []
                    result.data.forEach(item => {
                        item.value = item.level
                        item.text = levelToCN[item.level]
                        tempArr.push(item)
                    })
                    this.levelList = tempArr
                    callBack && callBack(tempArr)
                }
            } catch(err) {
                //
            }
            setLoading(false)
        },
        async getExamSubjectSong(callBack) {
            setLoading(true)
            try {
                const form = this.form
                const params = {
                    examSubjectId: form.subjectId,
                    examinationBasicId: this.examId,
                    level: form.levelId
                }
                const res = await getExamSubjectSong(params)
                const result = res.data
                if(result.code == 200 && result.data.length > 0) {
                    let tempArr = []
                    result.data.forEach(item => {
                        item.value = item.id
                        item.text = item.songName + '-' + item.songAuthor
                        tempArr.push(item)
                    })
                    this.songList = tempArr

                    callBack && callBack(tempArr)
                }
            } catch(err) {
                //
            }
            setLoading(false)
        },
        onChangePractice(type, index) {
            let songList = this.songList
            let sheetSong = this.sheetSong
            sheetSong.columns = []
            sheetSong.index = 0
            let tempPracticeArr = [],
                tempPerformArr = []
            songList.forEach(item => {
                if(item.type == "PERFORM") {
                    // if(this.performNumSelectIds.includes(item.id)) {
                    //     item.disabled = true
                    // } else {
                    //     item.disabled = false
                    // }
                    tempPerformArr.push(item)
                } else if(item.type == "PRACTICE") {
                    // if(this.practiceSelectIds.includes(item.id)) {
                    //     item.disabled = true
                    // } else {
                    //     item.disabled = false
                    // }
                    tempPracticeArr.push(item)
                }
            })
            if(type == 'practice') {
                sheetSong.columns = tempPracticeArr
            } else if(type == 'performNum') {
                sheetSong.columns = tempPerformArr
            }
            this.songSelectIndex = index
            sheetSong.status = true
        },
        onPracticeConfirm(value) {
            // 没有内容
            if(!value) {
                return
            }
            let songSelectIndex = this.songSelectIndex
            if(value.type == "PRACTICE") { // 练习
                this.practiceSelect[songSelectIndex] = value.text
                this.practiceSelectIds[songSelectIndex] = value.value
                this.practiceSelectList[songSelectIndex] = value
            } else if(value.type == "PERFORM") { // 演奏
                this.performNumSelect[songSelectIndex] = value.text
                this.performNumSelectIds[songSelectIndex] = value.value
                this.performNumSelectList[songSelectIndex] = value
            }

            this.sheetSong.status = false
        },
        beforeRead(file) {
            const isLt2M = file.size / 1024 / 1024 < 5

            if (!isLt2M) {
                this.$toast('上传图片大小不能超过 5MB')
                return false
            }
            // return new Promise((resolve) => {
            //     fileUtil.getOrientation(file).then((orient) => {
            //         console.log(orient)
            //         if (orient && orient != "" && orient != 1) {
            //             let reader = new FileReader()
            //             let img = new Image()
            //             reader.onload = (e) => {
            //                 img.src = e.target.result
            //                 img.onload = function () {
            //                     const data = fileUtil.rotateImage(img, img.width, img.height, orient)
            //                     const newFile = fileUtil.dataURLtoFile(data, file.name)
            //                     resolve(newFile)
            //                 }
            //             }
            //             reader.readAsDataURL(file)
            //         } else {
            //             resolve(file)
            //         }
            //     })
            // })
            return true
        },
        beforeDelete(file, detail) {
            const obj = detail.name.split('-')
            let form = this.form
            if(obj[0] == "certificate2") {
                form.lastMusicTheoryCertificateUrl = "" // 上传图片地址为空
            } else if(obj[0] == "certificate") {
                form.lastExamCertificateUrl = ""
            }
            return true
        },
        async afterRead(file, detail) { // 上传头像
            const obj = detail.name.split('-')
            try {
                file.status = 'uploading'
                file.message = '上传中...'
                let formData = new FormData()
                formData.append('file', file.file)
                let res = await uploadFile(formData)
                let result = res.data
                if(result.code == 200) {
                    file.status = 'done'
                    let form = this.form
                    if(obj[0] == "certificate2") {
                        form.lastMusicTheoryCertificateUrl = result.data.url // 上传图片地址为空
                    } else if(obj[0] == "certificate") {
                        form.lastExamCertificateUrl = result.data.url
                    } else if(obj[0] == 'practiceNum') {
                        file.url = result.data.url
                    } else if(obj[0] == 'performNum') {
                        file.url = result.data.url
                    }
                } else {
                    file.status = 'failed'
                    file.message = '上传失败'
                    this.$toast(result.msg)
                    return false
                }
            } catch (err) {
                return false
            }
        },
        onUploadSong(value, index) { // 上传曲目
            let songUpload = this.songUpload
            songUpload.songStatus = true
            songUpload.indexName = value
            songUpload.index = index
            let practiceSUL = this.practiceSelectUploadList[index]
            let performSUL = this.performNumSelectUploadList[index]
            if(value == "practiceNum") {
                songUpload.name = practiceSUL ? practiceSUL.name : null
                songUpload.author = practiceSUL ? practiceSUL.author : null
            } else if(value == "performNum") {
                songUpload.name = performSUL ? performSUL.name : null
                songUpload.author = performSUL ? performSUL.author : null
            }
        },
        onSaveCancel() {
            this.songUpload.songStatus = false
            this.performNumUpload = JSON.parse(JSON.stringify(this.performNumUploadTemp)) // 回填数据
            this.practiceUpload = JSON.parse(JSON.stringify(this.practiceUploadTemp)) // 回填数据
        },
        onSaveUpload() {
            let songUpload = this.songUpload
            if(!songUpload.name) {
                this.$toast("请输入曲名")
                return
            }
            const nameAuthor = songUpload.name + (songUpload.author ? "-" + songUpload.author : "")
            if(songUpload.indexName == "practiceNum") {
                const practiceObj = this.practiceUpload[songUpload.index]
                const practiceLength = practiceObj ? practiceObj.length : 0
                if(practiceObj && practiceLength > 0 && practiceObj[0].url) {
                    if(practiceObj[practiceLength - 1].url) {
                        this.practiceSelect[songUpload.index] = nameAuthor
                        this.practiceSelectUploadList[songUpload.index] = JSON.parse(JSON.stringify(songUpload))
                        this.practiceUploadTemp = JSON.parse(JSON.stringify(this.practiceUpload))
                    } else {
                        this.$toast("上传曲谱中，请稍等")
                        return
                    }
                } else {
                    this.$toast("请上传文件")
                    return
                }
            } else if(songUpload.indexName == "performNum") {
                const performObj = this.performNumUpload[songUpload.index]
                const performLength = performObj ? performObj.length : 0
                if(performObj && performLength > 0) {
                    if(performObj[performLength - 1].url) {
                        this.performNumSelect[songUpload.index] = nameAuthor
                        this.performNumSelectUploadList[songUpload.index] = JSON.parse(JSON.stringify(songUpload))
                        this.performNumUploadTemp = JSON.parse(JSON.stringify(this.performNumUpload))
                    } else {
                        this.$toast("上传曲谱中，请稍等")
                        return
                    }
                } else {
                    this.$toast("请上传文件")
                    return
                }
            }
            songUpload.name = null
            songUpload.author = null
            songUpload.songStatus = false
        },
        async onSubmit() {
            setLoading(true)
            try {
                // 验证
                if(!this.onCheckFields()) {
                    return
                }
                let songJson = [] // json 数组
                // 练习课 "PRACTICE"
                if(this.practiceSongIdList) {  // 下拉选择
                    this.practiceSelectList.forEach(item => {
                        songJson.push({
                            id: item.id,
                            type: item.type,
                            songName: item.songName,
                            songAuthor: item.songAuthor,
                            uploadUrl: item.fileUrlList
                        })
                    })
                } else {  // 自选
                    const practiceUpload = this.practiceUpload
                    this.practiceSelectUploadList.forEach(item => {
                        let tempUrl = []
                        practiceUpload[item.index].forEach(item => {
                            tempUrl.push(item.url)
                        })
                        songJson.push({
                            songName: item.name,
                            songAuthor: item.author,
                            index: item.index,
                            type: "PRACTICE",
                            uploadUrl: tempUrl.join(',')
                        })
                    })
                }
                // 演奏课 "PERFORM"
                if(this.performSongIdList) {
                    this.performNumSelectList.forEach(item => {
                        songJson.push({
                            id: item.id,
                            type: item.type,
                            songName: item.songName,
                            songAuthor: item.songAuthor,
                            uploadUrl: item.fileUrlList
                        })
                    })
                } else {
                    const performNumUpload = this.performNumUpload
                    this.performNumSelectUploadList.forEach(item => {
                        let tempUrl = []
                        performNumUpload[item.index].forEach(item => {
                            tempUrl.push(item.url)
                        })
                        songJson.push({
                            songName: item.name,
                            songAuthor: item.author,
                            index: item.index,
                            type: "PERFORM",
                            uploadUrl: tempUrl.join(',')
                        })
                    })
                }

                let form = this.form,
                    formText = this.formText
                let params = {
                    // studentName: localStorage.getItem("studentName"),
                    examStartTime: localStorage.getItem("examStartTime"),
                    adviserName: form.adviserName,
                    adviserPhone: form.adviserPhone,
                    examMusicTheoryId: form.examMusicTheoryId == 999 ? null : form.examMusicTheoryId,
                    examMusicTheoryLevel: form.examMusicTheoryLevel == 999 ? null : form.examMusicTheoryLevel,
                    examinationBasicId: this.examId,
                    lastExamCertificateUrl: form.lastExamCertificateUrl,
                    lastMusicTheoryCertificateUrl: form.lastMusicTheoryCertificateUrl,
                    level: form.levelId,
                    examSubjectSongId: form.examSubjectSongId,
                    subjectId: form.subjectId, // 考级专业
                    subjectName: formText.subjectName,
                    songJson: JSON.stringify(songJson),
                    organId: this.organId,
                    levelFee: form.levelFee,
                    theoryLevelFee: form.theoryLevelFee
                }
                setLoading(false)
                localStorage.setItem("examRegistrationParams", JSON.stringify(params))
                this.$router.push({
                    path: '/signUpPayment'
                })
            } catch(err) {
                //
            }
        },
        onCheckFields() {
            // 校验数据
            let form = this.form
            if(!form.subjectId) {
                this.$toast('请选择报考专业')
                return false
            }

            if(!form.levelId) {
                this.$toast('请选择专业级别')
                return false
            }
            // 有值说明是列表
            if(this.practiceSongIdList) {
                if(this.practiceSelectIds.length != this.practiceNum) {
                    this.$toast('请选择练习曲')
                    return false
                }
                const tempIds = new Set(this.practiceSelectIds)
                if(this.practiceSelectIds.length != tempIds.size) {
                    this.$toast("不能选择重复的练习曲")
                    return false
                }
            } else {
                if(this.practiceUpload.length != this.practiceNum) {
                    this.$toast('请上传练习曲')
                    return false
                }

            }
            if(this.performSongIdList) {
                if(this.performNumSelectIds.length != this.performNum) {
                    this.$toast('请选择演奏曲')
                    return false
                }
                const tempIds = new Set(this.performNumSelectIds)
                if(this.performNumSelectIds.length != tempIds.size) {
                    this.$toast("不能选择重复的演奏曲")
                    return false
                }
            } else {
                if(this.performNumUpload.length != this.performNum) {
                    this.$toast('请上传演奏曲')
                    return false
                }
            }

            if(!form.examMusicTheoryId) {
                this.$toast('请选择乐理级别')
                return false
            }

            // if(form.examMusicTheoryId == 999 && form.levelId > 2 && !form.lastMusicTheoryCertificateUrl) {
            //     this.$toast('请上传乐理证书')
            //     return false
            // }

            if(form.adviserPhone && !this.checkPhone(form.adviserPhone)) {
                return false
            }
            return true
        },
        checkPhone(phoneNumber) {
            let result = true
            if(!(this.patternPhone.test(phoneNumber))){
                this.$toast('联系方式输入有误')
                result = false
            }
            return result
        },
        onBack() { // 上一步
            window.history.go(-1)
        },
        numberToCN (value) {
            const tempNumber = {
                0: '一',
                1: '二',
                2: '三',
                3: '四',
                4: '五',
                5: '六',
                6: '七',
                7: '八',
                8: '九',
                9: '十',
            }
            return tempNumber[value]
        }
    },
    destroyed() {
		this.$toast.clear()
		this.$dialog.close()
	}
}
</script>
<style lang="less" scoped>
@import url("../../assets/commonLess/variable");
.signUpLevel {
    // height: 100vh;
    padding-bottom: 1rem;
    overflow-y: auto;
    overflow-x: hidden;
    background-color: @--main-bg-color;
    position: relative;
    .title {
        font-size: .16rem;
        color: @--font-second-color;
        padding: .12rem .16rem;
    }
    /deep/.van-cell {
        padding: .13rem .16rem;
    }
    /deep/.van-field__label {
        font-size: .17rem;
        color: @--font-main-color;
        width: 1.15rem;
    }
    /deep/.van-field__body {
        font-size: .16rem
    }

    .codeText {
        font-size: .16rem;
        color: @--main-color;
    }
}

.van-popup-song {
    width: 80%;
    border-radius: .08rem;
}
.song-popup {
    text-align: center;
    .title {
        font-size: 18px;
        font-weight: 500;
        color: @--font-main-color;
        padding: .2rem 0 .15rem;
    }
    // .song-upload {
    //     margin: 0 .5rem;
    //     padding: .18rem 0 .1rem;
    //     border-radius: .05rem;
    //     border: 1px dashed transparent;
    //     background: linear-gradient(0deg, transparent 6px, #777777 6px) repeat-y,
    //         linear-gradient(0deg, transparent 50%, #777777 0) repeat-y,
    //         linear-gradient(90deg, transparent 50%, #777777 0) repeat-x,
    //         linear-gradient(90deg, transparent 50%, #777777 0) repeat-x;
    //     background-size: 1px 12px, 1px 12px, 12px 1px, 12px 1px;
    //     background-position: 0 0, 100% 0, 0 0, 0 100%;
    //     font-size: .16rem;
    //     color: #777;
    // }
    .song-upload {
        border-radius: .05rem;
        border: 1px solid #c5c7cb;
        background-position: 0 0, 100% 0, 0 0, 0 100%;
        font-size: .16rem;
        color: #777;
        width: 80px;
        height: 80px;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        .van-uploader__preview {
            margin: 0;
        }
        p {
            font-size: 13px;
        }
    }
    /deep/.van-uploader {
        margin: 0 auto;
    }
    /deep/.van-uploader__upload,
    /deep/.van-uploader__preview-image {
            width: 65px;
            height: 65px;
        }
    .song-popup-tips {
        font-size: .14rem;
        color: #808080;
        padding-bottom: .15rem
        // padding-top: .1rem;
        // padding-bottom: .25rem;
    }
    /deep/.van-cell {
        padding: 13px 35px;
    }
    /deep/.van-field__label {
        width: .8rem;
        text-align: left;
    }
    .popup-group {
        width: 100%;
        display: flex;
        color: @--main-color;
        background-color: #F0F0F0;
        font-size: .18rem;
        span {
            padding: .12rem 0;
            flex: 1;
        }
        .popup-sure {
            color: #ffffff;
            background-color: @--main-color;
        }
    }
}

/deep/.van-uploader__upload {
    margin-bottom: 0;
}

.m-btn-group {
    position: fixed;
    bottom: 0;
    width: calc(100% - .4rem);
    padding: .1rem .2rem;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    box-shadow:0px -1px 4px 0px rgba(226,226,226,1);
    .van-button {
        font-size: .18rem;
        height: .5rem;
        width: 48%;
    }
    .btn_prev:active {
        color: @--main-color !important;
        background-color: #F5FFFD !important;
    }
    .btn_prev:active::before {
        // background-color: #F5FFFD !important;
        // border-color: @--main-color !important;
        opacity: 0;
    }
}
</style>