<template>
    <div class="personal">
        <h3>个人信息</h3>
        <p
            class="resubmit-notice clearfix"
            v-if="userInfo.loginInfo.certificationStatus ==
                        'FIRST_TRIAL_FAILURE'"
        >
            <span>*审核未通过的信息：</span>
            <br />
            <span>{{ jsRemark }}</span>
        </p>
        <el-select v-model="cardValue" placeholder="请选择证件类型" @change="selectCertificateType">
            <el-option
                v-for="item in cardOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
        </el-select>
        <label class="upload-notice" v-if="cardValue !== ''">
            <span>证件照片 （请确认信息无误，证件图片清晰可见，图片支持jpg、png、jpeg，文件不超过5MB）</span>
            <!-- <span>查看示例</span> -->
        </label>
        <div class="upload-box clearfix" v-if="cardValue == 2">
            <files-upload
                :uploadUrl="uploadUrl"
                :popoverImg="popoverImg"
                :imageUrl="imageUrl"
                :title="uploadTitle"
                v-loading="loading"
                @success="handleAvatarSuccess"
                @error="handleAvatarError"
                @before="beforeAvatarUpload"
            ></files-upload>
            <files-upload
                :uploadUrl="uploadUrl2"
                :popoverImg="popoverImg2"
                :imageUrl="imageUrl2"
                :title="uploadTitle2"
                v-loading="loading2"
                @success="handleAvatarSuccess2"
                @error="handleAvatarError2"
                @before="beforeAvatarUpload2"
            ></files-upload>
        </div>
        <div class="upload-box clearfix" v-else-if="cardValue == 1">
            <files-upload
                :uploadUrl="uploadUrl3"
                :popoverImg="popoverImg3"
                :imageUrl="imageUrl3"
                :title="uploadTitle3"
                v-loading="loading3"
                @success="handleAvatarSuccess3"
                @error="handleAvatarError3"
                @before="beforeAvatarUpload3"
            ></files-upload>
        </div>
        <div class="upload-box clearfix" v-else-if="cardValue == 3">
            <files-upload
                :uploadUrl="uploadUrl4"
                :popoverImg="popoverImg4"
                :imageUrl="imageUrl4"
                :title="uploadTitle4"
                v-loading="loading4"
                @success="handleAvatarSuccess4"
                @error="handleAvatarError4"
                @before="beforeAvatarUpload4"
            ></files-upload>
        </div>
        <div class="form-verify">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="form-ruleForm">
                <el-form-item prop="name">
                    <el-input v-model.trim="ruleForm.name" placeholder="请输入真实姓名" maxlength="60"></el-input>
                </el-form-item>
                <el-form-item prop="cusEngName">
                    <el-input v-model="ruleForm.cusEngName" placeholder="请输入英文名称" maxlength="100"></el-input>
                </el-form-item>
                <el-form-item prop="idCard">
                    <el-input v-model.trim="ruleForm.idCard" placeholder="请输入证件号码" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item prop="address">
                    <el-input v-model.trim="ruleForm.address" maxlength="100" placeholder="请输入常用住址"></el-input>
                </el-form-item>
                <el-form-item prop="region" class="region">
                    <el-select
                        v-model="ruleForm.region"
                        placeholder="选择店铺经营类别"
                        @change="getStoreBusinessTypeName(ruleForm.region)"
                    >
                        <el-option
                            :label="item.name"
                            :value="item.id"
                            v-for="(item) in storeList"
                            :key="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="agreement" class="check-box">
                    <el-checkbox name="type" v-model="ruleForm.agreement"></el-checkbox>
                    <p>
                        我已阅读并同意
                        <router-link to="/agreement" target="_blank">《大麦及时雨收款用户协议》</router-link>
                    </p>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="primary"
                        @click="submitForm('ruleForm')"
                        :loading="subLoading"
                    >提交</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import {
    api_findDictionary,
    api_addHKPersonal,
    api_getCertiInfo
} from "api/login.js";
import utils from "utils/utils.js";
import filesUpload from "./filesUpload";
let host = process.env.NODE_ENV == "development" ? "/api" : "";

