<template>
    <div class="kyc-box">
        <login-header></login-header>
        <main class="wrap" v-loading="loading">
            <section class="layout-box clearfix">
                <div class="layout-content box-shadow">
                    <div class="accont-title clearfix">
                        <h3>补充受益人信息</h3>
                    </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"
                                    :disabled="disabled"
                                    placeholder="请输入最终受益人姓名"
                                    @blur="setLegalPerson(ruleForm.name)"
                                ></el-input>
                            </el-form-item>
                            <el-form-item prop="cardValue" style="margin-bottom:0;">
                                <el-select
                                    v-model="ruleForm.cardValue"
                                    placeholder="请选择最终受益人证件类型"
                                    @change="selectCertificateType"
                                >
                                    <el-option
                                        v-for="item in cardOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>

                            <label class="upload-notice" v-if="ruleForm.cardValue !== ''">
                                <span>最终受益人证件照 （请确认信息无误，证件图片清晰可见，图片支持jpg、png、jpeg，文件不超过5MB）</span>
                                <!-- <span>查看示例</span> -->
                            </label>
                            <div class="upload-box clearfix" v-if="ruleForm.cardValue == 1">
                                <files-upload
                                    :uploadUrl="uploadUrl3"
                                    :popoverImg="popoverImg3"
                                    :imageUrl="imageUrl3"
                                    :title="uploadTitle3"
                                    v-loading="loading3"
                                    @success="handleAvatarSuccess3"
                                    @error="handleAvatarError3"
                                    @before="beforeAvatarUpload3"
                                ></files-upload>
                                <files-upload
                                    :uploadUrl="uploadUrl4"
                                    :popoverImg="popoverImg4"
                                    :imageUrl="imageUrl4"
                                    :title="uploadTitle4"
                                    v-loading="loading4"
                                    @success="handleAvatarSuccess4"
                                    @error="handleAvatarError4"
                                    @before="beforeAvatarUpload4"
                                ></files-upload>
                            </div>
                            <div class="upload-box clearfix" v-else-if="ruleForm.cardValue == 2">
                                <files-upload
                                    :uploadUrl="uploadUrl5"
                                    :popoverImg="popoverImg5"
                                    :imageUrl="imageUrl5"
                                    :title="uploadTitle5"
                                    v-loading="loading5"
                                    @success="handleAvatarSuccess5"
                                    @error="handleAvatarError5"
                                    @before="beforeAvatarUpload5"
                                ></files-upload>
                            </div>
                            <div class="upload-box clearfix" v-else-if="ruleForm.cardValue == 3">
                                <files-upload
                                    :uploadUrl="uploadUrl6"
                                    :popoverImg="popoverImg6"
                                    :imageUrl="imageUrl6"
                                    :title="uploadTitle6"
                                    v-loading="loading6"
                                    @success="handleAvatarSuccess6"
                                    @error="handleAvatarError6"
                                    @before="beforeAvatarUpload6"
                                ></files-upload>
                            </div>
                            <div v-if="ruleForm.cardValue !== ''" class="mt22">
                                <el-form-item prop="idCard">
                                    <el-input
                                        v-model.trim="ruleForm.idCard"
                                        placeholder="请输入最终受益人证件号码"
                                        maxlength="18"
                                    ></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>
                            </div>
                            <div v-if="ruleForm.cardValue == 1">
                                <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>
                            </div>
                            <el-form-item class="mt22">
                                <el-button
                                    type="primary"
                                    @click="submitForm('ruleForm')"
                                    :loading="subLoading"
                                >补充完成</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </section>
        </main>
        <login-footer></login-footer>
    </div>
</template>

