<template>
<div :class="mobile ? 'mobileMain' : ''" :style="{
      marginTop: mainMarginTop,
      marginBottom: mobile ? '0px' : '30px !important'
    }">
    <div class="name-cert-container" v-if="!mobile">
        <!-- 待实名 -->
        <div class="name-cert-main">
            <div class="name-cert-title-area">
                <img class="name-cert-icon" :src="icon" />
                <h6 class="name-cert-title">实名认证</h6>
                <p class="name-cert-tips">请如实填写信息，客栈承诺保障用户的信息安</p>
            </div>
            <el-form ref="modalForm" :model="modalFormData" :rules="rules" size="medium" label-width="100px">
                <div class="name-cert-label">姓名</div>
                <el-form-item label-width="0" prop="cert_name">
                    <el-input v-model="modalFormData.cert_name" placeholder="请输入真实姓名" clearable :style="{ width: '100%' }">
                    </el-input>
                </el-form-item>
                <div class="name-cert-label">证件类型</div>
                <el-form-item label-width="0" prop="cert_type">
                    <el-select v-model="modalFormData.cert_type" placeholder="请选择证件类型" clearable :style="{ width: '100%' }">
                        <el-option v-for="(item, index) in cert_typeOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                    </el-select>
                </el-form-item>
                <div class="name-cert-label">证件号</div>
                <el-form-item label-width="0" prop="cert_no">
                    <el-input v-model="modalFormData.cert_no" placeholder="请输入证件号" clearable :style="{ width: '100%' }">
                    </el-input>
                </el-form-item>
                <div class="upload-main">
                    <el-upload class="upload-box" action="#" :show-file-list="false" :multiple="false" accept="image/png, image/jpeg" :before-upload="file => handleFileChange(file,'z_file')">

                        <div class="upload-img" v-if="z_file" @click.stop="handleDeleteFile('z_file')">
                            <i class="el-icon-delete avatar-uploader-icon"></i>
                            <img :src="z_file" class="avatar" />
                        </div>
                        <div v-else class="upload-area z_file">
                            <p>+点击上传正面</p>
                            <div class="upload-"></div>
                        </div>

                    </el-upload>

                    <el-upload class="upload-box" action="#" :show-file-list="false" :multiple="false" accept="image/png, image/jpeg" :before-upload="file => handleFileChange(file,'f_file')">
                        <div class="upload-img" v-if="f_file" @click.stop="handleDeleteFile('f_file')">
                            <i class="el-icon-delete avatar-uploader-icon"></i>
                            <img :src="f_file" class="avatar" />
                        </div>
                        <div v-else class="upload-area f_file">
                            <p>+点击上传反面</p>
                        </div>
                    </el-upload>
                </div>

                <div class="name-cert-submit">
                    <el-button type="primary" class="cert-btn" size="medium" @click="submitForm">实名认证</el-button>
                </div>
            </el-form>
        </div>
    </div>

    <el-dialog title="温馨提示" :visible.sync="centerDialogVisible" width="350px" center>
        <p class="qrcode-tips">请打开支付宝扫码以下二维码</p>
        <div class="qrcode-img">
            <img :src="qrcodeBase64" />
        </div>
    </el-dialog>
</div>
</template>

<script>
import {
    mapState
} from "vuex";
import qs from "qs";
import icon from "@/assets/img/account/certicon@3x.png";
import iconSuccess from "@/assets/img/account/cert_success_icon@3x.png";
import iconFail from "@/assets/img/account/cert_fail_icon@3x.png";
import QRCode from "qrcode";
import uploader from "@/components/uploader";

