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

        <div class="title">基本信息</div>
        <van-field v-model="form.idCardNo" @blur="onCardNo" required name="idCardNo" label="身份证号" placeholder="请输入身份证号" >
            <template #button>
                <div class="cropper">
                    <!-- <van-icon name="scan" /> -->
                    <i class="icon-scan"></i>
                    <h5-cropper
                        @getFile="getFile"
                        :option="option"
                    ></h5-cropper>
                </div>
            </template>
        </van-field>
        <van-field required v-model="form.realName" name="realName" label="姓名" placeholder="请输入姓名" />

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

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

        <van-field required readonly name="nation" v-model="form.nation" @click="nationStatus = true" is-link label="民族" placeholder="请输入民族" />

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

        <div class="upload-img">
            <div class="cropper2">
                <van-image
                    width="100%"
                    height="100%"
                    :src="form.certificatePhoto"
                >
                    <template #loading>
                        <div class="upload-container">
                            <i class="icon-upload-add"></i>
                            <p>点击上传</p>
                        </div>
                    </template>
                    <template #error>
                        <div class="upload-container">
                            <i class="icon-upload-add"></i>
                            <p>点击上传</p>
                        </div>
                    </template>
                </van-image>
                <h5-cropper
                    @getFile="getFilePhoto"
                    :option="option2"
                ></h5-cropper>
            </div>
            <p class="upload-tips">须使用免冠证件照，纯底色<br/>（纯白、纯蓝或纯红）<br/>（图像预览可能会异常）</p>
        </div>

        <m-button class="step-btn" @click="onSubmit" text="下一步" />

        <van-popup v-model="birthdateShow" position="bottom">
            <van-datetime-picker
            v-model="currentDate"
            type="date"
            :min-date="minDate"
            :max-date="maxDate"
            :formatter="formatter"
            @cancel="birthdateShow = false"
            @confirm="onConfirm"
            />
        </van-popup>

        <van-popup v-model="nationStatus" position="bottom">
            <van-picker
                show-toolbar
                :columns="nationList"
                @confirm="onConfirmNation"
                @cancel="nationStatus = false"
                />
        </van-popup>
    </div>
