<template>
    <main>
        <section class="layout-box clearfix">
            <div class="layout-content box-shadow">
                <div class="accont-title clearfix">
                    <h3>申请提现</h3>
                    <a href="javascript:;" class="back-btn" @click="goBack">返回</a>
                </div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="form-ruleForm">
                    <p
                        class="text-big"
                    >提现金额（USD）: {{ this.withdrawDeposit.currencySymbol }}{{ formatNum(this.withdrawDeposit.totleMoney) }}</p>
                    <el-form-item prop="currency" class="currency">
                        <el-select
                            v-model="ruleForm.currency"
                            placeholder="请选择到账币种"
                            @change="getBankcardList"
                        >
                            <el-option
                                v-for="(item) in currencyList"
                                :label="item.currency"
                                :value="item.currencyKyc"
                                :key="item.currency"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <p class="text-big">提现到银行卡：</p>
                    <el-form-item prop="bankcard" class="bankcard">
                        <el-select
                            v-model="ruleForm.bankcard"
                            placeholder="请选择提现银行卡"
                            @change="getBankcardInfo"
                        >
                            <el-option
                                v-for="(item) in bankcardList"
                                :label="item.bankName + ' （尾号：' + item.accountNo.substring(item.accountNo.length-4) + '）'"
                                :value="item.id"
                                :key="item.id"
                            >
                                <span>{{ item.bankName }}</span>
                                <span>（尾号：{{ item.accountNo.substring(item.accountNo.length-4) }}）</span>
                            </el-option>
                        </el-select>
                        <a
                            href="javascript:;"
                            class="add-bankcard-btn"
                            @click="toAddBankcard"
                        >+添加银行卡</a>
                    </el-form-item>
                    <ul class="text-small">
                        <li>
                            <span>
                                手续费（USD）：
                                <b>{{ serviceCharge }}</b>
                            </span>
                        </li>
                        <li>
                            <span>
                                预计到账金额（USD）：
                                <b>{{ this.withdrawDeposit.currencySymbol }}{{ formatNum(this.withdrawDeposit.totleMoney) }}</b>
                            </span>
                        </li>
                    </ul>
                    <el-form-item prop="verifyType" class="verifyType">
                        <el-select
                            v-model="ruleForm.verifyType"
                            placeholder="请选择验证方式"
                            @change="getVerifyType"
                        >
                            <el-option
                                :label="item.name"
                                :value="item.id"
                                v-for="(item) in verifyTypeList"
                                :key="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="verificationCode" v-if="ruleForm.verifyType !== ''">
                        <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-form-item>
                </el-form>
            </div>
        </section>
        <add-bankcard
            :dialogFormVisible="dialogFormVisible"
            @close="closeDialog"
            @success="addSuccess"
            v-if="kycType === 'MAINLAND_PERSONAL'"
        ></add-bankcard>
        <add-bankcard-company
            :dialogFormVisibleCompany="dialogFormVisibleCompany"
            @close="closeDialog"
            @success="addSuccess"
            v-if="kycType === 'MAINLAND_COMPANY'"
        ></add-bankcard-company>
        <add-bankcard-hk
            :dialogFormVisibleHk="dialogFormVisibleHk"
            @close="closeDialog"
            @success="addSuccess"
            v-if="kycType === 'HK_PERSONAL'"
        ></add-bankcard-hk>
        <add-bankcard-hk-company
            :dialogFormVisibleHkCompany="dialogFormVisibleHkCompany"
            @close="closeDialog"
            @success="addSuccess"
            v-if="kycType === 'HK_COMPANY'"
        ></add-bankcard-hk-company>
    </main>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { api_code } from "api/login.js";
