<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="trans" class="channel-icon" />
                    <div>
                        <div class="channel_name">{{ t('capital.trans') }}</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">
                    <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.gold_transfer_own) && ioPowerMap.gold_transfer_own==1 && !isEmpty(ioPowerMap.gold_transfer_out) && ioPowerMap.gold_transfer_out==1) ||
                                    (ioPowerMap!=null && (ioPowerMap.out_flag == false || ioPowerMap.out_flag == 'false'))" >
                                        <el-col :md="24" :lg="12" >
                                            <el-form-item :label="t('capital.mt4_login_out')" prop="mt4_login_out" >
                                                <el-select
                                                    v-model="queryMtAccountIndex"
                                                :placeholder="t('common.selectChoose')"
                                                clearable
                                                @clear="queryMtAccountIndex = null"
                                                style="width: 100%"
                                                >
                                                    <el-option :disabled="index == queryMtAccountIndex2" v-for="(item, index) in mtAccountList" :key="index" :label="item.mt4_server_name + ' ' + item.mt4_login" :value="index" ></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :md="24" :lg="12" >
                                            <el-form-item :label="t('capital.transAmount')" >
                                                <div class="currency-amount">{{ '$' + form.mt4_balance }}</div>
                                            </el-form-item>
                                        </el-col>

                                        <el-col :md="24" :lg="12" >
                                          <el-form-item :label="t('form.transType.label')" prop="transfer_type">
                                            <el-select
                                                v-model="form.transfer_type"
                                                :placeholder="t('common.selectChoose')"
                                                clearable
                                                style="width: 100%"
                                                @change="handleChangeType"
                                            >
                                              <el-option
                                                  v-if="(ioPowerMap.gold_transfer_own!=1)"
                                                  :disabled="(ioPowerMap!=null && (ioPowerMap.out_flag == false || ioPowerMap.out_flag == 'false'))"
                                                  :label="t('form.transType.0')" :value="0"></el-option>
                                              <el-option
                                                  v-if="(ioPowerMap!=null && !isEmpty(ioPowerMap.gold_transfer_out) && ioPowerMap.gold_transfer_out==0)"
                                                  :disabled="(ioPowerMap!=null && (ioPowerMap.out_flag == false || ioPowerMap.out_flag == 'false'))"
                                                  :label="t('form.transType.1')" :value="1 "></el-option>

                                            </el-select>
                                          </el-form-item>
                                        </el-col>

                                      <el-col :md="24" :lg="12" v-if="showTransferOut">
                                        <el-form-item :label="t('capital.mt4_server')" prop="mt4_server_in" >
                                          <el-select
                                              v-model="form.mt4_server_in"
                                              :placeholder="t('common.selectChoose')"
                                              :clearable="false"
                                              style="width: 100%"
                                          >
                                            <el-option v-for="(item, index) in mtServerList" :key="index" :label="item.server_name" :value="item.id" ></el-option>
                                          </el-select>
                                        </el-form-item>
                                      </el-col>
                                      <el-col :md="24" :lg="12" v-if="showTransferOut">
                                        <el-form-item :label="t('capital.mt4_login')" prop="mt4_login_in" >
                                          <el-input v-model="form.mt4_login_in" style="width: 100%"></el-input>
                                        </el-form-item>
                                      </el-col>
                                      <el-col :md="24" :lg="12" v-if="showTransferOut">
                                        <el-form-item :label="t('form.mtAccountName.label')" prop="mt4_login_name" :rules="form.transfer_type == 1?[{ required: true, message: '', trigger: 'change' }]:[{required: false}]">
                                          <el-input v-model="form.mt4_login_name" style="width: 100%" ></el-input>
                                        </el-form-item>
                                      </el-col>

                                        <el-col :md="24" :lg="12" v-if="showTransferOwn">
                                            <el-form-item :label="t('capital.mt4_login_in')" prop="mt4_login_in" >
                                                <el-select
                                                    v-model="queryMtAccountIndex2"
                                                :placeholder="t('common.selectChoose')"
                                                clearable
                                                @clear="queryMtAccountIndex2 = null"
                                                style="width: 100%"
                                                >
                                                    <el-option :disabled="index == queryMtAccountIndex" v-for="(item, index) in mtAccountList" :key="index" :label="item.mt4_server_name + ' ' + item.mt4_login" :value="index" ></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :md="24" :lg="12" >
                                            <el-form-item :label="t('capital.usdAmount')" 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-form-item  style="width: 100%;">
                                            <el-button :loading="payLoading" 
                                            :disabled="!form.usd_amount || form.usd_amount < 0 || 
                                            (ioPowerMap!=null && !isEmpty(ioPowerMap.gold_transfer_own) && ioPowerMap.gold_transfer_own==1 && !isEmpty(ioPowerMap.gold_transfer_out) && ioPowerMap.gold_transfer_out==1) ||
                                            (ioPowerMap!=null && (ioPowerMap.out_flag == false || ioPowerMap.out_flag == 'false'))" 
                                            class="sub-btn" type="primary" @click="goStep2" >{{ 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.transDesc', {out: form.mt4_login_out, in: form.mt4_login_in}) }}</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="handleSubmit" >{{ 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.trans-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>
</template>

<script setup>
import { defineModel, watch } from "vue"
import { useLocale } from 'element-plus'
import { serverLang } from '@/utils/i18n'
import { getTemplateDetailByCode, getMtTableInfo2, queryByMt4Login, getPersonalAuthStatus,mtServer as getMtServer } from '@/api/common'
import { saveTransfer } from '@/api/transfer'
import { isEmpty, returnFloat, returnFloat3, round } from '@/utils/htfx'

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

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

const showTransferOut = ref(false)
const showTransferOwn = ref(false)
const payLoading = ref(false)
const mtAccountList = ref([])
const mtServerList = ref([])
const queryMtAccountIndex = ref(null)
const queryMtAccountIndex2 = ref(null)

let ioGoldConf = {}
const inAmountPlaceholder = ref(null)
const errorMsg = ref('')
const checkUsdAmount = (rule, value, callback) => {
    let ioThreshold = ioGoldConf[form.value.mt4_server_out+":"+form.value.mt4_login_out];
    if (!ioThreshold) {
        errorMsg.value = ''
        callback()
        return
    }
    if (value <= 0) {
        errorMsg.value = ''
        callback(new Error(''))
    } else {
        if(isEmpty(ioThreshold)) ioThreshold={};
        //跟系统配置对比
        let min_out = parseFloat(returnFloat(ioThreshold.tran_min));
        let max_out = parseFloat(returnFloat(ioThreshold.tran_max));
        if(isEmpty(min_out)) min_out=0.00;
        if(max_out==0) max_out=99999999.00;
        if(parseFloat(value)<min_out){
            errorMsg.value = t('common.error.minTransAmount', {min: min_out})
            callback(new Error(t('common.error.minTransAmount', {min: min_out})))
        } else {
            errorMsg.value = ''
            callback()
        }
    }
}

const d = reactive({
  form: {
    mt4_balance: 0,
    mt4_server_out: undefined,
    mt4_login_out: undefined,
    transfer_type: undefined,
    mt4_server_in: undefined,
    usd_amount: undefined,
    mt4_login_in: undefined,
    mt4_login_name: undefined
  },
  rules: {
    mt4_server_out: [{ required: true, message: "", trigger: "blur" }],
    mt4_login_out: [{ required: true, message: "", trigger: "blur" }],
    transfer_type: [{ required: true, message: "", trigger: "blur" }],
    mt4_server_in: [{ required: true, message: "", trigger: "blur" }],
    mt4_login_in: [{ required: true, message: "", trigger: "blur" }],
    usd_amount: [
        { required: true, message: "", trigger: "blur" },
        { type: "number", validator: checkUsdAmount, trigger: "blur" }
    ]
  },
  form2: {
    safe_pass: undefined
  },
  rules2: {
    safe_pass: [{ required: true, message: "", trigger: "blur" }]
  }
});

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

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
        })
        loadMtAccountList()
    }
    form2.value.safe_pass = undefined
}, {immediate: true})

