<template>
  <div class="page" v-loading.body.fullscreen="fullscreenLoading" element-loading-background="rgba(255, 255, 255, 0)">
    <van-sticky class="sticky">
      <div class="header flex">
        <div class="back">
          <backIcon/>
        </div>
        <!-- 货币兑换 -->
        {{ $t('account.l38') }}
        <div class="right-box flex">
          <searchIcon width="20px"/>
          <van-popover
            v-model="showPopover"
            placement="bottom-end"
            trigger="click"
          >
            <div class="popover-body">
              <div class="item flex" @click="goDepositUrl('/deposit')">
                <img class="icon14" src="/img/account/icon14.png" alt="极度证券">
                <div>
                  <!-- 存款 -->
                  {{ $t('home.l13') }}
                </div>
              </div>
              <div class="item flex" @click="$router.push('/withdraw')">
                <img class="icon14" src="/img/account/icon15.png" alt="极度证券">
                <div>
                  <!-- 划转 -->
                  {{ $t('home.l15') }}
                </div>
              </div>
              <div class="item flex" @click="$router.push('/chat')">
                <img class="icon14" src="/img/account/icon17.png" alt="极度证券">
                <div>
                  <!-- 客服 -->
                  {{ $t('home.l16') }}
                </div>
              </div>
              <div class="item flex" @click="$router.replace('/')">
                <img class="icon14" src="/img/account/icon16.png" alt="极度证券">
                <div>
                  <!-- 首页 -->
                  {{ $t('tab.tab1') }}
                </div>
              </div>
            </div>
            <template #reference>
              <img class="more" src="/img/icon/more.png" alt="极度证券"/>
            </template>
          </van-popover>
        </div>
      </div>
      
    </van-sticky>
    <div class="container">
      <div class="box flex">
        <div class="flex" @click="accountShow('formInfo')">
          <van-image
            v-if="formInfo.uid || formInfo.id"
            width="24"
            height="24"
            round
            fit="cover"
            :src="`/img/user/${formInfo.server ? formInfo.server : 'usd'}.png?14`"
          />
          <div v-if="formInfo.uid || formInfo.id">
            <!-- 美元钱包账户 -->
            {{ serverName[formInfo.server] || $t('account.l1') }}
          </div>
          <div v-else class="place">
            <!-- 请选择 -->
            {{ $t('common.l51') }}
          </div>
          <i class="el-icon-arrow-right"></i>
        </div>
        <img class="convert" @click="convertAccount" src="/img/convert/icon1.png?1" alt="极度证券">
        <div class="flex" @click="accountShow('toInfo')">
          <van-image
            v-if="toInfo.uid || toInfo.id"
            width="24"
            height="24"
            round
            fit="cover"
            :src="`/img/user/${toInfo.server ? toInfo.server : 'usd'}.png?14`"
          />
          <div v-if="toInfo.uid || toInfo.id">
            <!-- 美元钱包账户 -->
            {{ serverName[toInfo.server] || $t('account.l1') }}
          </div>
          <div v-else class="place">
            <!-- 请选择 -->
            {{ $t('common.l51') }}
          </div>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="section">
        <div class="wrapper flex">
          <div class="title">
            <!-- 兑出 -->
            {{ $t('fund.l18') }}
          </div>
          <div class="flex" @click="accountShow('formInfo')">
            <van-image
              v-if="formInfo.uid || formInfo.id"
              width="16"
              height="16"
              round
              fit="cover"
              :src="`/img/user/${formInfo.server ? formInfo.server : 'usd'}.png?14`"
            />
            <div v-if="formInfo.uid || formInfo.id">{{ serverName[formInfo.server] || $t('account.l1') }}{{ formInfo.id ? `(${formInfo.account || formInfo.uid})` : '' }}</div>
            <div v-else class="place">
              <!-- 请选择 -->
              {{ $t('common.l51') }}
            </div>
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="input-box flex">
          <!-- 兑出金额 -->
          <van-field :placeholder="$t('fund.l19')" v-model="amount" type="number" />
          <div>{{ serverUtil[formInfo.server] || 'USD' }}</div>
        </div>
        <div class="row flex" v-if="formInfo.uid || formInfo.id">
          <div class="label">
            <!-- 可兑金额 -->
            {{ $t('fund.l20') }}
          </div>
          <div class="flex">
            {{ $numToThousand(formInfo.id ? formInfo.margin_free : formInfo.balance) }} {{ serverUtil[formInfo.server] || 'USD' }}
            <!-- <img class="info" src="/img/account/info.png" alt="极度证券"> -->
          </div>
        </div>
        <div class="row flex" v-if="(formInfo.uid || formInfo.id) && ((serverUtil[formInfo.server] || serverUtil[toInfo.server] || 'USD') != 'USD')">
          <div class="label">
            <!-- 参考汇率 -->
            {{ $t('fund.l21') }}
          </div>
          <div class="flex">
            1 USD = {{ rate }} {{ serverUtil[formInfo.server] || serverUtil[toInfo.server] || 'USD' }}
            <!-- <img class="info" src="/img/account/info.png" alt="极度证券"> -->
            <img class="reset" @click="getCurrencyList" src="/img/icon/reset.png" alt="极度证券">
          </div>
        </div>
      </div>
      <div class="section1">
        <div class="wrapper flex">
          <div>
            <!-- 预计兑入 -->
            {{ $t('fund.l22') }}
          </div>
          <div class="flex" @click="accountShow('toInfo')">
            <van-image
              v-if="toInfo.uid || toInfo.id"
              width="15"
              height="15"
              round
              fit="cover"
              :src="`/img/user/${toInfo.server ? toInfo.server : 'usd'}.png?14`"
            />
            <div v-if="toInfo.uid || toInfo.id">{{ serverName[toInfo.server] || $t('account.l1') }}{{ toInfo.id ? `(${toInfo.account || toInfo.uid})` : '' }}</div>
            <div v-else class="place">
              <!-- 请选择 -->
              {{ $t('common.l51') }}
            </div>
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="container1">
          <div class="input-box flex">
            <!-- 兑入金额 -->
            <van-field disabled :placeholder="$t('fund.l31')" v-model="toAmount1" type="number" />
            <div>{{ serverUtil[toInfo.server] || 'USD' }}</div>
          </div>
          <div class="row flex" v-if="classify[toInfo.market] || classify[formInfo.market]">
            <div class="label">
              <!-- 手续费率(USD) -->
              {{ $t('fund.l23') }}(USD)
            </div>
            <div>{{ classify[toInfo.market] || classify[formInfo.market] }}%</div>
          </div>
        </div>
      </div>
    </div>
    <div class="section2">
      <div class="btn" @click="submit">
        <!-- 申请兑换 -->
        {{ $t('fund.l24') }}
      </div>
      <div class="href" @click="$router.push('/account-records/3')">
        <!-- 兑换记录 -->
        {{ $t('fund.l25') }}
      </div>
      <div class="tips-title">
        <!-- 温馨提示 -->
        {{ $t('common.l1') }}
      </div>
      <div class="tips">
        <!-- 1.页面汇率仅供参考，实际的兑换汇率会随外汇牌价变化。 -->
        {{ $t('fund.l26') }}
      </div>
      <div class="tips">
        <!-- 2.页面完成时间仅供参考，请以实际完成时间为准， -->
        {{ $t('fund.l27') }}
        <span class="span">
          <!-- 查看说明 -->
          {{ $t('fund.l28') }}
        </span>
      </div>
      <div class="tips">
        <!-- 3.当账户内存在未完成结算和交收的资金，此部分资金皆不支持进行兑换。股票一般T日交易，T+2个交易日可完成交收，期货一般T日交易，T+1个交易日可完成交收。 -->
        {{ $t('fund.l29') }}
      </div>
      <div class="tips">
        <!-- 4.HKD=港元;USD=美元; CNH=离岸人民币; JPY=日元 -->
        {{ $t('fund.l30') }}
      </div>
    </div>
    <van-popup v-model="show" round position="bottom">
      <list :tragetInfo="tragetInfo" @success="selectBack"/>
    </van-popup>
    <!-- <authIdentity v-if="authShow" @cancel="authCancel" /> -->
    <van-popup v-model="depositPopShow" position="right" :style="{ width: '100%' }">
      <depositPop :url="depositUrl" @cancel="depositPopShow = false" />
    </van-popup>
  </div>
