<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 v-if="form.levelId">
            <div class="title">报考曲目</div>

            <div class="van-hairline--bottom" v-if="practiceSongIdList" key="practiceNum">
                <van-field required v-for="(item, index) in practiceNum" :key="index" readonly :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 v-for="(item, index) in practiceNum" :key="index" clearable name="code" :label="`练习曲${numberToCN(index)}名称及作者`" placeholder="自定义曲目" >
                    <template #input>
                        <van-uploader
                            :name="`practiceNum-${index}`"
                            :before-read="beforeRead"
                            :before-delete="beforeDelete"
                            :after-read="afterRead"
                            v-model.trim="practiceUpload[index]"
                            accept="image/*"
                            multiple
                            :max-count="1" />
                    </template>
                </van-field>
            </div>

            <div v-if="performSongIdList" key="performNum">
                <van-field required v-for="(item, index) in performNum" :key="index" readonly :label="`演奏曲${numberToCN(index)}名称及作者`" v-model.trim="performNumSelect[index]" @click="onChangePractice('performNum', index)" placeholder="请选择" is-link />
            </div>
            <div v-else key="performNum">
                <van-field required v-for="(item, index) in performNum" :key="index" clearable name="code" :label="`演奏曲${numberToCN(index)}名称及作者`" placeholder="自定义曲目" >
                    <template #input>
                        <van-uploader
                            :name="`performNum-${index}`"
                            :before-read="beforeRead"
                            :before-delete="beforeDelete"
                            :after-read="afterRead"
                            v-model.trim="performNumUpload[index]"
                            accept="image/*"
                            multiple
                            :max-count="1" />
                    </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"
                    multiple
                    :max-count="1" />
            </template>
        </van-field>
        <div class="title">乐理知识</div>
        <van-field required @click="onGetSheetList('examMusicTheory')" readonly clickable name="nation" label="专业级别" v-model="form.examMusicTheoryName" placeholder="请选择专业级别" is-link />
        <!-- <van-field readonly clickable name="nation" label="上次考级级别" placeholder="请选择" is-link /> -->
        <van-field readonly :required="form.examMusicTheoryId ? true : false" clearable name="code" label="上次考级证书" >
            <template #input>
                <van-uploader
                    name="certificate2"
                    :before-read="beforeRead"
                    :before-delete="beforeDelete"
                    :after-read="afterRead"
                    v-model="uploadCertificate2"
                    accept="image/*"
                    multiple
                    :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" label="联系方式" placeholder="请输入联系方式" />
        <div class="m-btn-group">
            <van-button round color="var(--main-color)" @click="onBack" style="background-color: transparent" plain>上一步</van-button>
            <van-button round color="var(--main-color)" @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="songStatus">
            <div class="song-popup">
                <div class="title">自定义曲目</div>
                <div class="song-upload">
                    <van-uploader multiple :max-count="1" :max-size="3 * 1024 * 1024" >
                        <div class="upload-container">
                            <van-icon name="plus" />
                            <p>点击上传</p>
                        </div>
                    </van-uploader>
                </div>
                <p class="song-popup-tips">支持格式：pdf，png，jpg，bmp</p>

                <div class="popup-group">
                    <span @click="songStatus = false">取消</span>
                    <span class="popup-sure" @click="songStatus = false">确定</span>
                </div>
            </div>
        </van-popup> -->
    </div>
