<template>
    <div class="signupBaseInfo">
        <m-header />
        <m-step :number="2" />

        <!-- <van-form ref="form" :show-error="false" validate-first @submit="onSubmit" @failed="onFailed"> -->
        <div class="title">基本信息</div>
        <van-field v-model="form.idCardNo" readonly required name="idCardNo" label="身份证号" placeholder="请输入身份证号" >
            <template #button>
                <!-- <span class="codeText">上传</span> -->
                <van-uploader :before-read="beforeRead"
                                :after-read="afterReadOCR"
                                accept="image/*"
                                :max-count="1">
                    <span class="codeText">上传</span>
                </van-uploader>
            </template>
        </van-field>
        <!-- <div class="cardTips">如有括号，请用英文括号()</div> -->
        <van-field readonly required v-model="form.realName" name="realName" label="姓名" placeholder="请输入姓名" />

        <van-field name="radio" required label="性别">
            <template #input>
                <van-radio-group v-model="form.gender" direction="horizontal">
                    <van-radio disabled checked-color="var(--main-color)" :name="1">男</van-radio>
                    <van-radio disabled checked-color="var(--main-color)" :name="0">女</van-radio>
                </van-radio-group>
            </template>
        </van-field>

        <van-field readonly required name="birthdate" v-model="form.birthdate" label="生日" placeholder="请选择" />

        <van-field readonly required name="nation" v-model="form.nation" label="民族" placeholder="请选择" />

        <div class="title">证件照上传</div>

        <div class="upload-img">
            <van-uploader v-model="certificatePhoto" :before-read="beforeRead"
                                :before-delete="beforeDelete"
                                :after-read="afterRead"
                                accept="image/*"
                                :max-count="1">
                <div class="upload-container">
                    <i class="icon-upload-add"></i>
                    <p>点击上传</p>
                </div>
            </van-uploader>
            <p class="upload-tips">须使用免冠证件照，纯底色<br/>（纯白、纯蓝或纯红）<br/>（图像预览可能会异常）</p>
        </div>

        <m-button class="step-btn" @click="onSubmit" text="下一步" />
        <!-- </van-form> -->
    </div>