watch(queryMtAccountIndex, (n, o) => {
  if(n == null || n < 0 || !mtAccountList.value || !mtAccountList.value.length) {
    form.value.mt4_server_out = undefined
    form.value.mt4_login_out = undefined
    form.value.mt4_balance = 0
  } else {
    const { mt4_login, mt4_server, margin_free, margin, mt4_credit, ifCent } = mtAccountList.value[queryMtAccountIndex.value]
    form.value.mt4_server_out = mt4_server
    form.value.mt4_login_out = mt4_login
    let mt4_balance = '0.00'
    mt4_balance = Math.floor((parseFloat(returnFloat(margin_free))-parseFloat(returnFloat(margin))-parseFloat(returnFloat(mt4_credit)))*100)/100;
    // 如果是美分账户，需要除100
    if(!isEmpty(ifCent) && ifCent=='YES') {
        mt4_balance = returnFloat(parseFloat(mt4_balance)/100);
    }
    form.value.mt4_balance = mt4_balance
  }
  getIoGoldConfig()
}, { immediate: true })

watch(queryMtAccountIndex2, (n, o) => {
  if(n == null || n < 0 || !mtAccountList.value || !mtAccountList.value.length) {
    form.value.mt4_server_in = undefined
    form.value.mt4_login_in = undefined
  } else {
    const { mt4_login, mt4_server } = mtAccountList.value[queryMtAccountIndex2.value]
    form.value.mt4_server_in = mt4_server
    form.value.mt4_login_in = mt4_login
  }
}, { immediate: true })