import { api_initWithdrawInfo, api_applyWithdraw } from "api/portal.js";
import { api_bankList } from "api/center.js";
import utils from "utils/utils.js";
import addBankcard from "../center/components/addBankcard";
import addBankcardCompany from "../center/components/addBankcardCompany";
import addBankcardHk from "../center/components/addBankcardHk";
import addBankcardHkCompany from "../center/components/addBankcardHkCompany";
let timer;
export default {
    name: "withdrawDeposit",
    components: {
        addBankcard,
        addBankcardCompany,
        addBankcardHk,
        addBankcardHkCompany
    },
    data() {
        var checkCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("验证码不能为空"));
            } else if (value.length < 6) {
                return callback(new Error("验证码格式不正确"));
            } else {
                callback();
            }
        };
        return {
            ruleForm: {
                currency: "",
                bankcard: "",
                verifyType: "",
                verificationCode: ""
            },
            rules: {
                currency: [
                    {
                        required: true,
                        message: "请选择到账币种",
                        trigger: "change"
                    }
                ],
                bankcard: [
                    {
                        required: true,
                        message: "请选择提现银行卡",
                        trigger: "change"
                    }
                ],
                verifyType: [
                    {
                        required: true,
                        message: "请选择验证方式",
                        trigger: "change"
                    }
                ],
                verificationCode: [{ validator: checkCode, trigger: "blur" }]
            },
            currencyList: [],
            bankcardList: [],
            verifyTypeList: [
                {
                    id: 0,
                    name: "短信"
                }
            ],
            showCountDown: true,
            countDown: 60,
            submitLoading: false,
            markStr: "",
            sendSmsLoading: false,
            serviceCharge: "",
            dialogFormVisible: false,
            dialogFormVisibleCompany: false,
            dialogFormVisibleHk: false,
            dialogFormVisibleHkCompany: false,
            accountNo: "",
            phoneNo: ""
        };
    },
    computed: {
        ...mapState(["userInfo", "withdrawDeposit"])
    },
    methods: {
        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 + "");
        },
        initDate() {
            let initWithdrawInfoParams = {
                params: {
                    storeTheSite: this.$route.query.site
                }
            };
            api_initWithdrawInfo(initWithdrawInfoParams).then(res => {
                if (res.success) {
                    this.currencyList = res.data.currencyList;
                    this.serviceCharge = res.data.serviceCharge;
                } else {
                    this.$message.error(res.msg);
                }
            });
        },
        goBack() {
            this.$router.go(-1);
        },
        getBankcardList(val) {
            let bankListParams = {
                params: {
                    bindingType: "BINDING_COLLECTION",
                    currencyCode: val
                }
            };
            api_bankList(bankListParams).then(res => {
                if (res.success) {
                    this.bankcardList = res.data;
                } else {
                    this.$message.error(res.msg);
                }
            });
        },
        getBankcardInfo(val) {
            for (let i = 0; i < this.bankcardList.length; i++) {
                const element = this.bankcardList[i];
                if (element.id == val) {
                    this.accountNo = element.accountNo;
                }
            }
        },
        getVerifyType(val) {},
        toAddBankcard() {
            if (this.kycType === "MAINLAND_PERSONAL") {
                this.dialogFormVisible = true;
            } else if (this.kycType === "MAINLAND_COMPANY") {
                this.dialogFormVisibleCompany = true;
            } else if (this.kycType === "HK_PERSONAL") {
                this.dialogFormVisibleHk = true;
            } else if (this.kycType === "HK_COMPANY") {
                this.dialogFormVisibleHkCompany = true;
            }
        },
        closeDialog() {
            if (this.kycType === "MAINLAND_PERSONAL") {
                this.dialogFormVisible = false;
            } else if (this.kycType === "MAINLAND_COMPANY") {
                this.dialogFormVisibleCompany = false;
            } else if (this.kycType === "HK_PERSONAL") {
                this.dialogFormVisibleHk = false;
            } else if (this.kycType === "HK_COMPANY") {
                this.dialogFormVisibleHkCompany = false;
            }
        },
        addSuccess() {
            this.$refs["ruleForm"].resetFields();
            this.initDate();
            if (this.kycType === "MAINLAND_PERSONAL") {
                this.dialogFormVisible = false;
            } else if (this.kycType === "MAINLAND_COMPANY") {
                this.dialogFormVisibleCompany = false;
            } else if (this.kycType === "HK_PERSONAL") {
                this.dialogFormVisibleHk = false;
            } else if (this.kycType === "HK_COMPANY") {
                this.dialogFormVisibleHkCompany = false;
            }
        },
        submitForm(formName) {
            this.submitLoading = true;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.markStr === "") {
                        this.submitLoading = false;
                        this.$message.error("请获取验证码！");
                        return false;
                    }
                    let applyWithdrawData = {
                        data: {
                            withdrawTotalAmt: this.withdrawDeposit.totleMoney,
                            serviceCharge: this.serviceCharge,
                            currency: this.ruleForm.currency,
                            bankId: this.ruleForm.bankcard,
                            accountNo: this.accountNo,
                            phone: this.phoneNo,
                            markStr: this.markStr,
                            smsCode: this.ruleForm.verificationCode,
                            browserIP: this.browserIp || "114.55.171.170",
                            withdrawStoreList: this.withdrawDeposit
                                .withdrawStoreList,
                            storeTheSite: this.$route.query.site
                        }
                    };
                    api_applyWithdraw(applyWithdrawData).then(res => {
                        if (res.success) {
                            this.$router.push({
                                path: "/account/withdrawDeposit/succ"
                            });
                        } else {
                            if (res.code === -13) {
                                this.$message.error(res.msg);
                            } else {
                                this.$router.push({
                                    path: "/account/withdrawDeposit/failed"
                                });
                            }
                        }
                        this.submitLoading = false;
                    });
                } else {
                    this.submitLoading = false;
                    return false;
                }
            });
        },
        sendSms() {
            this.sendSmsLoading = true;
            if (this.showCountDown) {
                let verificationCode = {
                    data: {
                        phoneNo: this.phoneNo
                    }
                };
                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.$message.error(res.msg);
                            this.sendSmsLoading = false;
                        }
                    })
                    .catch(err => {
                        this.sendSmsLoading = false;
                    });
            }
        }
    },
    created() {
        clearInterval(timer);
        this.initDate();
        this.phoneNo = this.userInfo.loginInfo.phoneNo;
        this.kycType = this.userInfo.loginInfo.registerType;
    }
};
</script>

<style lang="less" scoped>
@import "../../assets/styles/common.css";
.form-ruleForm /deep/ .el-select {
    width: 100%;
}
.form-ruleForm /deep/ .verification-code {
    width: 190px;
}
.form-ruleForm /deep/ .verification-code + .el-button--primary {
    width: 120px;
    padding: 12px 0;
    margin-left: 16px;
    vertical-align: middle;
}
.form-ruleForm /deep/ .btn-reg {
    .el-button--primary {
        width: 100%;
    }
}
.count-down {
    width: 120px;
}
.accont-title {
    position: relative;
}

.back-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    padding-left: 22px;
    font-size: 14px;
    background: url(~assets/images/icon-center-back.png) left center no-repeat;
    color: #3d86e9;
}

.form-ruleForm {
    width: 330px;
    padding: 20px 0 50px 50px;
    text-align: left;
    .text-big {
        margin-bottom: 22px;
    }
    .text-small {
        margin-bottom: 22px;
        li {
            line-height: 30px;
            font-size: 14px;
            i {
                margin-left: 10px;
                font-style: normal;
                color: #999;
            }
        }
    }
}

.add-bankcard-btn {
    position: absolute;
    top: 1px;
    right: -100px;
    color: #3d86e9;
}
</style>
