<template>
    <div class="add-bankcard">
        <el-dialog
            title="添加新的提现银行卡"
            :visible.sync="dialogFormVisible"
            :before-close="closeDialog"
            :close-on-click-modal="false"
        >
            <bank-list :innerVisibleBankList="innerVisibleBankList" @close="closeBankList"></bank-list>
            <div slot="title" class="header-title">
                <h3>
                    添加新的提现银行卡
                    <span class="title-age">*添加的银行卡信息与认证的实名信息保持一致</span>
                </h3>
            </div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                <el-form-item prop="bankAreaValue">
                    <el-select
                        v-model="ruleForm.bankAreaValue"
                        placeholder="请选择银行所在地区"
                        @change="selectBankArea"
                    >
                        <el-option
                            v-for="item in bankAreaList"
                            :key="item.bankAreaType"
                            :label="item.bankAreaDesc"
                            :value="item.bankAreaType"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="currencyValue">
                    <el-select
                        v-model="ruleForm.currencyValue"
                        placeholder="请选择账户币种"
                        @change="selectAcctName"
                    >
                        <el-option
                            v-for="item in currencyList"
                            :key="item.currencyKyc"
                            :label="item.currency"
                            :value="item.currencyKyc"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <template v-if="acctName">
                    <el-form-item prop="acctNameValue">
                        <el-input type="text" v-model="ruleForm.acctNameValue" disabled></el-input>
                    </el-form-item>
                    <el-form-item prop="bankcardNum">
                        <p
                            class="bankcard-format"
                            v-show="bankcardFormat"
                        >{{ruleForm.bankcardNum.replace(/(\d{4})(?=\d)/g, "$1 ")}}</p>
                        <el-input
                            type="text"
                            v-model.trim="ruleForm.bankcardNum"
                            placeholder="请输入银行卡号"
                            maxlength="20"
                            @focus="showBankcardFormat"
                            @blur="showBankcardFormat"
                        ></el-input>
                        <a
                            href="javascript:;"
                            class="cl-blue"
                            style="position:absolute;left: 350px;top:0;width:150px"
                            @click="showBankList"
                        >查看支持银行卡列表</a>
                    </el-form-item>
                </template>
                <el-form-item prop="phoneNum">
                    <el-input
                        type="text"
                        v-model.number="ruleForm.phoneNum"
                        placeholder="请输入手机号"
                        maxlength="11"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="verificationCode">
                    <el-input
                        v-model.trim="ruleForm.verificationCode"
                        placeholder="短信验证码"
                        class="verification-code"
                        maxlength="6"
                    ></el-input>
                    <el-button
                        type="primary"
                        :loading="sendSmsLoading"
                        @click="sendSms"
                        v-if="showCountDown"
                    >发送验证码</el-button>
                    <el-button
                        type="primary"
                        :loading="false"
                        class="count-down"
                        disabled
                        v-else
                    >{{countDown}}秒</el-button>
                </el-form-item>
                <el-form-item class="btn-reg">
                    <el-button
                        type="primary"
                        @click="submitForm('ruleForm')"
                        :loading="submitLoading"
                    >确认添加</el-button>
                    <el-button @click="closeDialog">返 回</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import {
    api_findJsBankList,
    api_initAddBank,
    api_addBankCard
} from "api/center.js";
import { api_code } from "api/login.js";
import utils from "utils/utils.js";
import bankName from "const/const.js";
import BIN from "bankcardinfo";
import bankList from "pages/dialog/bankList";
let timer;
export default {
    name: "addBankcard",
    props: {
        dialogFormVisible: Boolean
    },
    computed: {
        ...mapState(["userInfo"])
    },
    components: {
        bankList
    },
    data() {
        var checkCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("验证码不能为空"));
            } else if (value.length < 6) {
                return callback(new Error("验证码格式不正确"));
            } else {
                callback();
            }
        };
        var checkPhone = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入手机号"));
            } else if (!utils.isvalidPhone(value)) {
                callback(new Error("手机号格式错误"));
            } else {
                callback();
            }
        };
        var checkBankcard = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入银行卡号"));
            } else if (!utils.luhnCheck(value)) {
                callback(new Error("银行卡号格式错误"));
            } else {
                BIN.getBankBin(value)
                    .then(res => {
                        if (res.bankCode == "CZCB") {
                            this.bankName = "浙江稠州商业银行";
                        } else {
                            this.bankName = res.bankName;
                        }
                        this.bankCode = res.bankCode;

                        let findJsBankListParams = {
                            params: { bankCode: res.bankCode }
                        };
                        api_findJsBankList(findJsBankListParams).then(res => {
                            if (res.success) {
                                if (res.data.length < 1) {
                                    callback(
                                        new Error(
                                            "暂不支持添加该银行发行的银行卡！"
                                        )
                                    );
                                } else {
                                    callback();
                                }
                            } else {
                                callback(new Error(res.msg));
                            }
                        });
                    })
                    .catch(err => {
                        callback(new Error("银行卡号格式错误"));
                    });
            }
        };
        return {
            ruleForm: {
                phoneNum: "",
                bankcardNum: "",
                verificationCode: "",
                acctNameValue: "",
                currencyValue: "",
                bankAreaValue: ""
            },
            rules: {
                phoneNum: [{ validator: checkPhone, trigger: "blur" }],
                bankcardNum: [{ validator: checkBankcard, trigger: "blur" }],
                verificationCode: [{ validator: checkCode, trigger: "blur" }],
                acctNameValue: [
                    {
                        required: true,
                        message: "请选择银行账户名称",
                        trigger: "change"
                    }
                ],
                currencyValue: [
                    {
                        required: true,
                        message: "请选择账户币种",
                        trigger: "change"
                    }
                ],
                bankAreaValue: [
                    {
                        required: true,
                        message: "请选择银行所在地区",
                        trigger: "change"
                    }
                ]
            },
            showCountDown: true,
            countDown: 60,
            submitLoading: false,
            markStr: "",
            acctNameList: [],
            currencyListSelect: [],
            currencyList: [],
            bankAreaList: [],
            bankName: "",
            bankCode: "",
            sendSmsLoading: false,
            acctName: false,
            accountCode: "",
            innerVisibleBankList: false,
            bankcardFormat: false
        };
    },
    methods: {
        closeDialog() {
            this.$refs["ruleForm"].resetFields();
            this.acctName = false;
            this.showCountDown = true;
            clearInterval(timer);
            this.countDown = 60;
            this.$emit("close");
        },
        selectBankArea(val) {
            this.currencyList = this.currencyListSelect;
        },
        selectAcctName(val) {
            this.acctName = true;
        },
        showBankList() {
            this.innerVisibleBankList = true;
        },
        closeBankList() {
            this.innerVisibleBankList = false;
        },
        showBankcardFormat() {
            this.bankcardFormat = !this.bankcardFormat;
        },
        sendSms() {
            this.sendSmsLoading = true;
            if (this.showCountDown) {
                let verificationCode = {
                    data: {
                        phoneNo: this.ruleForm.phoneNum
                    }
                };
                api_code(verificationCode)
                    .then(res => {
                        if (res.success) {
                            this.sendSmsLoading = false;
                            this.showCountDown = false;
                            this.markStr = res.data.markStr;

                            this.$message({
                                message: "验证码发送成功，请注意查收",
                                type: "success"
                            });
                            timer = setInterval(() => {
                                this.countDown--;
                                if (this.countDown < 0) {
                                    this.showCountDown = true;
                                    clearInterval(timer);
                                    this.countDown = 60;
                                }
                            }, 1000);
                        } else {
                            this.sendSmsLoading = false;
                            this.$message.error(res.msg);
                        }
                    })
                    .catch(err => {
                        this.sendSmsLoading = false;
                    });
            }
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                this.submitLoading = true;
                if (valid) {
                    if (this.markStr === "") {
                        this.submitLoading = false;
                        this.$message.error("请获取验证码！");
                        return false;
                    }

                    let addBankCardData = {
                        data: {
                            bindingType: "BINDING_COLLECTION",
                            stateOrRegion: this.ruleForm.bankAreaValue,
                            bankName:
                                this.bankName ||
                                bankName.bankName[this.bankCode],
                            bankCode: this.bankCode,
                            currencyCode: this.ruleForm.currencyValue,
                            accountCode: "SELF",
                            accountName: this.ruleForm.acctNameValue,
                            accountNo: this.ruleForm.bankcardNum,
                            phone: this.ruleForm.phoneNum,
                            markStr: this.markStr,
                            smsCode: this.ruleForm.verificationCode
                        }
                    };
                    api_addBankCard(addBankCardData).then(res => {
                        if (res.success) {
                            this.$emit("success");
                            this.closeDialog();
                        } else {
                            this.$message.error(res.msg);
                        }
                        this.submitLoading = false;
                    });
                } else {
                    this.submitLoading = false;

                    return false;
                }
            });
        }
    },
    created() {
        clearInterval(timer);
        let initAddBankParams = {
            params: {}
        };
        api_initAddBank(initAddBankParams).then(res => {
            if (res.success) {
                this.bankAreaList = res.data.bankArea.filter(item => {
                    if (item.bankAreaType == "MAIN_LAND") {
                        return item;
                    }
                });
                this.currencyListSelect = res.data.currencyCNY;
                this.acctNameList = res.data.acctPersonalName;
                this.ruleForm.acctNameValue = this.acctNameList[0].name;
                this.accountCode = this.acctNameList[0].nameType;
            } else {
                this.$message.error(res.msg);
            }
        });
        this.ruleForm.phoneNum = this.userInfo.loginInfo.phoneNo;
    }
};
</script>

