<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="请选择">
            <el-option
                v-for="item in cardOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
        </el-select>
        <label class="upload-notice">
            <span>证件照片 （请确认信息无误，证件图片清晰可见，图片支持jpg、png、jpeg，文件不超过5MB）</span>
            <!-- <span>查看示例</span> -->
        </label>
        <div class="upload-box clearfix">
            <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>
            <files-upload
                :uploadUrl="uploadUrl3"
                :popoverImg="popoverImg3"
                :imageUrl="imageUrl3"
                :title="uploadTitle3"
                v-loading="loading3"
                @success="handleAvatarSuccess3"
                @error="handleAvatarError3"
                @before="beforeAvatarUpload3"
            ></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="请输入真实姓名"
                        @blur="setEngName"
                        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="18"></el-input>
                </el-form-item>
                <el-form-item required>
                    <el-col :span="11">
                        <el-form-item prop="startTime">
                            <el-date-picker
                                v-model="ruleForm.startTime"
                                type="date"
                                placeholder="身份证有效期"
                                style="width: 100%;"
                                @change="setStartTime(ruleForm.startTime)"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col class="line" :span="2" style="text-align: center;">-</el-col>
                    <el-col :span="11">
                        <el-form-item prop="endTime">
                            <el-date-picker
                                v-model="ruleForm.endTime"
                                type="date"
                                placeholder="身份证有效期"
                                style="width: 100%;"
                                :disabled="longTime"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item prop="resource">
                    <el-radio-group v-model="ruleForm.resource" @change="isLongTime">
                        <el-radio label="1">非长期</el-radio>
                        <el-radio label="2">长期</el-radio>
                    </el-radio-group>
                </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_addPersonal,
    api_getCertiInfo,
    api_convertToPinYin
} from "api/login.js";
import utils from "utils/utils.js";
import filesUpload from "./filesUpload";
let host = process.env.NODE_ENV == "development" ? "/api" : "";
// console.log(process.env.NODE_ENV);
// console.log(host);

