<template>
    <div class="channel-wrap">
        <div class="channel-tab-line">
            <div class="channel-tab" :class="{'tab-active': active}" @click="selectChannel" >
                <div style="height: 100%;overflow: hidden;position: relative;display: flex;align-items: center;padding: 0 20px;">
                    <svg-icon icon-class="goldout" class="channel-icon" />
                    <div>
                        <div class="channel_name">{{ t('capital.goldOut') }}</div>
                    </div>
                    <el-icon v-if="active" ><ArrowDown /></el-icon>
                    <el-icon v-else ><ArrowRight /></el-icon>
                </div>
                <div v-if="active" class="active-overlay" ></div>
            </div>
        </div>
        <el-collapse-transition>
            <div class="channel-pannel" v-show="active" >
                <div class="pay-form">
                    <div v-show="step == 0" style="width: 100%;padding: 90px 0 60px;display: flex;justify-content: center;flex-direction: column;" >
                        <div style="width: 100%;margin-bottom: 22px;display: flex;align-items: center;justify-content: center;">
                            <svg-icon icon-class="error" style="width: 55px;height: 55px;margin-right: 16px;" />
                            <span style="font-size: 34px;font-weight: 700;color: rgba(51, 51, 51, 1);" >{{ t('capital.noKyc') }}</span>
                        </div>
                        <div style="display: flex;align-items: center;justify-content: center;width: 100%;
                        color: rgba(51, 51, 51, 1);font-size: 26px;font-weight: 700;margin-bottom: 50px;">
                            <span>{{ t('capital.noKyc1') }}</span>
                            <span style="color: rgba(41, 187, 228, 1);" >{{ t('capital.noKyc2', {n: 3 - progress}) }}</span>
                            <span>{{ t('capital.noKyc3') }}</span>
                        </div>
                        <router-link to="/profile" v-slot="{ navigate }" style="margin: auto;width: 580px;" >
                            <el-button type="primary" size="large" @click="navigate" 
                            style="width: 580px;font-size: 18px;height: 50px;" >{{ t('capital.toKyc') }}</el-button>
                        </router-link>
                    </div>
                    <el-row v-show="step == 1" >
                        <el-col :span="18">
                            <!-- apply -->
                            <el-row>
                                <div class="goldin-form">
                                    <el-form autocapitalize="off" :inline="true" label-position="top" size="large" :model="form" :rules="rules" ref="formRef"
                                    :disabled="(ioPowerMap!=null && !isEmpty(ioPowerMap.fund_out) && ioPowerMap.fund_out==1)" >
                                        <el-col :md="24" :lg="12" >
                                            <el-form-item :label="t('capital.outAmount')" >
                                                <div class="currency-amount">{{ '$' + form.mt4_balance }}</div>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :md="24" >
                                            <el-form-item :label="t('capital.outUsdAmount')" prop="usd_amount" >
                                                <el-input-number :controls="false" v-model="form.usd_amount" min="0" :max="form.mt4_balance" @input="handleAmount" @mousewheel.native.prevent style="width: 100%" />
                                                <div v-show="!errorMsg" class="el-form-item__error" style="color: #14CC9E;" >{{ inAmountPlaceholder }}</div>
                                                <div v-show="errorMsg" class="el-form-item__error" >{{ errorMsg }}</div>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :md="24" :lg="12" >
                                            <el-form-item :label="t('capital.outBank')" prop="bank_no" >
                                                <div style="flex-wrap: nowrap;width: 100%;display: flex;" >
                                                    <el-select
                                                        v-model="bankIndex"
                                                        :placeholder="t('common.selectChoose')"
                                                        :clearable="false"
                                                        style="flex-shrink: 1;"
                                                        @clear="bankIndex = null"
                                                        @change="handleBankChange"
                                                    >
                                                        <el-option :disabled="item.apply_status != 0" v-for="(item, index) in bankList" :key="index" :label="item.bank_no" :value="index" ></el-option>
                                                    </el-select>
                                                    <el-button style="margin-left: 8px;" type="primary" icon="Plus" plain @click="openAddBank" >{{ t('form.add') }}</el-button>
                                                </div>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :md="24" :lg="12" >
                                            <el-form-item :label="t('capital.currency_type')" prop="currency_type" >
                                                <el-select
                                                    v-model="form.currency_type"
                                                    :placeholder="t('common.selectChoose')"
                                                    :clearable="false"
                                                    style="width: 100%"
                                                    @change="handleCurrencyTypeChange"
                                                >
                                                    <template #label="{ label, value }">
                                                        <div style="width: 100%;display: flex;justify-content: space-between;">
                                                            <span>{{ label }} </span>
                                                            <span style="color:rgba(153, 153, 153, 1)">{{ t('capital.exchangeRate')+ ':' + (exchangeRate ? exchangeRate : '-') }}</span>
                                                        </div>
                                                    </template>
                                                    <el-option v-for="(item, index) in currencyList" :key="index" :label="item" :value="item" ></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :md="24" >
                                            <el-form-item :label="t('capital.remark')" prop="remark" >
                                                <el-input v-model="form.remark" style="width: 100%" maxlength="500" />
                                            </el-form-item>
                                        </el-col>
                                        <div style="width: 100%;display: flex;align-items: baseline;margin-top: 30px;">
                                            <span style="font-size: 16px;margin-right: 10px;">{{ t('capital.currencyAmount') }}</span>
                                            <div class="currency-amount">{{ '' + currencyAmount }}</div>
                                        </div>
                                        <el-form-item  style="width: 100%;">
                                            <el-button :loading="payLoading" 
                                            :disabled="!form.usd_amount || form.usd_amount < 0 || 
                                            (ioPowerMap!=null && !isEmpty(ioPowerMap.fund_out) && ioPowerMap.fund_out==1)" 
                                            class="sub-btn" type="primary" @click="loadOutServiceChargeTips" >{{ t('form.next') }}
                                                <template #loading>
                                                    <l-ring-2 size="20" stroke="2" stroke-length="0.25" bg-opacity="0.1" speed="0.8" color="white" style="margin-right: 17px;" ></l-ring-2>
                                                </template>
                                            </el-button>
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </el-row>
                        </el-col>
                        <el-col :span="6">
                            <div class="template-content">
                                <div v-if="templateContent" v-html="templateContent"></div>
                            </div>
                        </el-col>
                    </el-row>
                    <div v-show="step == 2" style="width: 100%;display: flex;justify-content: center;flex-direction: column;" >
                        <div style="display: flex;align-items: center;justify-content: center;width: 100%;
                        color: rgba(51, 51, 51, 1);font-size: 24px;font-weight: 700;margin-bottom: 10px;">
                            <span>{{ t('capital.fundoutDesc') }}</span>
                        </div>
                        <div class="currency-amount" style="text-align: center;">{{ '$' + form.usd_amount }}</div>
                        <el-form autocapitalize="off" :inline="true" label-position="top" size="large" :model="form2" :rules="rules2" ref="formRef2" style="width: 360px;margin: 40px auto 0;" >
                            <el-form-item :label="t('common.crmPwd')" style="width: 100%;" prop="safe_pass" >
                                <el-input type="password" v-model="form2.safe_pass" style="width: 360px" />
                            </el-form-item>
                        </el-form>
                        <div style="width: 100%;display: flex;justify-content: center;">
                            <el-button class="sub-btn dark-btn" style="width: 400px;height: 50px;font-size: 18px;" type="primary" @click="goStep1" >{{ t('form.last') }}</el-button>
                            <el-button :loading="payLoading" class="sub-btn" style="width: 400px;height: 50px;font-size: 18px;margin-left: 26px;" type="primary" @click="doGoldOut" >{{ t('capital.submit') }}
                                <template #loading>
                                    <l-ring-2 size="20" stroke="2" stroke-length="0.25" bg-opacity="0.1" speed="0.8" color="white" style="margin-right: 17px;" ></l-ring-2>
                                </template>
                            </el-button>
                        </div>
                    </div>
                    <div v-show="step == 3" style="padding: 0 300px;height: 100%;display: flex;flex-direction: column;justify-content: center;align-items: center">
                        <div style="margin-bottom: 16px;line-height: 55px;display: flex;align-items: center;">
                            <svg-icon icon-class="success" style="width: 55px;height: 55px;margin-right: 24px;" />
                            <div style="font-size: 36px;font-weight: 700;" >{{ t('capital.goldout-success') }}</div>
                        </div>
                        <div style="font-size: 18px;font-weight: 400;color: rgba(102, 102, 102, 1);margin-bottom: 80px;" >{{ t('capital.success-desc') }}</div>
                        <div style="width: 100%;display: flex;justify-content: space-between;">
                            <el-button class="sub-btn" type="primary" @click="reset" >{{ t('capital.close') }}</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </el-collapse-transition>
    </div>
    <choose v-model:show="showAddBank" @close="handleChooseAddBank" />
    <bank v-model:show="showCreateBank1" @done="loadBank" />
    <digital v-model:show="showCreateBank2" @done="loadBank" />
    <alipay v-model:show="showCreateBank3" @done="loadBank" />
    <VerificationMail v-model:show="showVerifyBank" @done="loadBank" :id="verifyBankId" />
  <ServiceChargeTips v-model:show="showServiceChargeTips" @done="goStep2" :num="num" :service_charge="service_charge" />