<style lang="less" scoped>
@import "../../../assets/styles/common.css";
.add-bankcard /deep/ .el-input.is-disabled .el-input__inner {
    color: #333;
}
.add-bankcard /deep/ .el-dialog {
    width: 550px;
}
.header-title {
    text-align: left;
    padding-bottom: 20px;
    border-bottom: 1px solid #eaeaea;
    h3 {
        font-size: 18px;
        span {
            font-size: 14px;
            color: #cc3333;
        }
    }
}
.el-form /deep/ .verification-code {
    width: 190px;
}
.el-form /deep/ .verification-code + .el-button--primary {
    width: 120px;
    padding: 12px 0;
    margin-left: 16px;
    vertical-align: middle;
}
.bankcard-format {
    position: absolute;
    left: 0;
    top: -38px;
    width: 330px;
    height: 40px;
    padding-left: 15px;
    line-height: 40px;
    font-size: 20px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background: #fff8e8;
    color: #333;
}
.count-down {
    width: 120px;
}
.el-form {
    width: 330px;
    .el-select {
        width: 100%;
    }
}
.btn-reg {
    position: relative;
    & /deep/ .el-button--primary {
        width: 330px;
    }
    & /deep/ .el-button--default {
        position: absolute;
        top: 0;
        right: -180px;
        width: 158px;
        height: 40px;
    }
}
</style>
