<template>
  <NavBar />
  <view class="container">
    <view class="title">
      <PageTitle :title="$t('home.apply.title')" />
      <text class="rightTitle">{{ $t('home.apply.salesWithdraw') }}</text>
    </view>

    <view class="bankRow" v-show="!show">
      <view class="bankItem" v-for="bank in bankList" @click="showDetails(bank)">
        <image src="/static/bankIcon.svg" mode="aspectFit" style="width: 36px;height: 36px"></image>
        <text class="bankNo">{{ bank.bank_no }}</text>
        <image src="/static/unfold.svg" class="rightIcon" mode="aspectFit" style="width: 8px;height: 14px"></image>
      </view>
    </view>

    <view class="outDetails" v-show="show">
      <view class="bankItem" @click="hideDetails">
        <image src="/static/bankIcon.svg" mode="aspectFit" style="width: 36px;height: 36px"></image>
        <text class="bankNo">{{ outParams.bank_no }}</text>
        <image src="/static/unfold.svg" class="rightIcon" mode="aspectFit" style="width: 8px;height: 14px"></image>
      </view>
      <view class="outContent">
        <uni-forms ref="withdrawForm" :modelValue="outParams" :rules="withdrawFormRules">
          <uni-forms-item name="currency_type">
            <view class="row">
              <view class="column">{{ $t('home.apply.salesWithdrawPage.currencyType') }}</view>
              <view class="value">
                <uni-data-select
                    :placeholder="$t('form.pleaseSelect')"
                    :localdata="currencyTypeList"
                    v-model="outParams.currency_type"
                    onchange="getExchangeRate"
                ></uni-data-select>
              </view>
            </view>
          </uni-forms-item>

          <uni-forms-item>
            <view class="row">
              <view class="column">{{ $t('home.apply.salesWithdrawPage.balance') }}</view>
              <view class="value">
                <text style="color: #29BBE4;font-size: 20px;font-weight: 700;">{{ '$'+this.balance }}</text>
              </view>
            </view>
          </uni-forms-item>

          <uni-forms-item name="usd_amount">
            <view class="row">
              <view class="column">{{ $t('home.apply.salesWithdrawPage.usdAmount') }}</view>
              <view class="value" style="position: relative">
                <view>
                  <input type="number" class="filterInput" v-model="outParams.usd_amount" :placeholder="$t('form.pleaseEnter')">
                </view>
                <view :class="['minAmount', amountAvailable ? '' : 'unavailable']">{{ unavailableAmountTip }}</view>
                <text style="position: absolute;right: 25px;top:5px;color: #29BBE4;font-size: 14px;font-weight: 400;">USD</text>
              </view>
            </view>
          </uni-forms-item>

          <uni-forms-item>
            <view class="row">
              <view class="column" >{{ $t('home.apply.salesWithdrawPage.exchangeRate') }}<image src="/static/exchangeRateTips.svg" mode="aspectFit" style="width: 12px;height: 12px;padding-left: 5px;"></image></view>
              <view class="value">
                <text style="color: #333333;font-size: 14px;font-weight: 400;">{{ outParams.exchange_rate }}</text>
              </view>
            </view>
          </uni-forms-item>

          <uni-forms-item>
            <view class="row">
              <view class="column">{{ $t('home.apply.salesWithdrawPage.currencyAmount') }}</view>
              <view class="value">
                <text style="color: #333333;font-size: 16px;font-weight: 400;">{{ this.outParams.currency_amount }}</text>
              </view>
            </view>
          </uni-forms-item>

          <uni-forms-item name="safe_pass">
            <view class="row">
              <view class="column">{{ $t('home.apply.salesWithdrawPage.safePass') }}</view>
              <view class="value">
                <uni-easyinput
                    class="uni-mt-5"
                    type="password"
                    trim="all"
                    primaryColor="#29BBE4"
                    v-model="outParams.safe_pass"
                ></uni-easyinput>
              </view>
            </view>
          </uni-forms-item>
        </uni-forms>
      </view>
    </view>


    <view style="padding-top: 24px" v-show="show">
      <button class="btn primaryButton" @click="saveOut()" >
        <image v-show="btnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
        {{ $t('form.save') }}
      </button>
    </view>

  </view>
</template>

<script>
import { getSelfBank, getExchangeRate, getUerBalance, getIfOTParamse, saveFundOut } from '@/services/capital/salesWithdraw.ts';
import { getSys } from '@/services/common.ts';
import UniDataSelect from "../../../uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
import { UserLanguage } from '@/utils/const';