<script>
import loginHeader from "./components/header";
import loginFooter from "./components/footer";
import { mapState } from "vuex";
import Clipboard from "clipboard";
import {
    api_getEnterprisePartners,
    api_addContacts,
    api_getContacts
} from "api/login.js";
import filesUpload from "./components/filesUpload";
import utils from "utils/utils.js";
let host = process.env.NODE_ENV == "development" ? "/api" : "";
export default {
    name: "kycShareholder",
    components: {
        loginHeader,
        loginFooter,
        filesUpload
    },
    data() {
        var checkIdCard = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入最终受益人证件号码"));
            } else {
                if (this.ruleForm.cardValue == 1) {
                    if (!utils.isvalidIdCard(value)) {
                        callback(new Error("最终受益人证件号码格式错误"));
                    } else if (utils.isAdult(value) < 18) {
                        callback(new Error("此身份信息未满十八周岁"));
                    } else {
                        this.ruleForm.idCard = utils.toLocaleUpperCaseIdCard(
                            value
                        );
                        callback();
                    }
                } else {
                    callback();
                }
            }
        };
        return {
            ruleForm: {
                cardValue: "",
                name: "",
                idCard: "",
                address: "",
                startTime: "",
                endTime: "",
                resource: "1"
            },
            rules: {
                cardValue: [
                    {
                        required: true,
                        message: "请选择最终受益人证件类型",
                        trigger: "change"
                    }
                ],
                name: [
                    {
                        required: true,
                        message: "请输入最终受益人姓名",
                        trigger: "change"
                    }
                ],
                idCard: [{ validator: checkIdCard, trigger: "blur" }],
                startTime: [
                    {
                        type: "date",
                        required: true,
                        message: "请选择开始日期",
                        trigger: "change"
                    }
                ],
                endTime: [
                    {
                        type: "date",
                        required: true,
                        message: "请选择结束日期",
                        trigger: "change"
                    }
                ],
                address: [
                    {
                        required: true,
                        message: "请输入最终受益人住址",
                        trigger: "change"
                    }
                ]
            },
            cardOptions: [
                {
                    value: "1",
                    label: "第二代居民身份证"
                },
                {
                    value: "2",
                    label: "护照"
                },
                {
                    value: "3",
                    label: "香港永久性居民身份证"
                }
            ],
            diCardTime: {},
            shareholderInfo: [],
            loading: false,
            loading3: false,
            loading4: false,
            loading5: false,
            loading6: false,
            isNeed: false,
            longTime: false,
            disabled: true,
            subLoading: false,
            certiCardType: "",
            certiCardTypeCopy: "",
            imageUrl3: "",
            imageUrl4: "",
            imageUrl5: "",
            imageUrl6: "",
            uploadUrl: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE`,
            popoverImg: require("assets/images/kyc-HK-registration.jpg"),
            uploadTitle: "商业登记证 照片",
            uploadUrl2: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE`,
            popoverImg2: require("assets/images/kyc-HK-registration-statement.jpg"),
            uploadTitle2: "公司注册证书 照片",
            uploadUrl3: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE&certiFileType=CARD_FRONT_IMAGE`,
            popoverImg3: require("assets/images/kyc-idcard-front.jpg"),
            uploadTitle3: "身份证 人像页",
            uploadUrl4: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE&certiFileType=CARD_BACK_IMAGE`,
            popoverImg4: require("assets/images/kyc-idcard-back.jpg"),
            uploadTitle4: "身份证 国徽页",
            uploadUrl5: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE`,
            popoverImg5: require("assets/images/kyc-passport.jpg"),
            uploadTitle5: "护照 首页",
            uploadUrl6: `${host}/api/v1/authc/jsFile/upFile?fileResourceType=REAL_NAME_CERTIFICATE&fileType=IMAGE`,
            popoverImg6: require("assets/images/kyc-HK-idcard.jpg"),
            uploadTitle6: "身份证 照片页",
            kycCertiLinkFileReqList: [],
            kycCertiLinkFileReqListCopy: [],
            idCardFront: {}, //身份证
            idCardHand: {},
            passport: {}, //护照
            idCardHk: {}, //香港永久性居民身份证
            selectCardType: false
        };
    },
    computed: {
        ...mapState(["userInfo"])
    },
    methods: {
        selectCertificateType(val) {
            if (val === "1") {
                this.certiCardType = "ID_CARD";
            } else if (val === "2") {
                this.certiCardType = "PASSPROT_IMAGE";
            } else if (val === "3") {
                this.certiCardType = "CARD_HK_PERPETUAL";
            }
            if (this.certiCardTypeCopy === this.certiCardType) {
                this.selectCardType = false;
                this.kycCertiLinkFileReqList = this.kycCertiLinkFileReqListCopy;
            } else {
                this.selectCardType = true;
                this.kycCertiLinkFileReqList = [];
            }

            this.$refs["ruleForm"].resetFields();
            this.ruleForm.cardValue = val;
            this.ruleForm.name = this.userInfo.legalPerson;
        },
        setLegalPerson(val) {
            this.$store.commit("setLegalPerson", val);
        },
        init() {
            let getEnterprise25PartnersData = {
                params: {}
            };
            api_getEnterprisePartners(getEnterprise25PartnersData).then(res => {
                this.shareholderInfo = res.data;
                this.shareholderInfo.filter(item => {
                    if (item.isNeed) {
                        this.isNeed = true;
                    }
                });
            });
        },
        formatNum(strNum) {
            var outputmoney = function(number) {
                number = number.replace(/\,/g, ""); //把所有的逗号，清除
                if (isNaN(number) || number == "") return "";
                number = Math.round(number * 100) / 100;
                if (number < 0)
                    return (
                        "-" +
                        outputdollars(Math.floor(Math.abs(number) - 0) + "") +
                        outputcents(Math.abs(number) - 0)
                    );
                else
                    return (
                        outputdollars(Math.floor(number - 0) + "") +
                        outputcents(number - 0)
                    );
            };
            //格式化金额
            var outputdollars = function(number) {
                if (number.length <= 3) {
                    return number == "" ? "0" : number;
                } else {
                    var mod = number.length % 3;
                    var output = mod == 0 ? "" : number.substring(0, mod);
                    for (let i = 0; i < Math.floor(number.length / 3); i++) {
                        if (mod == 0 && i == 0) {
                            output += number.substring(
                                mod + 3 * i,
                                mod + 3 * i + 3
                            );
                        } else {
                            output +=
                                "," +
                                number.substring(mod + 3 * i, mod + 3 * i + 3);
                        }
                    }
                    return output;
                }
            };
            var outputcents = function(amount) {
                amount = Math.round((amount - Math.floor(amount)) * 100);
                return amount < 10 ? ".0" + amount : "." + amount;
            };
            return outputmoney(strNum + "");
        },
        toUpdate(val) {
            if (val.contractsId === "") {
                this.$router.push({
                    path: "/kycUpdate"
                });
            } else {
                this.$router.push({
                    path: "/kycUpdate",
                    query: {
                        id: val.contractsId
                    }
                });
            }
        },
        //选择身份证开始结束时间
        setStartTime(val) {
            let endDate = new Date(val);
            if (!this.longTime) {
                this.ruleForm.endTime = new Date(
                    endDate.setFullYear(endDate.getFullYear() + 20)
                );
                this.diCardTime = {
                    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
                };
            }
        },
        //选择身份证有效期
        isLongTime(val) {
            this.longTime = val == "1" ? false : true;
        },
        //上传身份证
        handleAvatarSuccess3(res, file) {
            let ocrData = res.data.ocrData;
            if (ocrData !== null) {
                this.ruleForm.idCard = ocrData.id;
                this.ruleForm.address = ocrData.address;
            } else {
                this.ruleForm.idCard = "";
                this.ruleForm.address = "";
            }
            this.loading3 = false;
            this.imageUrl3 = URL.createObjectURL(file.raw);
            this.idCardFront = Object.assign(file.response.data, {
                certiFileType: "CARD_FRONT_IMAGE"
            });
            this.$message.warning("请确认上传的是身份证正面照！");
        },
        handleAvatarError3() {
            this.loading3 = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload3(file) {
            this.loading3 = true;
        },
        handleAvatarSuccess4(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, "/")
                        )
                    );
                    console.log(this.ruleForm.startTime);
                }
            } else {
                this.ruleForm.startTime = "";
                this.ruleForm.endTime = "";
            }
            this.loading4 = false;
            this.imageUrl4 = URL.createObjectURL(file.raw);
            this.idCardHand = Object.assign(file.response.data, {
                certiFileType: "CARD_BACK_IMAGE"
            });
        },
        handleAvatarError4() {
            this.loading4 = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload4(file) {
            this.loading4 = true;
        },
        //上传护照
        handleAvatarSuccess5(res, file) {
            this.loading5 = false;
            this.imageUrl5 = URL.createObjectURL(file.raw);
            this.passport = Object.assign(file.response.data, {
                certiFileType: "PASSPROT_IMAGE"
            });
        },
        handleAvatarError5() {
            this.loading5 = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload5(file) {
            this.loading5 = true;
        },
        //上传香港永久性居民身份证
        handleAvatarSuccess6(res, file) {
            this.loading6 = false;
            this.imageUrl6 = URL.createObjectURL(file.raw);
            this.idCardHk = Object.assign(file.response.data, {
                certiFileType: "CARD_HK_PERPETUAL"
            });
        },
        handleAvatarError6() {
            this.loading6 = false;
            this.$message.error("上传失败");
        },
        beforeAvatarUpload6(file) {
            this.loading6 = true;
        },
        //补充完成
        submitForm(formName) {
            this.subLoading = true;
            let kycContractsId = this.$route.query.id;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.selectCardType) {
                        if (this.ruleForm.cardValue === "1") {
                            if (!this.idCardFront.id || !this.idCardHand.id) {
                                this.subLoading = false;
                                this.$message.error("请上传证件照片！");
                                return false;
                            } else {
                                this.kycCertiLinkFileReqList = [
                                    this.idCardFront,
                                    this.idCardHand
                                ];
                                this.diCardTime = {
                                    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
                                };
                                let realStartTime = this.diCardTime.effectiveStartTime.split(
                                    "-"
                                )[0];
                                let realEndTime = this.diCardTime.effectiveEndTime.split(
                                    "-"
                                )[0];
                                if (
                                    parseInt(realStartTime) < 1000 ||
                                    parseInt(realEndTime) < 1000
                                ) {
                                    this.$message.error(
                                        "身份证日期格式不正确！"
                                    );
                                    return false;
                                }
                            }
                        } else if (this.ruleForm.cardValue === "2") {
                            if (!this.passport.id) {
                                this.subLoading = false;
                                this.$message.error("请上传证件照片！");
                                return false;
                            } else {
                                this.kycCertiLinkFileReqList = [this.passport];
                            }
                        } else if (this.ruleForm.cardValue === "3") {
                            if (!this.idCardHk.id) {
                                this.subLoading = false;
                                this.$message.error("请上传证件照片！");
                                return false;
                            } else {
                                this.kycCertiLinkFileReqList = [this.idCardHk];
                            }
                        }
                    }

                    let addContactsData = {
                        data: {
                            kycCertiId: this.userInfo.kycCertiId,
                            contactName: this.ruleForm.name,
                            idType: this.certiCardType,
                            idNo: this.ruleForm.idCard,
                            ...this.diCardTime,
                            address: this.ruleForm.address,
                            kycCertiLinkFileReqList: this
                                .kycCertiLinkFileReqList
                        }
                    };

                    if (kycContractsId) {
                        addContactsData.data = Object.assign(
                            addContactsData.data,
                            {
                                id: kycContractsId
                            }
                        );
                    }
                    api_addContacts(addContactsData)
                        .then(res => {
                            if (res.success) {
                                this.$router.replace({
                                    path: "/kycShareholder"
                                });
                                this.subLoading = false;
                            } else {
                                this.$message.error(res.msg);
                                this.subLoading = false;
                            }
                        })
                        .catch(err => {});
                } else {
                    this.subLoading = false;
                    return false;
                }
            });
        },
        firstTrialFailue(kycContractsId) {
            let getContactsParams = {
                params: {
                    kycContractsId: kycContractsId,
                    kycCertiId: this.userInfo.kycCertiId
                }
            };
            api_getContacts(getContactsParams).then(res => {
                this.certiCardType = res.data.idType;
                this.certiCardTypeCopy = res.data.idType;
                if (res.data.idType == "ID_CARD") {
                    this.ruleForm.cardValue = "1";
                } else if (res.data.idType == "PASSPROT_IMAGE") {
                    this.ruleForm.cardValue = "2";
                } else if (res.data.idType == "CARD_HK_PERPETUAL") {
                    this.ruleForm.cardValue = "3";
                }
                this.ruleForm.name = res.data.contactName;
                this.ruleForm.idCard = res.data.idNo;
                this.ruleForm.address = res.data.address;
                if (this.ruleForm.cardValue === "1") {
                    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.diCardTime = {
                        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
                    };
                }

                this.kycCertiLinkFileReqList = res.data.kycCertiLinkFileReqList;
                this.kycCertiLinkFileReqListCopy =
                    res.data.kycCertiLinkFileReqList;
                if (this.ruleForm.cardValue === "1") {
                    this.imageUrl3 = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.CARD_FRONT_IMAGE}&fileName=abc.jpg`;
                    this.imageUrl4 = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.CARD_BACK_IMAGE}&fileName=abc.jpg`;
                } else if (this.ruleForm.cardValue === "2") {
                    this.imageUrl5 = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.PASSPROT_IMAGE}&fileName=abc.jpg`;
                } else if (this.ruleForm.cardValue === "3") {
                    this.imageUrl6 = `${host}/api/v1/anon/jsFile/downLoad?filePath=${res.data.CARD_HK_PERPETUAL}&fileName=abc.jpg`;
                }
                res.data.longFlag === true
                    ? (this.longTime = true)
                    : (this.longTime = false);
            });
        }
    },
    created() {
        this.init();
        let kycContractsId = this.$route.query.id;
        if (kycContractsId) {
            this.firstTrialFailue(kycContractsId);
        } else {
            this.disabled = false;
        }

        this.ruleForm.name = this.userInfo.legalPerson;
    }
};
</script>

