<template>
    <div class="appDetail">
        <!-- <m-header v-if="headerStatus" /> -->
		<van-cell-group>
            <!-- <van-field v-model="form.paymentOrderNo" disabled label="订单编号" /> -->
            <van-field v-model="form.examBaseName" disabled label="考级名称" />
            <van-cell disabled title="缴费状态">
                <div v-if="form.status">
                    <p class="noPass" v-if="form.status === 'PAY_WAIT'">未缴费</p>
                    <p class="pass" v-else>已缴费</p>
                </div>
            </van-cell>
            <van-field v-model="form.examStartTime" disabled label="考试日期" />
            <van-cell title="专业等级" >
                {{ form.subjectName }}<span v-if="form.level || form.level == 0">({{ form.level | formatLevel }})</span>
            </van-cell>
            <van-cell v-for="(item, index) in practiceInfo" :key="index" :title="`练习曲${numberToCN(index)}`" @click="onOpen('practice', index)" :is-link="form.practiceSongIdList ? false : true" >
                {{ item.songName }} {{ item.songAuthor ? '-' + item.songAuthor : item.songAuthor }}
            </van-cell>
            <van-cell v-for="(item, index) in performInfo" :key="index" :title="`演奏曲${numberToCN(index)}`" @click="onOpen('perform', index)" :is-link="form.performSongIdList ? false : true" >
                {{ item.songName }} {{ item.songAuthor ? '-' + item.songAuthor : item.songAuthor }}
            </van-cell>
            <van-field v-model="form.name" disabled label="考级证书" >
                <template #input>
                    <van-uploader
                        name="certificate"
                        :before-read="beforeRead"
                        :before-delete="beforeDelete"
                        :after-read="afterRead"
                        accept="image/*"
                        :disabled="!form.editStatus"
                        :deletable="form.editStatus"
                        v-model="uploadCertificate"
                        :max-count="1" />
                </template>
            </van-field>
            <van-cell disabled title="乐理等级" >
                {{ form.examMusicTheoryLevel | formatLevel }}
            </van-cell>
            <van-field v-model="form.name" disabled label="乐理证书" >
                <template #input>
                    <van-uploader
                        name="certificate2"
                        :before-read="beforeRead"
                        :before-delete="beforeDelete"
                        :after-read="afterRead"
                        v-model="uploadCertificate2"
                        accept="image/*"
                        :disabled="!form.editStatus"
                        :deletable="form.editStatus"
                        :max-count="1" />
                </template>
            </van-field>
        </van-cell-group>

        <van-cell-group class="memos">
            <van-cell disabled title="报名审核" v-if="form.status == 'AUDIT_REJECT'">
                <div v-if="form.status">
                    <p class="pass" v-if="form.status === 'AUDIT_PASS'">已通过</p>
                    <p v-else-if="form.status === 'AUDIT_WAIT'">等待审核</p>
                    <p class="noPass" v-else>未通过</p>
                </div>
            </van-cell>
            <van-cell title="备注" >
                {{ form.memo }}
            </van-cell>
        </van-cell-group>
        <van-button type="primary" v-if="form.editStatus" @click="onSubmit" round block>重新提交</van-button>

        <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.songName" :disabled="!form.editStatus" label="曲名" placeholder="请输入曲名" >
                    <template #label><i style="color: #ee0a24">*</i>曲名</template>
                </van-field>
                <van-field name="songAuthor" :disabled="!form.editStatus" v-model="songUpload.songAuthor" label="作者" placeholder="请输入作者" >
                    <template #label><i style="color: #ffffff">*</i>作者</template>
                </van-field>
                <van-field readonly clearable >
                    <template #input>
                        <van-uploader
                        v-if="songUpload.indexName == 'practice'"
                        :name="songUpload.indexName + '-' + songUpload.index"
                        :before-read="beforeRead"
                        :before-delete="beforeDelete"
                        :after-read="afterRead"
                        v-model.trim="practiceUpload[songUpload.index]"
                        multiple
                        :disabled="!form.editStatus"
                        :deletable="form.editStatus"
                        accept="image/*"
                        :max-count="5" >
                    </van-uploader>
                    <van-uploader
                        v-if="songUpload.indexName == 'perform'"
                        :name="songUpload.indexName + '-' + songUpload.index"
                        :before-read="beforeRead"
                        :before-delete="beforeDelete"
                        :after-read="afterRead"
                        v-model.trim="performUpload[songUpload.index]"
                        multiple
                        :disabled="!form.editStatus"
                        :deletable="form.editStatus"
                        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 @click="onSaveUpload" class="popup-sure">确定</span>
                </div>
            </div>
        </van-popup>
    </div>