</template>
<script>
import MHeader from '@/components/MHeader'
import MStep from '@/components/MStep'
import setLoading from '@/utils/loading'
import { patternPhone } from '@/utils/validateRules'
import { getExamSubjects, getExamSubjectLevel, getExamSubjectSong, uploadFile, getTheoryLevelList, examRegistrationAdd, examRegistrationUpdate } from './SignUpApi'
const levelToCN = {
    1: "一级",
    2: "二级",
    3: "三级",
    4: "四级",
    5: "五级",
    6: "六级",
    7: "七级",
    8: "八级",
    9: "九级",
    10: "十级",
}
export default {
    name: 'signUpLevel',
	components: { MHeader, MStep },
    data () {
        const examId = localStorage.getItem('examId')
        return {
            examId: examId,
            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: [], //歌曲数量（包括练习曲和演奏曲）
            songStatus: false, // 曲目状态
            form: {
                subjectId: null,
                levelId: null,
                adviserName: null, // 老师姓名
                adviserPhone: null, // 联系电话
                lastExamCertificateUrl: null,
                lastExamCertificateUrl2: null,
                examMusicTheoryId: null,
            },
            formText: {
                subjectName: null,
                levelName: null,
                examMusicTheoryName: null
            },
            sheetSong: { // 上拉弹窗
                status: false,
                index: 0, // 选中的索引值
                columns: []
            },
            practiceSelect: [], // 循环列表
            practiceSelectIds: [], // 选中练习曲编号
            performNumSelect: [],
            performNumSelectIds: [], // 选中演奏曲编号
            songSelectIndex: null, // 选中的哪个
            uploadCertificate: [],  // 上传证书
            uploadCertificate2: [], // 上传乐理证书
            practiceUpload: [],
            practiceUploadImg: [],
            performNumUpload: [],
            performNumUploadImg: [],
            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()
        // this.form.levelId = 1
        // this.practiceNum = 2
        // this.practiceSongIdList = ""
        // this.performNum = 2
        // this.performSongIdList = ""
        // this.getExamSubjectSong()
    },
    methods: {
        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
                }

                const resTheory = await getTheoryLevelList({ examId: this.examId })
                const resultTheory = resTheory.data
                if(resultTheory.code == 200 && resultTheory.data.length > 0) {
                    let tempArr2 = []
                    resultTheory.data.forEach(item => {
                        item.value = item.id
                        item.text = levelToCN[item.level]
                        tempArr2.push(item)
                    })
                    this.examMusicTheoryList = 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.examSubjectId) {
                    form.subjectId = value.examSubjectId
                    formText.subjectName = value.name
                    this.examSubjectIndex = index

                    // 清除报考级别
                    form.levelId = null
                    formText.levelName = null
                    this.levelIndex = 0
                    this.practiceNum = 0 // 练习曲数量
                    this.practiceSongIdList = null
                    this.performNum = 0 // 演奏曲数量
                    this.performSongIdList = null
                    this.getExamSubjectLevel() // 请求报考级别
                }
                sheetForm.sheetStatus = false
            } else if(sheetForm.currentType == 'level') {
                form.levelId = value.value
                formText.levelName = value.text
                this.levelIndex = index
                this.practiceNum = value.practiceNum
                this.practiceSongIdList = value.practiceSongIdList
                this.performNum = value.performNum
                this.performSongIdList = value.performSongIdList
                sheetForm.sheetStatus = false
                this.getExamSubjectSong()
            } else if(sheetForm.currentType == "examMusicTheory") {
                form.examMusicTheoryId = value.value
                form.examMusicTheoryName = value.text
                this.examMusicTheoryIndex = index
                sheetForm.sheetStatus = false
            }
        },
        async getExamSubjectLevel() {
            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
                }
            } catch(err) {
                //
            }
            setLoading(false)
        },
        async getExamSubjectSong() {
            setLoading(true)
            try {
                const form = this.form
                const params = {
                    // examSubjectId: form.subjectId,
                    // examinationBasicId: this.examId,
                    // level: form.levelId
                    examSubjectId: 5,
                    examinationBasicId: 6,
                    level: 1
                }
                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
                }
            } catch(err) {
                //
            }
            setLoading(false)
        },
        onChangePractice(type, index) {
            let songList = this.songList
            // console.log(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
            // console.log(sheetSong)
            // if(this.examSubjectList.length > 0) {
            //     sheetForm.sheetStatus = true
            //     sheetForm.columns = this.examSubjectList
            //     sheetForm.index = this.examSubjectIndex
            // } else {
            //     this.$toast("暂无报考专业")
            //     return
            // }
        },
        onPracticeConfirm(value) {
            // 没有内容
            if(!value) {
                return
            }
            let songSelectIndex = this.songSelectIndex
            if(value.type == "PRACTICE") { // 练习
                this.practiceSelect[songSelectIndex] = value.text
                this.practiceSelectIds[songSelectIndex] = value.value
            } else if(value.type == "PERFORM") { // 演奏
                this.performNumSelect[songSelectIndex] = value.text
                this.performNumSelectIds[songSelectIndex] = value.value
            }

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

            if (!isLt2M) {
                this.$toast('上传证书大小不能超过 2MB')
                return false
            }
            return true
        },
        beforeDelete(file, detail) {
            let form = this.form
            if(detail.name == "certificate2") {
                form.lastExamCertificateUrl2 = "" // 上传图片地址为空
            } else if(detail.name == "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.lastExamCertificateUrl2 = result.data.url // 上传图片地址为空
                    } else if(obj[0] == "certificate") {
                        form.lastExamCertificateUrl = result.data.url
                    } else if(obj[0] == 'practiceNum') {
                        this.practiceUploadImg[obj[1]] = result.data.url
                    } else if(obj[0] == 'performNum') {
                        this.performNumUploadImg[obj[1]] = result.data.url
                    }
                } else {
                    file.status = 'failed'
                    file.message = '上传失败'
                    this.$toast(result.msg)
                    return false
                }
            } catch (err) {
                return false
            }
        },
        async onSubmit() {
            // setLoading(true)
            this.$router.push({
                path: '/signUpPayment'
            })
            try {
                // 验证
                if(!this.onCheckFields()) {
                    return
                }
                let form = this.form,
                    formText = this.formText
                let params = {
                    adviserName: form.adviserName,
                    adviserPhone: form.adviserPhone,
                    examMusicTheoryId: form.examMusicTheoryId,
                    examMusicTheoryLevel: formText.examMusicTheoryName,
                    examSubjectSongId: form.subjectId,
                    examinationBasicId: this.examId,
                    lastExamCertificateUrl: form.lastExamCertificateUrl,
                    level: form.levelId
                }
                console.log("参数", params)
                let res = await examRegistrationAdd(params)
                setLoading(false)
                let result = res.data
                if(result.code == 200) {
                    //
                } else {
                    this.$toast(result.msg)
                }
            } 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
                }
            } else {
                if(this.practiceUploadImg.length != this.practiceNum) {
                    this.$toast('请上传练习曲')
                    return false
                }
            }

            if(this.performSongIdList) {
                if(this.performNumSelectIds.length != this.performNum) {
                    this.$toast('请选择演奏曲')
                    return false
                }
            } else {
                if(this.performNumUploadImg.length != this.performNum) {
                    this.$toast('请上传演奏曲')
                    return false
                }
            }

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

            if(form.examMusicTheoryId > 1 && !form.lastExamCertificateUrl2) {
                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: '五',
            }
            return tempNumber[value]
        }
    }
}
</script>
<style lang="less" scoped>
.signUpLevel {
    // height: 100vh;
    padding-bottom: 1rem;
    overflow-y: auto;
    overflow-x: hidden;
    background-color: var(--main-bg-color);
    position: relative;
    .title {
        font-size: .16rem;
        color: var(--font-second-color);
        padding: .12rem .16rem;
    }
    /deep/.van-cell {
        padding: .13rem .16rem;
    }
    /deep/.van-field__label {
        font-size: .17rem;
        color: var(--font-main-color);
        width: 1.15rem;
    }
    /deep/.van-field__body {
        font-size: .16rem
    }

    .codeText {
        font-size: .16rem;
        color: var(--main-color);
    }
}

// .van-popup-song {
//     width: 80%;
//     border-radius: .08rem;
// }
// .song-popup {
//     text-align: center;
//     .title {
//         font-size: 18px;
//         font-weight: 500;
//         color: var(--font-main-color);
//         padding: .2rem 0 .24rem;
//     }
//     .song-upload {
//         margin: 0 .5rem;
//         padding: .18rem 0 .1rem;
//         border-radius: .05rem;
//         // border: 1px dashed #777777;
//         border: 1px dashed transparent;
//         // background: linear-gradient(wihte, wihte);
//         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-popup-tips {
//         font-size: .14rem;
//         color: #808080;
//         padding-top: .1rem;
//         padding-bottom: .25rem;
//     }
//     .popup-group {
//         width: 100%;
//         display: flex;
//         color: var(--main-color);
//         background-color: #F0F0F0;
//         font-size: .18rem;
//         span {
//             padding: .12rem 0;
//             flex: 1;
//         }
//         .popup-sure {
//             color: #ffffff;
//             background-color: var(--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%;
    }
}
</style>