<style lang="less" scoped>
@import "../../assets/styles/common.css";
.kyc-box /deep/ .check-box {
    position: relative;
    .el-checkbox {
        margin-right: 10px;
    }
    .el-form-item__error {
        margin-top: -10px;
    }
    p {
        position: absolute;
        top: 0;
        left: 24px;
        color: #747474;
        a {
            color: #3d86e9;
        }
    }
}
.kyc-box /deep/ .el-button--primary {
    width: 330px;
}

.kyc-box /deep/ .el-form-item__error {
    width: 330px;
}
.el-date-editor {
    width: 330px;
}
.kyc-box {
    background: #f7f7f7;
}
.wrap {
    min-height: calc(100vh - 184px);
    margin: 30px 0;
}
.form-verify {
    text-align: left;
    overflow: hidden;
    .form-ruleForm {
        margin: 20px;
        width: 330px;
    }
    .upload-notice {
        display: block;
        width: 900px;
        line-height: 56px;
        span {
            font-size: 14px;
            color: #999999;
        }
    }
    .el-select {
        width: 330px;
    }
    .upload-box {
        width: 1080px;
    }
}
.mt22 {
    margin-top: 22px;
}
.notice {
    margin-bottom: 20px;
    padding: 20px;
    background: #fff8e8;
    p {
        line-height: 22px;
        padding-left: 32px;
        font-size: 14px;
        text-align: left;
        background: url(~assets/images/icon-notice.png) left 0 no-repeat;
        background-size: 20px 20px;
        color: #cc3333;
    }
}
</style>
