<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="缴费状态">
                <p class="noPass" v-if="form.status === 'PAY_WAIT'">未缴费</p>
                <p class="pass" v-else>已缴费</p>
            </van-cell>
            <van-field v-model="form.examStartTime" disabled label="考试日期" />
            <van-cell title="专业等级" >
                {{ form.subjectName }}({{ form.level | formatLevel }})
            </van-cell>
            <van-cell v-for="(item, index) in performInfo" :key="index" :title="`练习曲${numberToCN(index)}`" @click="onOpen('perform', index)" is-link >
                {{ item.songName }} {{ item.songAuthor ? '-' + item.songAuthor : item.songAuthor }}
            </van-cell>
            <van-cell v-for="(item, index) in practiceInfo" :key="index" :title="`演奏曲${numberToCN(index)}`" @click="onOpen('practice', index)" is-link >
                {{ item.songName }} {{ item.songAuthor ? '-' + item.songAuthor : item.songAuthor }}
            </van-cell>
            <!-- <van-cell title="练习曲" is-link />
            <van-cell title="演奏曲" is-link />
            <van-cell title="演奏曲" is-link /> -->
            <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
                        :deletable="false"
                        v-model="uploadCertificate"
                        :max-count="1" />
                </template>
            </van-field>
            <van-cell disabled title="乐理等级" >
                {{ form.lastMusicTheoryLevel | 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/*"
                        :max-count="1" />
                </template>
            </van-field>
            <!-- disabled
                        :deletable="false" -->
        </van-cell-group>

        <van-cell-group style="margin-top: 20px">
            <van-cell disabled title="报名审核" >
                <p class="pass" v-if="form.status === 'AUDIT_PASS'">已通过</p>
                <p class="noPass" v-else>未通过</p>
            </van-cell>
            <van-cell title="备注" >
                {{ form.memo }}
            </van-cell>
        </van-cell-group>
        <van-button type="primary" 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.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 == 'practice'"
                        :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 == 'perform'"
                        :name="songUpload.indexName + '-' + songUpload.index"
                        :before-read="beforeRead"
                        :before-delete="beforeDelete"
                        :after-read="afterRead"
                        v-model.trim="performUpload[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">确定</span>
                </div>
            </div>
        </van-popup>
    </div>
</template>
<script>
import MHeader from '@/components/MHeader'
import { browser } from '@/utils/common'
import dayjs from 'dayjs'
import setLoading from '@/utils/loading'
import fileUtil from '@/utils/fileUtil'
import { uploadFile } from '../signup/SignUpApi'
import { applyList } from './appApi'
export default {
    name: 'appDetail',
	components: { MHeader },
    data () {
        const query = this.$route.query
        return {
            headerStatus: false,
            examRegistrationId: query.examRegistrationId,
            form: {
                paymentOrderNo: null,
                examBaseName: null,
                subjectName: null,
                level: null,
                status: null,
                examStartTime: null,
                lastExamCertificateUrl: null,
                lastMusicTheoryLevel: null,
                lastMusicTheoryCertificateUrl: null,
                memo: null
            },
            uploadCertificate: [],
            uploadCertificate2: [],
            songUpload: {
                songStatus: false, // 曲目状态
                indexName: null,
                index: null, // 索引
                name: null, // 曲名
                author: null // 作者
            },
            performUpload: [], // 演奏曲
            performInfo: [], // 演奏曲基本信息
            practiceUpload: [], // 练习曲
            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
                })
                const result = res.data
                if(result.code == 200) {
                    const detail = result.data.rows ? result.data.rows[0] : {}
                    // console.log(detail)
                    this.form = {
                        paymentOrderNo: detail.paymentOrderNo,
                        examBaseName: detail.examBaseName,
                        subjectName: detail.subjectName,
                        level: detail.level,
                        status: detail.status,
                        examStartTime: detail.examStartTime,
                        lastExamCertificateUrl: detail.lastExamCertificateUrl,
                        lastMusicTheoryLevel: detail.lastMusicTheoryLevel,
                        lastMusicTheoryCertificateUrl: detail.lastMusicTheoryCertificateUrl,
                        memo: detail.memo
                    }
                    if(detail.lastExamCertificateUrl) {
                        this.uploadCertificate = [{ url: detail.lastExamCertificateUrl }]
                    }
                    if(detail.lastMusicTheoryCertificateUrl) {
                        this.uploadCertificate2 = [{ url: detail.lastMusicTheoryCertificateUrl }]
                    }

                    const songJson = detail.songJson ? JSON.parse(detail.songJson) : []
                    console.log(songJson)
                    songJson.forEach(item => {
                        // 曲谱
                        const uploadUrl = item.uploadUrl.split(',')
                        let tempUrl = []
                        uploadUrl.forEach(url => {
                            tempUrl.push({
                                url: url
                            })
                        })
                        if(item.type === "PRACTICE") {
                            this.practiceUpload.push(tempUrl)
                            this.practiceInfo.push(item)
                        } else if(item.type === "PERFORM") {
                            this.performUpload.push(tempUrl)
                            this.performInfo.push(item)
                        }
                    })

                    console.log({
                        practiceInfo: this.practiceInfo,
                        practiceUpload: this.practiceUpload,
                        performInfo: this.performInfo,
                        performUpload: this.performUpload
                    })
                }
                // examRegistrationId
            }catch(err) {
                //
            }
            setLoading(false)
        },
        onOpen(type, index) {
            let songUpload = this.songUpload
            songUpload.indexName = type
            songUpload.index = index
            let practiceSUL = this.practiceInfo[index]
            let performSUL = this.performInfo[index]
            if(type == "perform") {
                songUpload.name = performSUL ? performSUL.songName : null
                songUpload.author = performSUL ? performSUL.songAuthor : null
            } else if(type == "practice") {
                songUpload.name = practiceSUL ? practiceSUL.songName : null
                songUpload.author = practiceSUL ? practiceSUL.songAuthor : null
            }
            songUpload.songStatus = true
        },
        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) => {
                    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] == '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
            }
        },
        onSaveCancel() {
            this.songUpload.songStatus = false
        },
        numberToCN (value) {
            const tempNumber = {
                0: '一',
                1: '二',
                2: '三',
                3: '四',
                4: '五',
            }
            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: 40%;
        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;
}
.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>