</template>
<script>
import MStep from '@/components/MStep'
import MButton from '@/components/MButton'
import setLoading from '@/utils/loading'
import H5Cropper from 'vue-cropper-h5'
import { getStudent, ocr, uploadFile, updateStudentInfo, getExamIngOrder, closeOrder } from './SignUpApi'
import { validateCardNo } from '@/utils/validateRules'
import dayjs from 'dayjs'
const nation = ["汉族", "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "朝鲜族", "满族", "侗族", "瑶族", "白族", "土家族", "哈尼族", "哈萨克族", "傣族", "黎族", "僳僳族", "佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族", "土族", "达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族", "塔吉克族", "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族", "德昂族", "保安族", "裕固族", "京族", "塔塔尔族", "独龙族", "鄂伦春族" ,"赫哲族", "门巴族", "珞巴族", "基诺族"]

export default {
    name: 'signupBaseInfo',
	components: { MStep, MButton, H5Cropper },
    data () {
        const examId = localStorage.getItem('examId')
        return {
            birthdateShow: false,
            nationStatus: false,
            nationList: nation,
            examId: examId,
            certificatePhoto: [],
            minDate: new Date(1940, 0, 1),
            maxDate: new Date(),
            currentDate: new Date(),
            form: {
                idCardNo: null,
                realName: null,
                gender: 1,
                birthdate: null,
                nation: null,
                certificatePhoto: null
            },
            fileList: [],
            option: {
                canScale: true,
                fixedNumber: [3, 2],
                img: '',
                size: 1,
                info: true,
                full: false,
                canMove: true,
                fixedBox: false,
                original: false,
                canMoveBox: true,
                autoCrop: true,
                centerBox: false,
                high: true,
                ceilbutton: true
            }, //配置
            option2: {
                canScale: true,
                fixedNumber: [5, 7],
                img: '',
                size: 1,
                info: true,
                full: false,
                canMove: true,
                fixedBox: false,
                original: false,
                canMoveBox: true,
                autoCrop: true,
                centerBox: false,
                high: true,
                ceilbutton: true
            }, //配置
            photoUrl: null
            // "https://img.yzcdn.cn/vant/cat.jpeg"
        }
    },
    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: {
        formatter(type, val) {
            if (type === 'year') {
                return `${val}年`;
            } else if (type === 'month') {
                return `${val}月`;
            } else if (type === 'day') {
                return `${val}日`;
            }
            return val;
        },
        onCardNo() {
            let form = this.form
            if(form.idCardNo.length >= 15) { // 大于15位说明是大陆身份证
                // 身份证号检验
                if(!validateCardNo(form.idCardNo)) {
                    this.$toast('输入身份证号有误')
                    return
                }
                let birthday = this.getBirth(form.idCardNo)
                let sex = this.getSex(form.idCardNo)
                form.gender = sex
                form.birthdate = birthday
            }
        },
        getBirth(idCard) {
            let birthday = "";
            if(idCard != null && idCard != ""){
                if(idCard.length == 15){
                    birthday = "19"+idCard.slice(6,12);
                } else if(idCard.length == 18){
                    birthday = idCard.slice(6,14);
                }
                birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
                //通过正则表达式来指定输出格式为:1990-01-01
            }
            return birthday;
        },
        getSex(idCard) {
            let sex = null;
            if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
                sex = 1;
            } else {
                sex = 0;
            }
            return sex;
        },
        onConfirm(value) {
            this.form.birthdate = dayjs(value).format('YYYY-MM-DD')
            this.birthdateShow = false
        },
        onConfirmNation(value) {
            this.form.nation = value
            this.nationStatus = false
        },
        onChangeDate() {
            this.birthdateShow = true
            if(this.form.birthdate) {
                this.currentDate = new Date(dayjs(this.form.birthdate))
            }
        },
        async getFile(file) {
            setLoading(true)
            try {
                let formData = new FormData()
                formData.append('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) {
                setLoading(false)
                return false
            }
        },
        async getFilePhoto(file) {
            setLoading(true)
            try {
                let formData = new FormData()
                formData.append('file', file)
                formData.append('idCardSide', "front")
                let res = await uploadFile(formData)
                let result = res.data
                setLoading(false)
                if(result.code == 200) {
                    this.form.certificatePhoto = result.data.url
                } else {
                    this.$toast(result.msg)
                    return false
                }
            } catch (err) {
                setLoading(false)
                return false
            }
        },
        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(() => {
                        const orderNo = resultOrder.data.orderNo
                        this.$dialog.close()
                        if(!orderNo) {
                            return
                        }
                        this.onCloseOrder(orderNo)
                    })
                }
            } catch(err) {
                //
            }
            setLoading(false)
        },
        async onCloseOrder(orderNo) {
            setLoading(true)
            await closeOrder({ orderNo: orderNo })
            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) {
                    // localStorage.setItem("studentName", this.form.realName)
                    this.$router.push({
                        path: '/signUpLevel'
                    })
                } else {
                    this.$toast(result.msg)
                }
            } catch(err) {
                //
            }
        },
        onCheckFields() { // 校验字段
            let form = this.form
            if(!form.idCardNo) {
                this.$toast("请输入身份证号")
                return false
            } else if(form.idCardNo.length >= 15 && !validateCardNo(form.idCardNo)) {
                this.$toast("输入身份证号有误")
                return false
            } else if(!form.realName) {
                this.$toast("请输入姓名")
                return false
            } else if(!form.birthdate) {
                this.$toast("请选择生日")
                return false
            } else if(!form.nation) {
                this.$toast("请输入民族")
                return false
            } else if(!form.certificatePhoto) {
                this.$toast('请上传证件照片')
                return false
            }
            return true
        },
        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,
                        certificatePhoto: this.form.certificatePhoto
                    }
                    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)
        }
    },
    destroyed() {
		this.$toast.clear()
        this.$dialog.close()
	}
}
</script>
<style lang="less" scoped>
@import url("../../assets/commonLess/variable");
.cropper {
    width: 30px;
    /* 切记position: relative一定要有 */
    position: relative;
    overflow: hidden;
    text-align: center;
    span, .icon-scan {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        color: @--main-color;
    }
    .icon-scan {
        display: inline-block;
        width: 0.24rem;
        height: .22rem;
        background: url('../../assets/images/level/scan_icon.png') no-repeat center;
        background-size: contain;
        text-align: right;
    }

    .upbtn {
        height: 24px;
    }
}
.cropper2 {
    /* 切记position: relative一定要有 */
    position: relative;
    overflow: hidden;
    text-align: center;
    height: 1.4rem;
    /deep/.van-image {
        position: absolute;
        left: 0;
        top: 0;
        color: @--main-color;
    }
    /deep/.van-image__img {
        width: 1rem;
        height: 1.4rem;
        margin: 0 auto;
    }
    .upbtn {
        height: 1.4rem;
        width: 1rem;
        margin: auto;
    }
    /deep/.van-image__error, /deep/.van-image__loading {
        width: 1rem;
        left: 50%;
        margin-left: -.5rem;
    }
}
.img {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
}
.signupBaseInfo {
    min-height: 100vh;
    overflow-y: auto;
    overflow-x: hidden;
    background-color: @--main-bg-color;
    .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: 1rem;
    }
    /deep/.van-field__body {
        font-size: .16rem
    }

    .codeText {
        font-size: .16rem;
        color: @--main-color;
    }
}
.upload-img {
    background: #ffffff;
    text-align: center;
    padding: .3rem 0 .2rem;
    .van-uploader__wrapper {
        &:active {
            .icon-upload-add {
                display: inline-block;
                width: .55rem;
                height: .55rem;
                background: url('../../assets/images/level/icon_upload_add_active.png') no-repeat center;
                background-size: contain;
            }
            // p {

            // }
        }
    }
    .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: @--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: @--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-icon {
    background-color: #F5F5F5;
}
/deep/.van-radio__icon--disabled.van-radio__icon--checked .van-icon, /deep/.van-radio__icon--checked .van-icon {
    background-color: @--main-color;
    border-color: @--main-color;
    color: #ffffff;
}
</style>