function handleChangeType(value) {
  form.value.mt4_server_in = undefined
  form.value.mt4_login_in = undefined
  form.value.mt4_login_name = undefined
  if(value == 0) {
    showTransferOut.value = false
    showTransferOwn.value = true
  }else if (value == 1){
    showTransferOut.value = true
    showTransferOwn.value = false
    if (!mtServerList.value || !mtServerList.value.length){
      getTransOutMtServer()
    }
  }else {
    showTransferOut.value = false
    showTransferOwn.value = false
  }
}

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

function reset() {
    step.value = null
    active.value = false
    queryMtAccountIndex.value = null
    queryMtAccountIndex2.value = null
    loadMtAccountList()
    form.value = {
        mt4_balance: 0,
        mt4_server_out: undefined,
        mt4_login_out: undefined,
        transfer_type: undefined,
        mt4_server_in: undefined,
        usd_amount: undefined,
        mt4_login_in: undefined,
        mt4_login_name: undefined
    }
    form2.value = {
        safe_pass: undefined
    }
    inAmountPlaceholder.value = null
}

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

function getTransOutMtServer() {
  getMtServer({
    qcc_language: serverLang(),
    server_type: 'live'
  }).then(resp => {
    mtServerList.value = resp.data
  })
}

function loadMtAccountList() {
  getMtTableInfo2({
    mt4_server: '',
    language: serverLang(),
    server_type: 'live'
  }).then(resp => {
    if (resp.data) {
      mtAccountList.value = resp.data;
      if (resp.data && resp.data.length) {
        for (let index = 0; index < resp.data.length; index++) {
            const element = resp.data[index];            
              if (props.mtLogin == element.mt4_login && props.mtServer == element.mt4_server) {
                queryMtAccountIndex.value = index
                break
              }
        }
      }
    }
  })
}

function getIoGoldConfig() {
    if (isEmpty(form.value.mt4_server_out)) {
        inAmountPlaceholder.value = ''
        return
    }
    if (!isEmpty(form.value.mt4_server_out) && !isEmpty(form.value.mt4_login_out) && !isEmpty(ioGoldConf[form.value.mt4_server_out+':'+form.value.mt4_login_out])) {
        let ioThreshold = ioGoldConf[form.value.mt4_server_out+':'+form.value.mt4_login_out]
        if(isEmpty(ioThreshold)) {
            inAmountPlaceholder.value = ''
            return
        }
        let min_tran = parseFloat(returnFloat(ioThreshold.tran_min));
        let max_tran = parseFloat(returnFloat(ioThreshold.tran_max));
        if(max_tran==0) max_tran=99999999.00;
        if (min_tran) {
            inAmountPlaceholder.value = t('common.error.minTransAmount', {min: min_tran})
        } else {
            inAmountPlaceholder.value = ''
        }
        return
    }
    queryByMt4Login({
        mt4_server: form.value.mt4_server_out,
        mt4_login: form.value.mt4_login_out
    }).then(resp => {
        ioGoldConf[form.value.mt4_server_out + ':' + form.value.mt4_login_out] = resp.data
        let ioThreshold = resp.data
        if(isEmpty(ioThreshold)) {
            inAmountPlaceholder.value = ''
            return
        }
        let min_tran = parseFloat(returnFloat(ioThreshold.tran_min));
        let max_tran = parseFloat(returnFloat(ioThreshold.tran_max));
        if(max_tran==0) max_in=99999999.00;
        if (min_tran) {
            inAmountPlaceholder.value = t('common.error.minTransAmount', {min: min_tran})
        } else {
            inAmountPlaceholder.value = ''
        }
    })
}

function goStep2() {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            step.value = 2
            form2.value.safe_pass = undefined
        }
    })
}

function goStep1() {
    step.value = 1
}

function handleSubmit() {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            proxy.$refs["formRef2"].validate(valid => {
                if (valid) {
                    payLoading.value = true
                    proxy.loading.show()
                    const { mt4_server_out, mt4_login_out, transfer_type, mt4_server_in, usd_amount, mt4_login_in,mt4_login_name } = form.value
                    const { safe_pass } = form2.value
                    saveTransfer({
                        qcc_language: serverLang(),
                        mt4_login_out,
                        mt4_server_out,
                        transfer_type,
                        mt4_login_in,
                        mt4_server_in,
                        mt4_login_name,
                        usd_amount,
                        safe_pass
                    }).then(resp => {
                        step.value = 3
                        payLoading.value = false
                        proxy.loading.hide()
                    }).catch(() => {
                        payLoading.value = false
                        proxy.loading.hide()
                    })
                }
            })
        }
    })
}

getTemplateDetailByCode({
    qcc_language: serverLang(),
    templateCode: 'TRANSFER'
}).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;
        }
    }
}

.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>