</template>

<script setup>
import { defineModel, watch } from "vue"
import { useLocale } from 'element-plus'
import { serverLang } from '@/utils/i18n'
import { getTemplateDetailByCode, getExchangeRate, getPersonalAuthStatus, getOtFundConfig, getIfChargeCommission } from '@/api/common'
import { saveGoldOut, getIbFundSum } from '@/api/ib'
import { queryBankList } from '@/api/personal'
import { isEmpty, returnFloat, returnFloat3, round } from '@/utils/htfx'
import { eventBus } from '@/utils/event-bus';
import choose from "../personal/wallet/choose"
import bank from "../personal/wallet/bank"
import digital from "../personal/wallet/digital"
import alipay from "../personal/wallet/alipay"
import VerificationMail from "./verificationMail.vue"
import ServiceChargeTips from "./serviceChargeTips.vue";

const { proxy } = getCurrentInstance();
const { t } = useLocale()
const active = ref(false)
const step = ref(1)
const templateContent = ref(null)
const authStatus = ref(null)

const progress = computed(() => {
    if (!authStatus.value) {
        return 0
    }
    return (authStatus.value.address?1:0) +
    (authStatus.value.identity?1:0) +
    (authStatus.value.email?1:0) 
})

const props = defineProps({
    ioPowerMap: {
        type: Object,
        default: {}
    }
})