</template>
<script>
import { browser } from '@/utils/common'
// import dayjs from 'dayjs'
import setLoading from '@/utils/loading'
// import fileUtil from '@/utils/fileUtil'
import { uploadFile, examRegistrationUpdate } from '../signup/SignUpApi'
import { applyList } from './appApi'
export default {
    name: 'appDetail',
    data () {
        const query = this.$route.query
        return {
            headerStatus: false,
            examRegistrationId: query.examRegistrationId,
            form: {
                id: null,
                paymentOrderNo: null,
                examBaseName: null,
                subjectName: null,
                level: null,
                status: null,
                examStartTime: null,
                lastExamCertificateUrl: null,
                examMusicTheoryLevel: null,
                lastMusicTheoryCertificateUrl: null,
                memo: null,
                practiceSongIdList: null,
                performSongIdList: null,
                editStatus: false
            },
            uploadCertificate: [],
            uploadCertificate2: [],
            songUpload: {
                songStatus: false, // 曲目状态
                indexName: null,
                index: null, // 索引
                songName: null, // 曲名
                songAuthor: null // 作者
            },
            practiceNum: null,
            performUpload: [], // 演奏曲
            performUploadTemp: [], // 演奏曲
            performInfo: [], // 演奏曲基本信息
            performNum: null,
            practiceUpload: [], // 练习曲
            practiceUploadTemp: [], // 练习曲
            practiceInfo: [], // 练习曲基本信息
        }
    },
    mounted() {
        // 插入token
        let params = this.$route.query
        if(params.Authorization) {
            localStorage.setItem('Authorization', decodeURI(params.Authorization))
        }
        // 判断是否在app里面
        if(!browser().android && !browser().iPhone) {
            this.headerStatus = true
        } else {
            document.title = '报考详情'
        }

        this.__init()
    },
    methods: {
        async __init() {
            setLoading(true)
            try {
                const res = await applyList({
                    page: 1,
                    rows: 20,
                    examRegistrationId: this.examRegistrationId
                })
                setLoading(false)
                const result = res.data
                if(result.code == 200) {
                    const detail = result.data.rows ? result.data.rows[0] : {}
                    this.form = {
                        id: detail.id,
                        paymentOrderNo: detail.paymentOrderNo,
                        examBaseName: detail.examBaseName,
                        subjectName: detail.subjectName,
                        level: detail.level,
                        status: detail.status,
                        examStartTime: detail.examStartTime,
                        lastExamCertificateUrl: detail.lastExamCertificateUrl,
                        examMusicTheoryLevel: detail.examMusicTheoryLevel,
                        lastMusicTheoryCertificateUrl: detail.lastMusicTheoryCertificateUrl,
                        memo: detail.memo,
                        practiceSongIdList: detail.practiceSongIdList,
                        performSongIdList: detail.performSongIdList,
                        editStatus: detail.status === "AUDIT_PASS" || detail.status === "AUDIT_WAIT" ? false : true
                    }
                    if(detail.lastExamCertificateUrl) {
                        this.uploadCertificate = [{ url: detail.lastExamCertificateUrl }]
                    }
                    if(detail.lastMusicTheoryCertificateUrl) {
                        this.uploadCertificate2 = [{ url: detail.lastMusicTheoryCertificateUrl }]
                    }

                    const songJson = detail.songJson ? JSON.parse(detail.songJson) : []
                    songJson.forEach(item => {
                        // 曲谱
                        const uploadUrl = item.uploadUrl ? item.uploadUrl.split(',') : []
                        let tempUrl = []
                        uploadUrl.forEach(url => {
                            tempUrl.push({
                                url: url
                            })
                        })
                        if(item.type === "PRACTICE") {
                            this.practiceUpload.push(tempUrl)
                            this.practiceUploadTemp.push(tempUrl)
                            this.practiceInfo.push(item)
                        } else if(item.type === "PERFORM") {
                            this.performUpload.push(tempUrl)
                            this.performUploadTemp.push(tempUrl)
                            this.performInfo.push(item)
                        }
                    })
                    this.practiceInfo.forEach((item, index) => {
                        item.index = index
                    })
                    this.performInfo.forEach((item, index) => {
                        item.index = index
                    })
                    this.practiceNum = this.practiceUpload.length
                    this.performNum = this.performUpload.length
                }
            } catch(err) {
                //
                setLoading(false)
            }
        },
        onOpen(type, index) {
            let songUpload = this.songUpload
            let practiceSUL = this.practiceInfo[index]
            let performSUL = this.performInfo[index]
            const practiceSongIdList = this.form.practiceSongIdList
            const performSongIdList = this.form.performSongIdList
            if(type == "perform") {
                if(performSongIdList) {
                    return
                }
                songUpload.songName = performSUL ? performSUL.songName : null
                songUpload.songAuthor = performSUL ? performSUL.songAuthor : null
            } else if(type == "practice") {
                if(practiceSongIdList) { // 判断是否是自定义
                    return
                }
                songUpload.songName = practiceSUL ? practiceSUL.songName : null
                songUpload.songAuthor = practiceSUL ? practiceSUL.songAuthor : null
            }
            songUpload.indexName = type
            songUpload.index = index
            songUpload.songStatus = true
        },
        beforeRead(file) {
            const isLt2M = file.size / 1024 / 1024 < 5

            if (!isLt2M) {
                this.$toast('上传图片大小不能超过 5MB')
                return false
            }
            return true
            // return new Promise((resolve) => {
            //     fileUtil.getOrientation(file).then((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)
            //         }
            //     })
            // })
        },
        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] == 'practice') {
                        file.url = result.data.url
                    } else if(obj[0] == 'perform') {
                        file.url = result.data.url
                    }
                } else {
                    file.status = 'failed'
                    file.message = '上传失败'
                    this.$toast(result.msg)
                    return false
                }
            } catch (err) {
                return false
            }
        },
        async onSubmit() {
            if(!this.onCheckFields()) {
                return
            }

            let songJson = [] // json 数组
            // 练习课 "PRACTICE"
            const practiceUpload = this.practiceUpload
            this.practiceInfo.forEach(item => {
                let tempUrl = []
                practiceUpload[item.index].forEach(item => {
                    tempUrl.push(item.url)
                })
                songJson.push({
                    songName: item.songName,
                    songAuthor: item.songAuthor,
                    index: item.index,
                    type: "PRACTICE",
                    uploadUrl: tempUrl.join(',')
                })
            })
            // 演奏课 "PERFORM"
            const performUpload = this.performUpload
            this.performInfo.forEach(item => {
                let tempUrl = []
                performUpload[item.index].forEach(item => {
                    tempUrl.push(item.url)
                })
                songJson.push({
                    songName: item.songName,
                    songAuthor: item.songAuthor,
                    index: item.index,
                    type: "PERFORM",
                    uploadUrl: tempUrl.join(',')
                })
            })
            let form = this.form
            let params = {
                id: form.id,
                lastExamCertificateUrl: form.lastExamCertificateUrl,
                lastMusicTheoryCertificateUrl: form.lastMusicTheoryCertificateUrl,
                songJson: JSON.stringify(songJson),
                status: "AUDIT_WAIT"
            }
            setLoading(true)
            try {
                const res = await examRegistrationUpdate(params)
                setLoading(false)
                const result = res.data
                if(result.code == 200) {
                    this.practiceUpload = []
                    this.practiceUploadTemp = []
                    this.practiceInfo = []
                    this.performUpload = []
                    this.performUploadTemp = []
                    this.performInfo = []
                    this.__init()
                } else {
                    this.$toast(result.msg)
                }
            } catch(err) {
                //
                setLoading(false)
            }
        },
        onCheckFields() {
            // 校验数据
            let form = this.form
            // 有值说明是列表
            if(this.practiceUpload.length != this.practiceNum) {
                this.$toast('请上传练习曲')
                return false
            }

            if(this.performUpload.length != this.performNum) {
                this.$toast('请上传演奏曲')
                return false
            }

            if(form.level > 2 && form.examMusicTheoryLevel == 0 && !form.lastMusicTheoryCertificateUrl) {
                this.$toast("请上传乐理证书")
                return false
            }
            return true
        },
        onSaveCancel() {
            this.songUpload.songStatus = false
            this.performUpload = JSON.parse(JSON.stringify(this.performUploadTemp)) // 回填数据
            this.practiceUpload = JSON.parse(JSON.stringify(this.practiceUploadTemp)) // 回填数据
        },
        onSaveUpload() {
            let songUpload = this.songUpload
            if(!songUpload.songName) {
                this.$toast("请输入曲名")
                return
            }
            if(songUpload.indexName == "practice") {
                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.practiceInfo[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 == "perform") {
                const performObj = this.performUpload[songUpload.index]
                const performLength = performObj ? performObj.length : 0
                if(performObj && performLength > 0) {
                    if(performObj[performLength - 1].url) {
                        this.performInfo[songUpload.index] = JSON.parse(JSON.stringify(songUpload))
                        this.performUploadTemp = JSON.parse(JSON.stringify(this.performUpload))
                    } else {
                        this.$toast("上传曲谱中，请稍等")
                        return
                    }
                } else {
                    this.$toast("请上传文件")
                    return
                }
            }
            songUpload.songName = null
            songUpload.songAuthor = null
            songUpload.songStatus = false
        },
        numberToCN (value) {
            const tempNumber = {
                0: '一',
                1: '二',
                2: '三',
                3: '四',
                4: '五',
                5: '六',
                6: '七',
                7: '八',
                8: '九',
                9: '十'
            }
            return tempNumber[value]
        }
    },
    filters: {
        filterStatus(value) {
            const template = {
                PAY_WAIT: '未缴费',
                AUDIT_WAIT: '等待审核',
                AUDIT_PASS: '通过',
                AUDIT_REJECT: '拒绝',
                REFUNDED: '已退款'
            }
            return template[value]
        }
    }
}
</script>
<style lang="less" scoped>
@import url("../../assets/commonLess/variable");
.appDetail {
    min-height: 100vh;
    overflow: hidden;
}
/deep/.van-cell {
    padding: 14px 16px;
    font-size: 16px;
    // color: @--font-main-color;
    .van-cell__title {
        margin-right: 12px;
    }
    .van-cell__value {
        width: calc(40% - .2rem);
        padding-right: .2rem;
        text-align: left;
        flex: auto;
        color: @--font-second-color;
    }
    .van-cell__right-icon {
        position: absolute;
        right: 16px;
    }
    .payTime {
        color: @--red-color;
    }
    &.van-field--disabled .van-field__label {
        color: @--font-main-color;
    }
    .van-field__control:disabled {
        color: @--font-second-color;
    }
    .noPass {
        color: @--red-color;
        .van-field__control:disabled {
            color: @--red-color;
        }
    }
    .pass {
        color: @--main-color;
        .van-field__control:disabled {
            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 {
        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;
        }
    }
}

.section {
    margin-top: 10px;
}
.memos {
    margin-top: 20px;
    margin-bottom: 20px;
    & + .van-button {
        margin-top: 0;
    }
}
.van-button--primary {
    margin: .15rem 0 .2rem;
    background-color: @--main-color;
    border: 1px solid @--main-color;
    color: #FFFFFF;
    font-size: .18rem;
    height: .5rem;
    line-height: .52rem;
    width: 90%;
    margin-left: 5%;
}
</style>