</template>
<script>
import list from "./components/list.vue";
import bus from '@/utils/bus'
import { mapGetters } from "vuex";
// import authIdentity from "@/components/authIdentity";
import { transactionToCash, cashToTransaction, getParams } from "@/api/assets";
import { cashToFollow, followToCash } from "@/api/copy";
import selectDepositPop from "@/mixins/selectDepositPop";
export default {
  components: {
    list,
    // authIdentity
  },
  mixins: [selectDepositPop],
  data () {
    return {
      amount: '',
      showPopover: false,
      authShow: false,
      show: false,
      item: '1',
      formInfo: {},
      toInfo: {},
      tragetInfo: {},
      accountId: '',
      sign: '',
      classify: {}
    }
  },
  computed: {
    ...mapGetters(['cashInfo', 'accountList', 'userInfo', 'currencyList', 'followAccount']),
    rate() {
      return this.currencyList[this.serverUtil[this.formInfo.market] || this.serverUtil[this.toInfo.market]] || 1
    },
    toAmount1() {
      return this.toAmount ? this.$handleDigits(this.toAmount, 3) : ''
    },
    toAmount() {
      if (!this.formInfo.id && !this.toInfo.id) {
        return ''
      }
      if (!Number(this.amount)) {
        return ''
      }
      if (this.formInfo.uid) {
        return this.$handleDigits(this.$bigDecimal.multiply(this.amount, this.rate))
      }
      return Number(this.$bigDecimal.divide(this.amount, this.rate))
    }
  },
  watch: {
    amount(val) {
      if (val == '-') {
        this.amount = ''
      }
    },
    cashInfo: {
      handler() {
        if (this.accountId == 'uid' && !this.toInfo.uid && !this.toInfo.id) {
          this.toInfo = this.cashInfo
          return
        }
        if (!this.formInfo.uid && !this.formInfo.id) {
          this.formInfo = this.cashInfo
        }
      },
      deep: true
    },
    accountList: {
      handler() {
        if (this.accountId == 'uid' && !this.formInfo.uid && !this.formInfo.id) {
          var info = null
          this.accountList.forEach(item => {
            if (item.balance && !info) {
              info = item
            }
          })
          this.formInfo = (info || this.accountList[0] || {})
          return
        }
        if (!this.toInfo.uid && !this.toInfo.id) {
          if (this.accountId) {
            this.accountList.forEach(item => {
              if (item.id == this.accountId) {
                this.toInfo = item
              }
            })
            return
          }
          this.toInfo = this.accountList[0]
        }
      },
      deep: true
    },
    followAccount: {
      handler() {
        if (!this.toInfo.uid && !this.toInfo.id) {
          if (this.accountId == this.followAccount.id) {
            this.toInfo = this.followAccount
            return
          }
        }
      },
      deep: true
    },
    userInfo: {
      handler() {
        if (this.userInfo.identity_status !== 1) {
          this.authShow = true
        }
      },
      deep: true
    }
  },
  created () {
    if (this.$route.params.id) {
      this.accountId = this.$route.params.id
    }
    if (this.userInfo.identity_status && this.userInfo.identity_status !== 1) {
      this.authShow = true
    }
    this.getParams()
    this.$store.dispatch('getFollowAccount')
    bus.$emit('updateAssets', ['getAccountList', 'getCash'])
  },
  methods: {
    submit() {
      if (this.userInfo.group == 9999) {
        bus.$emit('abnormalPopSign')
        return
      }
      if (!this.formInfo.id && !this.formInfo.uid) {
        // this.$toast('请选择兑出账户');
        this.$toast(this.$t('fund.l32'));
        return
      }
      if (!this.toInfo.id && !this.toInfo.uid) {
        // this.$toast('请选择兑入账户');
        this.$toast(this.$t('fund.l33'));
        return
      }
      if (!Number(this.amount)) {
        // this.$toast('请输入兑出金额');
        this.$toast(this.$t('fund.l34'));
        return
      }
      if (Number(this.amount) > (this.formInfo.id ? this.formInfo.margin_free : this.formInfo.balance)) {
        // this.$toast('可兑金额不足');
        this.$toast(this.$t('fund.l35'));
        return
      }
      var amount = Number(this.amount)
      if (this.formInfo.id == this.followAccount.id || this.toInfo.id == this.followAccount.id) {
        if (this.formInfo.id == this.followAccount.id) {
          this.followToCash({
            amount: amount,
          })
          return
        }
        if (this.toInfo.id == this.followAccount.id) {
          this.cashToFollow({
            amount: amount,
          })
        }
        return
      }
      if (this.formInfo.uid) {
        this.cashToTransaction({
          amount: amount,
          server: this.toInfo.server,
          account: this.toInfo.account,
        })
        return
      }
      if (this.toInfo.uid) {
        this.transactionToCash({
          amount: amount,
          server: this.formInfo.server,
          account: this.formInfo.account,
          input_currency: this.serverUtil[this.formInfo.server]
        })
      }
    },
    cashToTransaction(data) {
      this.fullscreenLoading = true
      cashToTransaction(data).then(res => {
        this.$notify({
          // message: '操作成功',
          message: this.$t('common.l52'),
          type: 'success'
        });
        this.$router.back()
      }).catch(() => {}).finally(() => {
        this.fullscreenLoading = false;
      })
    },
    transactionToCash(data) {
      this.fullscreenLoading = true
      transactionToCash(data).then(res => {
        this.$notify({
          // message: '操作成功',
          message: this.$t('common.l52'),
          type: 'success'
        });
        this.$router.back()
      }).catch(() => {}).finally(() => {
        this.fullscreenLoading = false;
      })
    },
    followToCash(data) {
      this.fullscreenLoading = true
      followToCash(data).then(res => {
        this.$notify({
          // message: '操作成功',
          message: this.$t('common.l52'),
          type: 'success'
        });
        this.$router.back()
      }).catch(() => {}).finally(() => {
        this.fullscreenLoading = false;
      })
    },
    cashToFollow(data) {
      this.fullscreenLoading = true
      cashToFollow(data).then(res => {
        this.$notify({
          // message: '操作成功',
          message: this.$t('common.l52'),
          type: 'success'
        });
        this.$router.back()
      }).catch(() => {}).finally(() => {
        this.fullscreenLoading = false;
      })
    },
    convertAccount() {
      this.sign = 'toInfo'
      this.selectBack(this.formInfo)
    },
    accountShow(sign) {
      this.show = true
      this.sign = sign
      this.tragetInfo = this[sign]
    },
    selectBack(item) {
      this.show = false
      if ((!item.server && !this[this.sign].server) || (this[this.sign].server == item.server && this[this.sign].server)) {
        return
      }
      if (!item.server && this[this.sign].server) {
        if (this.sign == 'formInfo') {
          this.toInfo = this.formInfo
        }
        if (this.sign == 'toInfo') {
          this.formInfo = this.toInfo
        }
      }
      if (item.id) {
        if (this.sign == 'formInfo' && this.toInfo.id) {
          this.toInfo = this.cashInfo
        }
        if (this.sign == 'toInfo' && this.formInfo.id) {
          this.formInfo = this.cashInfo
        }
      }
      this[this.sign] = item
      this.amount = ''
    },
    getParams() {
      getParams({
        type: 'Exchange',
        title: 'fee'
      }).then(res => {
        var list = res.list || []
        if (list[0]) {
          this.classify = list[0].value ? JSON.parse(list[0].value) : {}
        }
      }).catch(() => {})
    },
    getCurrencyList() {
      bus.$emit('updateAssets', ['getCurrencyList'])
    },
    authCancel() {
      this.authShow = false
      this.$router.back()
    }
  }
}
</script>
<style lang="less" scoped>
.sticky {
  background-color: var(--bg-);
  margin-bottom: 8px;
}
.header {
  position: relative;
  height: 38px;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
  background-color: var(--bg-);
  .back {
    position: absolute;
    left: 9px;
    top: 50%;
    transform: translateY(-50%);
  }
  .right-box {
    position: absolute;
    right: 19px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--color-3-);
    font-size: 12px;
    font-weight: 400;
    column-gap: 16px;
  }
  .more {
    cursor: pointer;
    width: 20px;
    display: block;
  }
}
.container {
  padding: 7px 18px 0;
}
.box {
  border-radius: 6px;
  border: 1px solid #E6E6E6;
  min-height: 54px;
  background-color: var(--bg-);
  justify-content: space-between;
  padding: 4px 12px;
  font-size: 14px;
  margin-bottom: 10px;
  column-gap: 6px;
  >.flex {
    cursor: pointer;
  }
  .convert {
    min-width: 16px;
    max-width: 16px;
    cursor: pointer;
  }
  .van-image {
    margin-right: 6px;
    min-width: 24px;
  }
  .place {
    color: #8B8B8B;
  }
  .el-icon-arrow-right {
    color: #8B8B8B;
    font-weight: 600;
  }
}
.section {
  border-radius: 6px;
  border: 1px solid #E6E6E6;
  background-color: var(--bg-);
  margin-bottom: 10px;
  padding: 16px 12px 20px;
  color: var(--color-1-);
  .wrapper {
    justify-content: space-between;
    >.flex {
      column-gap: 4px;
    }
  }
  .title {
    font-weight: 500;
    line-height: 15px;
  }
  .input-box {
    font-weight: 600;
    font-size: 20px;
    color: #232323;
    padding-bottom: 3px;
    padding-top: 20px;
    border-bottom: 1px solid #EBEBEB;
    margin-bottom: 17px;
  }
  .van-field {
    font-size: 20px;
    font-weight: 400;
    padding: 10px 0;
  }
  .row {
    color: #232323;
    font-size: 12px;
    justify-content: space-between;
    &+.row {
      margin-top: 13px;
    }
    .label {
      color: #8B8B8B;
    }
    .info {
      width: 12px;
      margin-left: 6px;
      cursor: pointer;
    }
    .van-image {
      min-width: 16px;
    }
    .reset {
      width: 12px;
      margin-left: 6px;
      cursor: pointer;
    }
  }
  .el-icon-arrow-right {
    font-weight: 600;
    color: #8B8B8B;
  }
}
.section1 {
  border-radius: 6px;
  border: 1px solid #E6E6E6;
  background-color: var(--bg-);
  padding-bottom: 20px;
  color: var(--color-1-);
  .van-image {
    min-width: 16px;
  }
  .wrapper {
    padding: 16px 12px 0;
    justify-content: space-between;
    >.flex {
      column-gap: 4px;
    }
  }
  .title {
    font-weight: 500;
    line-height: 15px;
  }
  .container1 {
    padding: 0 12px;
  }
  .input-box {
    font-weight: 600;
    font-size: 20px;
    color: #232323;
    padding-bottom: 3px;
    padding-top: 20px;
    border-bottom: 1px solid #EBEBEB;
  }
  .van-field {
    font-size: 20px;
    font-weight: 400;
    padding: 10px 0;
  }
  .el-icon-arrow-right {
    font-weight: 600;
    color: #8B8B8B;
  }
  .row {
    color: #232323;
    font-size: 12px;
    justify-content: space-between;
    margin-top: 17px;
    .label {
      color: #8B8B8B;
    }
  }
}
.section2 {
  padding: 25px 18px;
  .btn {
    cursor: pointer;
    background-color: #000;
    color: #FEFFFF;
    text-align: center;
    line-height: 44px;
    border-radius: 6px;
    font-size: 16px;
    margin-bottom: 14px;
    font-weight: 600;
  }
  .href {
    cursor: pointer;
    background: #FFFFFF;
    color: #000;
    text-align: center;
    line-height: 44px;
    font-size: 16px;
    margin-bottom: 25px;
    font-weight: 600;
    border-radius: 6px;
    border: 1px solid #000000;
  }
  .tips-title {
    font-size: 14px;
    color: #000000;
    margin-bottom: 5px;
  }
  .tips {
    color: #8B8B8B;
    font-size: 12px;
    line-height: 18px;
  }
  .span {
    cursor: pointer;
    color: var(--color-);
  }
}
.popover-body {
  .item {
    cursor: pointer;
    height: 42px;
    padding-left: 16px;
    padding-right: 8px;
    color: #2C2C2C;
    font-size: 14px;
    min-width: 122px;
    max-width: 180px;
    line-height: 1;
    &+.item {
      border-top: 1px solid #E9E9E9;
    }
  }
  .icon14 {
    width: 22px;
    margin-right: 8px;
  }
}
::v-deep{
  .van-cell {
    &::after {
      border-bottom: none;
    }
  }
}
</style>