const payLoading = ref(false)
const bankList = ref([])
const bankIndex = ref(null)
const currencyList = ref([])
const exchangeRate = ref(null)
let exchange_rate_sign = null
const verifyBankId = ref(null)
let otFundConfig = {}
const inAmountPlaceholder = ref(null)
const errorMsg = ref('')
const checkUsdAmount = (rule, value, callback) => {
    if (value <= 0) {
        errorMsg.value = ''
        callback(new Error(''))
    } else {
        //跟系统配置对比
        let min_out = parseFloat(returnFloat(otFundConfig.sys_min_out));
        let max_out = parseFloat(returnFloat(otFundConfig.sys_max_out));
        if(max_out==0) max_out=99999999.00;
        let balance = form.value.mt4_balance
        //跟余额对比
        if(parseFloat(value)>parseFloat(balance)){
            errorMsg.value = t('common.error.amountRange3', {balance: balance})
            callback(new Error(t('common.error.amountRange3', {balance: balance})))
            return
        }
        if(parseFloat(value)<min_out || parseFloat(value)>max_out){
            errorMsg.value = t('common.error.minOutAmount', {min: min_out})
            callback(new Error(t('common.error.minOutAmount', {min: min_out})))
            return
        }
        errorMsg.value = ''
        callback()
    }
}

const d = reactive({
  form: {
    mt4_balance: 0,
    remark: null,
    currency_type: null,
    usd_amount: null,
    bank_no: null
  },
  rules: {
    bank_no: [{ required: true, message: "", trigger: "blur" }],
    usd_amount: [
        { required: true, message: "", trigger: "blur" },
        { type: "number", validator: checkUsdAmount, trigger: "blur" }
    ],
    currency_type: [{ required: true, message: "", trigger: "blur" }]
  },
  form2: {
    safe_pass: undefined
  },
  rules2: {
    safe_pass: [{ required: true, message: "", trigger: "blur" }]
  }
});

const { form, rules, form2, rules2 } = toRefs(d);

function reset() {
    step.value = null
    active.value = false
    inAmountPlaceholder.value = null
    loadBank()
    form.value = {
        mt4_balance: 0,
        remark: null,
        currency_type: null,
        usd_amount: null,
        bank_no: null
    }
    form2.value = {
        safe_pass: undefined
    }
}

watch(active, (n, o) => {
    if (n) {
        step.value = null
        getPersonalAuthStatus().then(resp => {
            step.value = (resp.data.address==1 && resp.data.identity==1 && resp.data.email==1) ? 1 : 0
            authStatus.value = resp.data
        })
    }
}, {immediate: true})