export default {
    name: "ChinaPersonal",
    components: { filesUpload },
    computed: {
        ...mapState(["userInfo"])
    },
    data() {
        var checkIdCard = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入身份证号码"));
            } else if (!utils.isvalidIdCard(value)) {
                callback(new Error("身份证号码格式错误"));
            } else if (utils.isAdult(value) < 18) {
                callback(new Error("此身份信息未满十八周岁"));
            } else {
                this.ruleForm.idCard = utils.toLocaleUpperCaseIdCard(value);
                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: "",
                startTime: "",
                endTime: "",
                resource: "1",
                region: "",
                address: "",
                agreement: []
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入真实姓名",
                        trigger: "change"
                    }
                ],
                cusEngName: [{ validator: regEngName, trigger: "change" }],
                idCard: [{ validator: checkIdCard, trigger: "change" }],
                startTime: [
                    {
                        type: "date",
                        required: true,
                        message: "请选择开始日期",
                        trigger: "change"
                    }
                ],
                endTime: [
                    {
                        type: "date",
                        required: true,
                        message: "请选择结束日期",
                        trigger: "change"
                    }
                ],
                region: [
                    {
                        required: true,
                        message: "请选择店铺经营类别",
                        trigger: "change"
                    }
                ],
                address: [
                    {
                        required: true,
                        message: "请输入常用住址",
                        trigger: "change"
                    }
                ],
                agreement: [
                    {
                        type: "array",
                        required: true,
                        message: "请阅读服务协议并选中",
                        trigger: "change"
                    }
                ]
            },
            cardOptions: [
                {
                    value: "1",
                    label: "第二代居民身份证"
                }
            ],
            cardValue: "第二代居民身份证",
            imageUrl: "",
            imageUrl2: "",
            imageUrl3: "",
            loading: false,
            loading2: false,
            loading3: false,
            storeList: [],
            storeBusinessTypeName: "",
            browserIP: "",
            idCardFront: {}, //身份证
            idCardBack: {},
            idCardHand: {},
            kycCertiLinkFileReqList: [],
            longTime: false,
            uploadUrl: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE&certiFileType=CARD_FRONT_IMAGE`,
            popoverImg: require("assets/images/kyc-idcard-front.jpg"),
            uploadTitle: "身份证人像页",
            uploadUrl2: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE&certiFileType=CARD_BACK_IMAGE`,
            popoverImg2: require("assets/images/kyc-idcard-back.jpg"),
            uploadTitle2: "身份证国徽页",
            uploadUrl3: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE`,
            popoverImg3: require("assets/images/kyc-idcard-hand.jpg"),
            uploadTitle3: "手持身份证照片",
            subLoading: false,
            jsRemark: "",
            resubmitId: ""
        };
    },
    methods: {
        ...mapMutations(["setLoginInfo"]),
        //上传身份证
        handleAvatarSuccess(res, file) {
            let ocrData = res.data.ocrData;
            if (ocrData !== null) {
                this.ruleForm.name = ocrData.name;
                this.ruleForm.idCard = ocrData.id;
                this.ruleForm.address = ocrData.address;
                this.setEngName();
            } else {
                this.ruleForm.name = "";
                this.ruleForm.idCard = "";
                this.ruleForm.address = "";
                this.ruleForm.cusEngName = "";
            }

            this.loading = false;
            this.imageUrl = URL.createObjectURL(file.raw);
            this.idCardFront = Object.assign(file.response.data, {
                certiFileType: "CARD_FRONT_IMAGE"
            });
            this.$message.warning("请确认上传的是身份证正面照！");
        },
        handleAvatarError() {
            this.loading = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload(file) {
            this.loading = true;
        },
        handleAvatarSuccess2(res, file) {
            let ocrData = res.data.ocrData;
            if (ocrData !== null) {
                if (ocrData.valid_date !== "") {
                    this.ruleForm.startTime = new Date(
                        Date.parse(
                            ocrData.valid_date.split("-")[0].replace(/\./g, "/")
                        )
                    );
                    this.ruleForm.endTime = new Date(
                        Date.parse(
                            ocrData.valid_date.split("-")[1].replace(/\./g, "/")
                        )
                    );
                }
            } else {
                this.ruleForm.startTime = "";
                this.ruleForm.endTime = "";
            }

            this.loading2 = false;
            this.imageUrl2 = URL.createObjectURL(file.raw);
            this.idCardBack = Object.assign(file.response.data, {
                certiFileType: "CARD_BACK_IMAGE"
            });
        },
        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.idCardHand = Object.assign(file.response.data, {
                certiFileType: "CARD_HANDID_IMAGE"
            });
            // if (res.data.ocrData == "true") {
            //     this.imageUrl3 = URL.createObjectURL(file.raw);
            //     this.idCardHand = Object.assign(file.response.data, {
            //         certiFileType: "CARD_HANDID_IMAGE"
            //     });
            // } else {
            //     this.$message.error("手持身份证识别失败！");
            //     return false;
            // }
        },
        handleAvatarError3() {
            this.loading3 = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload3(file) {
            this.loading3 = true;
        },
        //汉字转拼音
        setEngName() {
            let convertToPinYinParams = {
                params: {
                    hanZi: this.ruleForm.name
                }
            };
            api_convertToPinYin(convertToPinYinParams).then(res => {
                this.ruleForm.cusEngName = res.data;
                if (this.ruleForm.cusEngName !== "") {
                    this.$message.warning("请核对英文名称是否正确！");
                }
            });
        },
        //选择身份证开始结束时间
        setStartTime(val) {
            let endDate = new Date(val);
            if (!this.longTime) {
                this.ruleForm.endTime = new Date(
                    endDate.setFullYear(endDate.getFullYear() + 20)
                );
            }
        },
        //选择身份证有效期
        isLongTime(val) {
            this.longTime = val == "1" ? false : 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;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (
                        this.userInfo.loginInfo.certificationStatus !==
                        "FIRST_TRIAL_FAILURE"
                    ) {
                        if (
                            !this.idCardFront.id ||
                            !this.idCardBack.id ||
                            !this.idCardHand.id
                        ) {
                            this.subLoading = false;
                            this.$message.error("请上传证件照片！");
                            return false;
                        }
                    }

                    if (
                        this.userInfo.loginInfo.certificationStatus !==
                        "FIRST_TRIAL_FAILURE"
                    ) {
                        this.kycCertiLinkFileReqList = [
                            this.idCardFront,
                            this.idCardBack,
                            this.idCardHand
                        ];
                    }

                    let addPersonalData = {
                        data: {
                            certiCardType: "ID_CARD",
                            cusName: this.ruleForm.name,
                            cusEngName: this.ruleForm.cusEngName,
                            idNo: this.ruleForm.idCard,
                            effectiveStartTime: utils.formatDate(
                                this.ruleForm.startTime,
                                "yyyy-MM-dd"
                            ),
                            effectiveEndTime:
                                this.ruleForm.resource === "1"
                                    ? utils.formatDate(
                                          this.ruleForm.endTime,
                                          "yyyy-MM-dd"
                                      )
                                    : "",
                            longFlag:
                                this.ruleForm.resource === "1" ? false : true,
                            storeBusinessTypeId: this.ruleForm.region,
                            liveAddress: this.ruleForm.address,
                            storeBusinessTypeName: this.storeBusinessTypeName,
                            kycCertiLinkFileReqList: this
                                .kycCertiLinkFileReqList,
                            browserIP: this.browserIp || "114.55.171.170",
                            id: this.resubmitId
                        }
                    };
                    api_addPersonal(addPersonalData)
                        .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.ruleForm.name = res.data.cusName;
                this.ruleForm.cusEngName = res.data.cusEngName;
                this.ruleForm.idCard = res.data.idNo;
                this.ruleForm.startTime = new Date(res.data.effectiveStartTime);
                this.ruleForm.endTime = new Date(res.data.effectiveEndTime);
                res.data.longFlag === false
                    ? (this.ruleForm.resource = "1")
                    : (this.ruleForm.resource = "2");
                this.ruleForm.region = res.data.storeBusinessTypeId;
                this.ruleForm.address = res.data.liveAddress;
                this.storeBusinessTypeName = res.data.storeBusinessTypeName;
                this.kycCertiLinkFileReqList = res.data.kycCertiLinkFileReqList;
                this.imageUrl = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.CARD_FRONT_IMAGE}&fileName=abc.jpg`;
                this.imageUrl2 = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.CARD_BACK_IMAGE}&fileName=abc.jpg`;
                this.imageUrl3 = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.CARD_HANDID_IMAGE}&fileName=abc.jpg`;
                res.data.longFlag === true
                    ? (this.longTime = true)
                    : (this.longTime = false);
                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;
}
.el-date-editor {
    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>