export default {
    name: "SeoLearnList",
    components: {
        uploader
    },
    data() {
        return {
            diploma_photo: "",
            baseUrl: "",
            mobile: false,
            isWeixinApp: true,
            icon,
            iconSuccess,
            iconFail,

            centerDialogVisible: false,
            url: "",
            certifyId: "",

            qrcodeBase64: "",
            timer: null,
            // normal 待实名   success 认证成功   fail 认证失败
            state: "normal",
            init: false,

            modalFormData: {
                cert_name: "",
                cert_type: 1,
                cert_no: ""
            },
            z_file: "",
            f_file: "",
            rules: {
                cert_name: [{
                    required: true,
                    message: "请输入真实姓名",
                    trigger: "blur"
                }],
                cert_type: [{
                    required: true,
                    message: "请选择证件类型",
                    trigger: "change"
                }],
                cert_no: [{
                    required: true,
                    message: "请输入证件号",
                    trigger: "blur"
                }]
            },
            cert_typeOptions: [{
                    label: "身份证",
                    value: 1
                },
                {
                    label: "港澳通行证",
                    value: 2
                },
                {
                    label: "台湾通行证",
                    value: 3
                },
                {
                    label: "港澳居住证",
                    value: 4
                },
                {
                    label: "台湾身份证",
                    value: 5
                }
            ]
        };
    },
    head() {
        const {
            title = "实名认证",
                keyword = "",
                description = "",
                h1 = "",
                canonical = "",
                metaLocation
        } = this.head || {};
        let obj = {
            title: title,
            meta: [{
                    name: "keywords",
                    content: keyword
                },
                {
                    name: "description",
                    content: description
                },
                {
                    name: "h1",
                    content: h1
                }
            ],
            link: [{
                rel: "canonical",
                href: canonical
            }]
        };
        if (metaLocation) {
            obj.meta.push({
                name: "location",
                content: metaLocation
            });
        }
        return obj;
    },
    computed: {
        ...mapState(["deviceType"]),
        showWxHeader() {
            return (
                !this.deviceType.app &&
                !this.isWeixinApp &&
                (this.deviceType.android || this.deviceType.ios)
            );
        },
        mainMarginTop() {
            if (this.mobile && this.showWxHeader) {
                return "64px !important";
            } else if (this.mobile) {
                return "0px !important";
            } else {
                return "20px !important";
            }
        },
        userInfo() {
            return this.$store.state.userinfo;
        }
    },

    mounted() {
        this.checkLogin(true);
        this.home_page_type = this.userInfo.home_page_type;
        this.baseUrl = this.$store.state.domainConfig.siteUrl;
        this.isWeixinApp = navigator.userAgent.indexOf("miniProgram") > -1;

        this.checkNameIsCerted();
        document.body.style.background = "#fff";
    },
    methods: {
        handleDeleteFile(type) {
            if (type == 'z_file') {
                this.z_file = ""
            }
            if (type == 'f_file') {
                this.f_file = ""
            }
        },
        handleFileChange(file, type) {

            if (this.limitFileSize && this.limitFileSize > 0) {
                if (file.size / (1024 * 1024) > this.limitFileSize) {
                    this.$message.error(`图片大小不得超过${this.limitFileSize}M，请重新选择`);
                    return false;
                }
            } else if (file.size / 1024 > 2048) {
                this.$message.error("图片大小不得超过2M，请重新选择");
                return false;
            }
            const formData = new FormData();
            formData.append("file", file);
            formData.append("original_filename", file.name);
            this.uploading = true;
            this.$axios
                .$post(`/upload_image`, formData, {
                    headers: {
                        "Content-Type": "multipart/form-data"
                    }
                })
                .then(res => {
                    this.$emit("change", res.filename);
                    if (type == 'z_file') {
                        this.z_file = res.filename
                    }
                    if (type == 'f_file') {
                        this.f_file = res.filename
                    }

                })
                .finally(() => {
                    this.uploading = false;
                });
            return false
        },
        submitForm() {
            this.$refs["modalForm"].validate(valid => {
                if (!valid) return;

                if (!this.z_file) {
                    this.$message.error("请上传证件正面")
                    return
                }
                if (!this.f_file) {
                    this.$message.error("请上传证件反面")
                    return
                }
                this.submit();
                // TODO 提交表单
            });
        },
        resetForm() {
            this.$refs["modalForm"].resetFields();
        },
        async submit() {
            const {
                cert_name,
                cert_no,
                cert_type
            } = this.modalFormData;
            // 测试用
            // let res = {
            //     status:1,
            //     data: {
            //         url: "http://www.baidu.com",
            //         certifyId: "123123"
            //     }
            // }
            let res = await this.$axios.$post("/uapi/user/realName/create", {
                cert_name,
                cert_no,
                cert_type,
                z_file:this.z_file,
                f_file:this.f_file,
                is_face_check:0,
                from_type: 1
            });

            if (Number(res.status) !== 1) {
                this.$message.error(res.info);
                return;
            }

            const {
                kezhan_url,
                certifyId,
                cert_status,
                zfb_url,
                certify_type
            } = res.data;

            if(cert_status==3)
            {
              this.toSuccess();
              return ;
            }

            if(certify_type==2)
            {
              this.url = kezhan_url;
              this.certifyId = certifyId;
              this.centerDialogVisible = true;
              this.createQrCode();
              this.startTimer();
            }
        },
        createQrCode() {
            this.$nextTick(() => {
                const text = this.url;
                let that = this;
                QRCode.toDataURL(
                    text, {
                        errorCorrectionLevel: "H",
                        margin: 1,
                        width: 300
                    },
                    function (err, url) {
                        that.qrcodeBase64 = url;
                    }
                );
            });
        },
        startTimer() {
            // 启动定时器查询
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
            }

            this.timer = setInterval(async () => {
                let res = await this.$axios.$post("/uapi/user/realName/check", {});
                if (Number(res.status) !== 1) {
                    this.$message.error(res.info);
                    return;
                }
                let {
                    type
                } = res.data.type;
                if (type == 1 || type == 4) {
                    // 关闭弹层
                    this.centerDialogVisible = false;
                    clearInterval(this.timer);
                    this.timer = null;

                    if (type == 1) {
                        // 显示成功态
                        this.toSuccess();
                    } else if (type == 4) {
                        // 显示失败态
                        this.toFail();
                    }
                }
            }, 5000);
        },
        checkNameIsCerted() {
            if (this.userInfo && this.userInfo.realname_verify_status == 2) {
                this.toSuccess()
            }
        },
        toSuccess() {
            location.href = "/frontend/name_cert_success";
        },
        toFail() {
            location.href = "/frontend/name_cert_fail";
        }
    }
};
</script>

<style lang="scss">
@import "@/assets/css/name_cert/name_cert.scss";
</style>