function handleBankChange() {
    if (bankIndex.value == null || bankIndex.value < 0 || !bankList.value || !bankList.value.length) {
        currencyList.value = []
        form.value.currency_type = undefined
        form.value.bank_no = undefined
    } else {
        if (bankList.value[bankIndex.value].bank_currency) {
            currencyList.value = bankList.value[bankIndex.value].bank_currency.split(',')
            form.value.currency_type = currencyList.value[0]
            form.value.bank_no = bankList.value[bankIndex.value].bank_no
        } else {
            currencyList.value = []
            form.value.currency_type = undefined
            form.value.bank_no = undefined
        }
        currencyTypeChange()
    }
}

const currencyAmount = computed(() => {
    if (!exchangeRate.value || isNaN(exchangeRate.value) || exchangeRate.value <= 0) {
        return 0
    }
    if (isEmpty(form.value.usd_amount)) {
        return 0
    }
    let usd_amount = parseFloat(form.value.usd_amount)
    let currency_amount = returnFloat3(exchangeRate.value * usd_amount)
    return currency_amount
})

function selectChannel() {
    active.value = !!!active.value
}

function handleAmount(v) {
    if (v < 0) {
        form.value.usd_amount = 0
    }
}

function handleCurrencyTypeChange() {
    currencyTypeChange()
}

function currencyTypeChange() {
    if (isEmpty(form.value.currency_type)) {
        exchangeRate.value = null
    } else {
        getExchangeRateByUSD()
    }
}

function getExchangeRateByUSD() {
    getExchangeRate({
        exchange_currency: form.value.currency_type,
        type: 'crm',
        io: 'o'
    }).then(resp => {
        let rs = resp.data
        let exchange_rate = rs.exchange_rate;
        if(parseFloat(exchange_rate)<=0) {
            window.showTip({
                titleCode: 'capital.noSetExchangeRate',
                status: 'error'
            })
            exchangeRate.value = null
        } else {
            exchangeRate.value = exchange_rate
            exchange_rate_sign = rs.exchange_rate_sign
        }
    })
}

function loadBank() {
    bankIndex.value = null
    queryBankList().then(resp => {
        bankList.value = resp.data
        handleBankChange()
    })
}

const showServiceChargeTips = ref(false)
const num = ref(null)
const service_charge = ref(null)
function loadOutServiceChargeTips() {
  getIfChargeCommission().then(resp => {
    let data = resp.data;
    if (data && data.ifChargeCommission) {
      num.value = data.num
      service_charge.value = data.service_charge
      showServiceChargeTips.value = true
    }else {
      goStep2()
    }
  })
}

const showAddBank = ref(false)
const showCreateBank1 = ref(false)
const showCreateBank2 = ref(false)
const showCreateBank3 = ref(false)

function openAddBank() {
    showAddBank.value = true
}

function handleChooseAddBank(type) {
    if (type == 'B1') {
        showCreateBank2.value = false
        showCreateBank3.value = false
        showCreateBank1.value = true
    } else if (type == 'B2') {
        showCreateBank1.value = false
        showCreateBank3.value = false
        showCreateBank2.value = true
    } else if (type == 'B3') {
        showCreateBank1.value = false
        showCreateBank2.value = false
        showCreateBank3.value = true
    }
}

const showVerifyBank = ref(false)

function goStep2() {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            const bank = bankList.value[bankIndex.value]
            // 是否需要邮箱验证
            if (bank.bank_standby_1 != 'B1' && bank.verify_email == 0) {
                verifyBankId.value = bank.id
                showVerifyBank.value = true
            } else {
                step.value = 2
                form2.value.safe_pass = undefined
            }
        }
    })
}

function goStep1() {
    step.value = 1
}

function doGoldOut() {
    proxy.$refs["formRef2"].validate(valid => {
        if (valid) {
            const bank = bankList.value[bankIndex.value]
            payLoading.value = true
            proxy.loading.show()
            const { usd_amount, currency_type, remark } = form.value
            const { safe_pass } = form2.value
            saveGoldOut({
                usd_amount, currency_type, remark, 
                bank_no: bank.bank_no, bank_name: bank.bank_name, bank_sub_name: bank.bank_sub_name, bank_cards: bank.bank_cards, bank_swift: bank.bank_swift, bank_remark: bank.bank_remark,
                exchange_rate: exchangeRate.value,
                currency_amount: currencyAmount.value,
                qcc_language: serverLang(),
                exchange_rate_sign: exchange_rate_sign,
                safe_pass
            }).then(resp => {
                step.value = 3
                payLoading.value = false
                proxy.loading.hide()
                eventBus.$emit('fund-event');
            }).catch(() => {
                payLoading.value = false
                proxy.loading.hide()
                eventBus.$emit('fund-event');
            })
        }
    })
}