</template>
<script>
import MHeader from '@/components/MHeader'
import MStep from '@/components/MStep'
import MButton from '@/components/MButton'
import setLoading from '@/utils/loading'
import { getStudent, ocr, uploadFile, updateStudentInfo, getExamIngOrder } from './SignUpApi'
import dayjs from 'dayjs'
export default {
    name: 'signupBaseInfo',
	components: { MHeader, MStep, MButton },
    data () {
        const examId = localStorage.getItem('examId')
        return {
            examId: examId,
            certificatePhoto: [],
            form: {
                idCardNo: null,
                realName: null,
                gender: 1,
                birthdate: null,
                nation: null,
                certificatePhoto: null
            },
            fileList: [],
        }
    },
    mounted() {
        localStorage.removeItem("examRegistrationParams")
        // 插入token
        // let params = this.$route.query
        // if(params.Authorization) {
        //     localStorage.setItem('Authorization', decodeURI(params.Authorization))
        //     localStorage.setItem('userInfo', decodeURI(params.Authorization))
        // }
        this.__init()
    },
    methods: {
        async __init() {
            setLoading(true)
            try {
                const res = await getStudent()
                if(res.data.code == 200) {
                    const tempData = res.data.data
                    this.form = {
                        idCardNo: tempData.idCardNo,
                        realName: tempData.realName == tempData.phone ? null : tempData.realName,
                        gender: tempData.gender,
                        birthdate: tempData.birthdate ? dayjs(tempData.birthdate).format('YYYY-MM-DD') : null,
                        nation: tempData.nation,
                        certificatePhoto: tempData.certificatePhoto
                    }
                    if(tempData.certificatePhoto) { // 判断是否在头像
                        this.certificatePhoto = [{url: tempData.certificatePhoto}]
                    }
                }

                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(() => {
                        this.$dialog.close()
                    })
                }
            } catch(err) {
                //
            }
            setLoading(false)
        },
        async onSubmit() {
            if(!this.onCheckFields()) {
                return
            }
            setLoading(true)
            try {
                let res = await updateStudentInfo(this.form)
                setLoading(false)
                let result = res.data
                if(result.code == 200) {
                    this.$router.push({
                        path: '/signUpLevel',
                        query: {
                            studentName: this.form.realName
                        }
                    })
                } else {
                    this.$toast(result.msg)
                }
            } catch(err) {
                //
            }
            // this.$router.push({
            //     path: '/signUpLevel'
            // })
        },
        onCheckFields() { // 校验字段
            let form = this.form
            if(!form.idCardNo || !form.realName || !form.birthdate || !form.nation) {
                this.$toast('请上传身份证正面进行扫描')
                return false
            } else if(!form.certificatePhoto) {
                this.$toast('请上传证件照片')
                return false
            }
            return true
        },
        beforeRead(file) {
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!isLt2M) {
                this.$toast('上传证书大小不能超过 2MB')
                return false
            }
            return true
        },
        beforeDelete() {
            this.form.certificatePhoto = '' // 上传图片地址为空
            return true
        },
        async afterRead(file) { // 上传头像
            // setLoading(true)
            try {
                file.status = 'uploading'
                file.message = '上传中...'
                let formData = new FormData()
                formData.append('file', file.file)
                let res = await uploadFile(formData)
                let result = res.data
                // setLoading(false)
                if(result.code == 200) {
                    file.status = 'done'
                    this.form.certificatePhoto = result.data.url
                } else {
                    file.status = 'failed'
                    file.message = '上传失败'
                    this.$toast(result.msg)
                    return false
                }
            } catch (err) {
                return false
            }
        },
        async afterReadOCR(file) { // 上传身份证照片识别
            setLoading(true)
            try {
                let formData = new FormData()
                formData.append('file', file.file)
                formData.append('idCardSide', "front")
                let res = await ocr(formData)
                let result = res.data
                setLoading(false)
                if(result.code == 200) {
                    this.idCardParse(result.data)
                } else {
                    this.$toast(result.msg)
                    return false
                }
            } catch (err) {
                return false
            }
        },
        idCardParse(data) {
            // 身份证信息解析
            let wordsResult = data.words_result
            let errorText
            switch (data.image_status) {
                case "normal":
                    this.form = {
                        idCardNo: wordsResult["公民身份号码"].words,
                        realName: wordsResult["姓名"].words,
                        gender: wordsResult["性别"].words == '男' ? 1 : 0,
                        birthdate: dayjs(wordsResult["出生"].words).format('YYYY-MM-DD'),
                        nation: wordsResult["民族"].words
                    }
                    break;
                case "reversed_side":
                    errorText = "身份证正反面颠倒"
                    break;
                case "non_idcard":
                    errorText = "上传的图片中不包含身份证"
                    break;
                case "blurred":
                    errorText = "身份证模糊"
                    break;
                case "other_type_card":
                    errorText = "身份证关键字段反光或过曝"
                    break;
                case "over_dark":
                    errorText = "身份证欠曝（亮度过低）"
                    break;
                default:
                    errorText = "上传身份证有误"
                    break;
            }
            errorText && this.$toast(errorText)
        }
    }
}
</script>
<style lang="less" scoped>
.signupBaseInfo {
    height: 100vh;
    overflow-y: auto;
    overflow-x: hidden;
    background-color: var(--main-bg-color);
    .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);
    }
}

.upload-img {
    background: #ffffff;
    text-align: center;
    padding: .3rem 0 .2rem;
    .upload-container {
        width: 1rem;
        height: 1.4rem;
        background: url('../../assets/images/level/uploadBg.png') no-repeat center;
        background-size: contain;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
    .upload-tips {
        padding-top: .18rem;
        font-size: .14rem;
        color: var(--font-second-color);
    }
    .icon-upload-add {
        display: inline-block;
        width: .55rem;
        height: .55rem;
        background: url('../../assets/images/level/icon_upload_add.png') no-repeat center;
        background-size: contain;
    }
    p {
        margin-top: -.04rem;
        font-size: .16rem;
        color: var(--main-color);
    }
}
/deep/.van-uploader__preview {
    margin: 0;
}
/deep/.van-uploader__preview-image {
    width: 1rem;
    height: 1.4rem;
}
.cardTips {
    font-size: .14rem;
    color: #2DC7AA;
    padding-left: 1.28rem;
    padding-top: .03rem;
    padding-bottom: .15rem;
}

/deep/.van-radio__icon--disabled.van-radio__icon--checked .van-icon {
    background-color: var(--main-color);
    border-color: var(--main-color);
    color: #ffffff;
}
</style>