export default {
  components: {UniDataSelect},
  data() {
    return{
      show:false,
      bankList:[],
      outParams:{
        usd_amount:null,
        remark:null,
        currency_type:null,
        exchange_rate:null,
        currency_amount:0,
        safe_pass:null,
        exchange_rate_sign:null,
        bank_no:null,
        bank_cards:null,
        bank_name:null,
        bank_sub_name:null,
        bank_swift:null,
        bank_remark:null
      },
      balance:0,
      goldRange: null,
      amountAvailable: true,
      unavailableAmountTip: '',
      currencyTypeList:[],
      btnLoading: false,
      saveDisabled:true,
      withdrawFormRules: {
        usd_amount: {
          rules: [
            {
              required: true,
              errorMessage: this.$t('form.amount.required')
            },
            {
              validateFunction: (rule, value, data, callback) => {
                // 异步需要返回 Promise 对象
                return new Promise((resolve, reject) => {
                  setTimeout(() => {
                    if (Number(value) < this.goldRange?.sys_min_out) {
                      // 不通过返回 reject(new Error('错误信息'))
                      this.amountAvailable = false;
                      reject(new Error(' '));
                    } else if (Number(value) > (this.balance ?? 0)) {
                      this.amountAvailable = false;
                      reject(new Error(' '));
                      this.unavailableAmountTip = `${this.$t('withdrawal.maxAmount')} $${this.balance ?? 0}`;
                    } else {
                      // 通过返回 resolve
                      this.amountAvailable = true;
                      resolve();
                    }
                  }, 0);
                });
              }
            }
          ]
        },
        currency_type: {
          rules: [
            {
              required: true,
              errorMessage: this.$t('form.currencyType.required')
            }
          ]
        },
        safe_pass: {
          rules: [
            {
              required: true,
              errorMessage: this.$t('form.CRMPassword.required')
            }
          ]
        }
      }
    }
  },
  methods:{
    async getSelfBank(){
      const res = await getSelfBank()
      if (res && res.code === 0) {
        this.bankList = res.data;
      }
    },
    showDetails(bank){
      this.outParams.bank_no = bank.bank_no
      this.outParams.currency_type = bank.bank_currency
      this.outParams.bank_cards = bank.bank_cards
      this.outParams.bank_name = bank.bank_name
      this.outParams.bank_sub_name = bank.bank_sub_name
      this.outParams.bank_swift = bank.bank_swift
      this.outParams.bank_remark = bank.bank_remark

      this.currencyTypeList[0] = {text: bank.bank_currency,value: bank.bank_currency}
      this.getExchangeRate()
      this.show = true
    },
    hideDetails() {
      this.show = false
    },
    async getExchangeRate(){
      if (this.outParams.currency_type == null || this.outParams.currency_type == ''){
        this.outParams.exchange_rate = ''
        this.outParams.exchange_rate_sign = ''
        return
      }
      const res = await getExchangeRate({
        exchange_currency:this.outParams.currency_type,
        type:"crm",
        io:"o"
      })
      if (res && res.code === 0) {
        this.outParams.exchange_rate = res.data.exchange_rate
        this.outParams.exchange_rate_sign = res.data.exchange_rate_sign
      }
    },
    async getUerBalance(){
      const res = await getUerBalance()
      if (res && res.code === 0) {
        this.balance = res.data.balance
      }
    },
    async getGoldRangeData() {
      const res = await getSys();
      if (res && res.code === 0) {
        const temp = {};
        res.data.forEach((item) => {
          temp[item.sub_type] = item.text;
        });
        this.goldRange = temp;
      }
    },
    async saveOut (){
      this.btnLoading = true
      this.$refs.withdrawForm.validate().then(async (fields) => {
        this.submitBtnLoading = true;
        const res = await saveFundOut(this.outParams);
        this.submitBtnLoading = false;
        if (res && res.code === 0) {
          uni.redirectTo({
            url: '/pages/capital/salesWithdraw/success/index'
          });
        } else {
          this.$nextTick(() => {
            this.$cusModal.showModal({
              type: 'message',
              status: 'warning',
              contentText: res.msg ?? this.$t('common.error.sysError')
            });
          })
        }
      });
      this.btnLoading = false
    }
  },
  created() {
    this.getSelfBank()
    this.getUerBalance()
    this.getGoldRangeData()
  },
  mounted() {
  },
  watch: {
    'outParams.usd_amount': {
      handler(newVal, oldVal) {
        this.outParams.currency_amount = this.outParams.exchange_rate && newVal ? this.outParams.exchange_rate * newVal : undefined;
      }
    },
    goldRange: {
      handler(newVal, oldVal) {
        this.unavailableAmountTip = `${this.$t('withdrawal.minAmount')} $${this.goldRange?.sys_min_out??0}`;
      }
    },
    exchangeRate: {
      handler(newVal, oldVal) {
        this.outParams.currency_amount = newVal && this.outParams.usd_amount ? (newVal * this.outParams.usd_amount).toFixed(2) : '-';
      }
    }
  }

};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