function loadFund() {
    getIbFundSum().then(resp => {
        form.value.mt4_balance = resp.data.amount
    })
}

function loadOtFundConfig() {
    getOtFundConfig().then(resp => {
        if (resp.data) {
            let rs = resp.data
            for(let i=0;i<rs.length;i++){
                otFundConfig[rs[i].sub_type]=rs[i].text;
            }
            let sys_min_out = isEmpty(otFundConfig.sys_min_out)?'0.00': otFundConfig.sys_min_out;
            let sys_max_out = isEmpty(otFundConfig.sys_max_out)?'0.00': otFundConfig.sys_max_out;
            if (sys_min_out) {
                inAmountPlaceholder.value = t('common.error.minOutAmount', {min: sys_min_out})
            } else {
                inAmountPlaceholder.value = ''
            }
        }
    })
}

loadBank()
loadFund()
loadOtFundConfig()
getTemplateDetailByCode({
    qcc_language: serverLang(),
    templateCode: 'COM_OUT'
}).then(resp => {
    templateContent.value = resp.data.content
})
</script>

<style lang="scss" scoped>
.channel-wrap {
    width: 100%;
    margin-bottom: 10px;
    margin-left: -12px;

    .channel-tab-line {
        width: 100%;
        display: flex;
        flex-wrap: nowrap;
        overflow: hidden;
    }

    .channel-tab {
        width: 390px;
        height: 105px;
        border-radius: 8px 8px 8px 8px;
        background-color: #fff;
        box-shadow: 0px 2px 9px  rgba(0, 0, 0, 0.1);
        // display: flex;
        // align-items: center;
        font-size: 22px;
        padding: 0 20px;
        margin-top: 12px;
        margin-left: 12px;
        margin-bottom: 12px;
        user-select: none;
        cursor: pointer;
        position: relative;

        .channel-icon {
            width: 80px;
            height: 80px;
            margin-right: 30px;
        }

        .channel_name {
            width: 200px;
            font-size: 22px;
            font-weight: 700;
            letter-spacing: 0px;
            color: rgba(51, 51, 51, 1);
        }
    }

    .channel-tab:not(:last-child) {
        margin-right: 20px;
    }

    .tab-active {
        // padding-bottom: 12px;
        // height: 117px;
        // margin-bottom: 0;
        box-shadow: none;
        border-radius: 8px 8px 0 0;
    }

    .active-overlay {
        position: absolute;
        top: 0;
        width: 100%;
        bottom: -20px;
        left: 0;
        box-shadow: 0px 2px 9px  rgba(0, 0, 0, 0.1);
        background-color: transparent;
        border-radius: 8px 8px 0 0;
        z-index: 2;
    }

    .active-overlay::after {
        content: '';
        position: absolute;
        bottom: 0;
        width: 100%;
        background: #fff;
        left: 0;
        height: 20px;
    }

    .channel-pannel {
        width: 100%;
        min-height: 500px;
        margin-left: 12px;
        margin-bottom: 40px;
        box-shadow: 0px 2px 9px  rgba(0, 0, 0, 0.1);

        .pay-form {
            // background-color: #d64a4a;
            min-height: 500px;
            width: 100%;
            padding: 50px 80px;
            position: relative;
        }

        .pay-form::after {
            position: absolute;
            right: 0;
            top: 50px;
            bottom: 50px;
            content: '';
            width: 1px;
            background-color: rgba(204, 204, 204, 1);
        }
    }
}

.goldin-form {
    width: 100%;
    position: relative;
}

.goldin-form::after {
    position: absolute;
    right: 0;
    top: 50px;
    bottom: 50px;
    content: '';
    width: 1px;
    background-color: rgba(204, 204, 204, 1);
}

.currency-amount {
    font-size: 36px;
    font-weight: 700;
    letter-spacing: 0px;
    // line-height: 55.02px;
    color: rgba(41, 187, 228, 1);
}

.sub-btn {
    width: 100%;
    height: 40px;
    margin-top: 50px;
}


.template-content {
    padding: 50px 50px;
}

.template-content > div {
    font-size: 14px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 27px;
    color: rgba(170, 170, 170, 1);
    text-align: left;
}
</style>
<style>
.goldin-form .el-input-number .el-input__inner {
    text-align: left;
}
</style>