export default {
    name: "HKPersonal",
    components: { filesUpload },
    computed: {
        ...mapState(["userInfo"])
    },
    data() {
        var checkIdCard = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入证件号码"));
            } else {
                callback();
            }
        };
        var regEngName = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入英文名称"));
            } else if (utils.regEngName(value)) {
                callback(new Error("请输入正确的英文名称"));
            } else {
                callback();
            }
        };
        return {
            ruleForm: {
                name: "",
                cusEngName: "",
                idCard: "",
                region: "",
                address: "",
                agreement: []
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入真实姓名",
                        trigger: "blur"
                    }
                ],
                cusEngName: [{ validator: regEngName, trigger: "blur" }],
                idCard: [{ validator: checkIdCard, trigger: "blur" }],
                region: [
                    {
                        required: true,
                        message: "请选择店铺经营类别",
                        trigger: "change"
                    }
                ],
                address: [
                    {
                        required: true,
                        message: "请输入常用住址",
                        trigger: "blur"
                    }
                ],
                agreement: [
                    {
                        type: "array",
                        required: true,
                        message: "请阅读服务协议并选中",
                        trigger: "change"
                    }
                ]
            },
            cardOptions: [
                {
                    value: "1",
                    label: "护照"
                },
                {
                    value: "2",
                    label: "香港永久性居民身份证"
                }
                // {
                //     value: "3",
                //     label: "英国国民（海外）护照"
                // }
            ],
            cardValue: "",
            certiCardType: "",
            //上传图片的路径
            imageUrl: "",
            imageUrl2: "",
            imageUrl3: "",
            imageUrl4: "",
            loading: false,
            loading2: false,
            loading3: false,
            loading4: false,
            storeList: [],
            storeBusinessTypeName: "",
            browserIP: "",
            idCardHk: {}, //香港永久性居民身份证
            idCardHkHand: {}, //香港永久性居民身份证手持
            passport: {}, //护照
            overseasPassport: {}, //英国国民（海外）护照
            kycCertiLinkFileReqList: [],
            longTime: false,
            uploadUrl: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE`,
            popoverImg: require("assets/images/kyc-HK-idcard.jpg"),
            uploadTitle: "身份证 照片页",
            uploadUrl2: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE`,
            popoverImg2: require("assets/images/kyc-idcard-hand.jpg"),
            uploadTitle2: "手持身份证 照片",
            uploadUrl3: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE`,
            popoverImg3: require("assets/images/kyc-passport.jpg"),
            uploadTitle3: "护照 首页",
            uploadUrl4: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE`,
            popoverImg4: require("assets/images/kyc-British-passport.jpg"),
            uploadTitle4: "英国国民（海外）护照",
            subLoading: false,
            jsRemark: "",
            resubmitId: ""
        };
    },
    methods: {
        ...mapMutations(["setLoginInfo"]),
        selectCertificateType(val) {
            if (val === "1") {
                this.certiCardType = "PASSPROT_IMAGE";
            } else if (val === "2") {
                this.certiCardType = "CARD_HK_PERPETUAL";
            } else if (val === "3") {
                this.certiCardType = "UK_PASSPORT";
            }
        },
        //上传香港永久性居民身份证
        handleAvatarSuccess(res, file) {
            this.loading = false;
            this.imageUrl = URL.createObjectURL(file.raw);
            this.idCardHk = Object.assign(file.response.data, {
                certiFileType: "CARD_HK_PERPETUAL"
            });
        },
        handleAvatarError() {
            this.loading = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload(file) {
            this.loading = true;
        },
        handleAvatarSuccess2(res, file) {
            this.loading2 = false;
            this.imageUrl2 = URL.createObjectURL(file.raw);
            this.idCardHkHand = Object.assign(file.response.data, {
                certiFileType: "CARD_HANDID_HK_PERPETUAL"
            });
        },
        handleAvatarError2() {
            this.loading2 = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload2(file) {
            this.loading2 = true;
        },
        //上传护照
        handleAvatarSuccess3(res, file) {
            this.loading3 = false;
            this.imageUrl3 = URL.createObjectURL(file.raw);
            this.passport = Object.assign(file.response.data, {
                certiFileType: "PASSPROT_IMAGE"
            });
        },
        handleAvatarError3() {
            this.loading3 = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload3(file) {
            this.loading3 = true;
        },
        //上传英国国民（海外）护照
        handleAvatarSuccess4(res, file) {
            this.loading4 = false;
            this.imageUrl4 = URL.createObjectURL(file.raw);
            this.overseasPassport = Object.assign(file.response.data, {
                certiFileType: "UK_PASSPORT"
            });
        },
        handleAvatarError4() {
            this.loading4 = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload4(file) {
            this.loading4 = true;
        },

        //选择店铺经营类别
        getStoreBusinessTypeName(val) {
            let storeType = this.storeList.filter(item => {
                return item.id === val;
            });
            this.storeBusinessTypeName = storeType[0].name;
        },
        //提交
        submitForm(formName) {
            this.subLoading = true;
            let copyInitVuex = JSON.parse(localStorage.getItem("initVuex"));
            copyInitVuex.userInfo.loginInfo.certificationStatus =
                "SUBMIT_WATING";
            copyInitVuex.userInfo.loginInfo.certificationName = this.ruleForm.name;
            if (
                this.userInfo.loginInfo.certificationStatus !==
                "FIRST_TRIAL_FAILURE"
            ) {
                if (this.cardValue === "") {
                    this.subLoading = false;
                    this.$message.error("请选择证件类型！");
                    return false;
                }
            }
            if (
                this.userInfo.loginInfo.certificationStatus !==
                "FIRST_TRIAL_FAILURE"
            ) {
                if (this.cardValue === "1") {
                    if (!this.passport.id) {
                        this.subLoading = false;
                        this.$message.error("请上传证件照片！");
                        return false;
                    } else {
                        this.kycCertiLinkFileReqList = [this.passport];
                    }
                } else if (this.cardValue === "2") {
                    if (!this.idCardHk.id || !this.idCardHkHand.id) {
                        this.subLoading = false;
                        this.$message.error("请上传证件照片！");
                        return false;
                    } else {
                        this.kycCertiLinkFileReqList = [
                            this.idCardHk,
                            this.idCardHkHand
                        ];
                    }
                } else if (this.cardValue === "3") {
                    if (!this.overseasPassport.id) {
                        this.subLoading = false;
                        this.$message.error("请上传证件照片！");
                        return false;
                    } else {
                        this.kycCertiLinkFileReqList = [this.overseasPassport];
                    }
                }
            }

            this.$refs[formName].validate(valid => {
                if (valid) {
                    let addHKPersonalData = {
                        data: {
                            certiCardType: this.certiCardType,
                            cusName: this.ruleForm.name,
                            cusEngName: this.ruleForm.cusEngName,
                            certificateNo: this.ruleForm.idCard,
                            address: this.ruleForm.address,
                            storeBusinessTypeId: this.ruleForm.region,
                            storeBusinessTypeName: this.storeBusinessTypeName,
                            kycCertiLinkFileReqList: this
                                .kycCertiLinkFileReqList,
                            browserIP: this.browserIp || "114.55.171.170",
                            id: this.resubmitId
                        }
                    };

                    api_addHKPersonal(addHKPersonalData)
                        .then(res => {
                            if (res.success) {
                                this.$store.commit(
                                    "setLoginInfo",
                                    copyInitVuex.userInfo.loginInfo
                                );
                                localStorage.setItem(
                                    "initVuex",
                                    JSON.stringify(copyInitVuex)
                                );
                                this.$router.push({
                                    path: "/kycSucc"
                                });
                                this.subLoading = false;
                            } else {
                                if (res.code == -33) {
                                    this.$router.push({
                                        path: "/account"
                                    });
                                } else {
                                    this.$message.error(res.msg);
                                }
                                this.subLoading = false;
                            }
                        })
                        .catch(err => {});
                } else {
                    this.subLoading = false;
                    return false;
                }
            });
        },
        firstTrialFailue() {
            let getCertiInfoParams = {
                params: {}
            };
            api_getCertiInfo(getCertiInfoParams).then(res => {
                this.certiCardType = res.data.idType;
                if (this.certiCardType === "PASSPROT_IMAGE") {
                    this.cardValue = "1";
                } else if (this.certiCardType === "CARD_HK_PERPETUAL") {
                    this.cardValue = "2";
                } else if (this.certiCardType === "UK_PASSPORT") {
                    this.cardValue = "3";
                }
                this.ruleForm.name = res.data.cusName;
                this.ruleForm.cusEngName = res.data.cusEngName;
                this.ruleForm.idCard = res.data.certificateNo;
                this.ruleForm.address = res.data.address;
                this.ruleForm.region = res.data.storeBusinessTypeId;
                this.storeBusinessTypeName = res.data.storeBusinessTypeName;
                this.kycCertiLinkFileReqList = res.data.kycCertiLinkFileReqList;
                this.imageUrl = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.CARD_HK_PERPETUAL}&fileName=abc.jpg`;
                this.imageUrl2 = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.CARD_HANDID_HK_PERPETUAL}&fileName=abc.jpg`;
                this.imageUrl3 = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.PASSPROT_IMAGE}&fileName=abc.jpg`;
                this.imageUrl4 = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.UK_PASSPORT}&fileName=abc.jpg`;
                this.jsRemark = res.data.jsRemark;
                this.resubmitId = res.data.id;
            });
        }
    },
    created() {
        let storeBusinessType = {
            params: {
                type: "STORE_BUSINESS_TYPE"
            }
        };
        api_findDictionary(storeBusinessType)
            .then(res => {
                if (res.success) {
                    this.storeList = res.data;
                } else {
                    this.$message.error(res.msg);
                }
            })
            .catch(err => {});
        if (
            this.userInfo.loginInfo.certificationStatus ===
            "FIRST_TRIAL_FAILURE"
        ) {
            this.firstTrialFailue();
        }
    },
    mounted() {}
};
</script>

<style lang="less" scoped>
.personal /deep/ .el-popover {
    width: 270px;
    img {
        width: 270px;
        height: 168px;
    }
}

.personal /deep/ .check-box {
    .el-checkbox {
        margin-right: 10px;
    }
    .el-form-item__error {
        margin-top: -10px;
    }
    p {
        display: inline-block;
        color: #747474;
        a {
            color: #3d86e9;
        }
    }
}
.personal /deep/ .el-button--primary {
    width: 330px;
}

.personal {
    padding-top: 30px;
    h3 {
        margin-bottom: 8px;
    }
    .upload-notice {
        display: block;
        line-height: 56px;
        span {
            font-size: 14px;
            color: #999999;
            &:last-of-type {
                cursor: pointer;
                color: #3d86e9;
            }
        }
    }
    .avatar-uploader {
        overflow: hidden;
        position: relative;
        float: left;
        width: 270px;
        height: 168px;
        margin-right: 30px;
        border: 1px dashed #f0f4ff;
        border-radius: 6px;
        background: #f0f4ff;
        img {
            position: relative;
            z-index: 8;
        }
        .avatar-uploader-icon {
            position: absolute;
            left: 0;
            top: 0;
            z-index: 10;
            width: 270px;
            height: 168px;
            &::before {
                content: "";
            }
        }
        .avatar-cont {
            position: absolute;
            left: 0;
            top: 0;
            width: 270px;
            height: 168px;
            span {
                display: block;
                line-height: 24px;
                font-size: 14px;
            }
            .icon-plus {
                display: block;
                width: 50px;
                height: 50px;
                margin: 30px auto 18px;
                background: url(~assets/images/icon-plus.png) no-repeat;
                background-size: 50px 50px;
            }
        }
        .avatar {
            width: 270px;
            height: 168px;
            display: block;
        }
        .mask {
            position: absolute;
            left: 0;
            top: 0;
            z-index: 9;
            width: 270px;
            height: 168px;
            line-height: 168px;
            text-align: center;
            background: rgba(0, 0, 0, 0.5);
            p {
                color: #ffffff;
            }
        }
        .example-mask {
            position: absolute;
            left: 0;
            bottom: -210px;
            z-index: 6;
            width: 270px;
            height: 168px;
            border-radius: 6px;
            background: #e4dde5;
            &::before {
                content: "";
                position: absolute;
                top: -20px;
                left: 60px;
                width: 0;
                height: 0;
                border-top: 10px solid transparent;
                border-right: 10px solid transparent;
                border-bottom: 10px solid #e4dde5;
                border-left: 10px solid transparent;
            }
        }
    }
    .form-verify {
        margin-top: 24px;
        .form-ruleForm {
            width: 330px;
        }
    }
}
.resubmit-notice {
    margin: 20px 0;
    padding: 20px;
    line-height: 28px;
    border-radius: 6px;
    background: #fff8e8;
    color: #cc3333;
    span {
        &:first-child {
            font-weight: bold;
        }
        &:last-child {
            font-size: 16px;
        }
    }
}
</style>
