<template>
  <mobile-sub-layout :title="$t('account.header.withdrawalBankTitle')" :lineHeight="4"
    :bgColor="themeStore2.theme.bgColor">
    <view class="bank-card-body">
      <view class="bank-card-content" :style="{ backgroundColor: themeStore.lightBgColor }">
        <view class="bank-card-item-lable" :style="{ color: themeStore.text.lable }">{{
          $t("account.bankCard.labels.accountType") }}</view>
        <view class="select-input" @click="showSelectList" :style="{
          backgroundColor:
            accountType != 'Select'
              ? themeStore.backCardItemBg
              : themeStore.placeHolderBgColor,
          borderColor:
            accountType != 'Select'
              ? themeStore.backCardItemBorder
              : themeStore.placeHolderBorderColor,
          color:
            accountType != 'Select'
              ? themeStore.text.inputColor
              : themeStore.text.placeHolderColor,
        }">
          <text>{{ accountType }}</text>
          <theme-image src="@/static/account/icon/launch.png" v-if="pageData.withdrawTypes.length > 1"
            class="launch-iamge"></theme-image>
        </view>
        <template v-if="pageData.withdrawAccountRule.includes('accountName')">
          <view class="bank-card-item-lable m-top" :style="{ color: themeStore.text.lable }">
            {{ $t("account.bankCard.labels.accountName") }}
          </view>
          <view class="bank-card-item-value" :style="{
            backgroundColor: themeStore.backCardItemBg,
            borderColor: themeStore.backCardItemBorder,
          }">
            <view class="bank-card-item-value-icon-content" v-if="themeStore.isShowInputImage">
              <theme-image class="bank-card-item-value-icon" src="@/static/account/icon/user.png"></theme-image>
              <theme-image class="bank-card-item-value-segmentation"
                src="@/static/account/icon/segmentation.png"></theme-image>
            </view>
            <input type="text" v-model="accountName" class="bank-card-item-value-input" :placeholder-style="JSON.stringify({ color: themeStore.text.placeHolderColor })
              " :style="{ color: themeStore.text.inputColor }"
              :placeholder="$t('account.bankCard.placeholder.accountName')" />
          </view>
        </template>
        <template v-if="pageData.withdrawAccountRule.includes('accountNumber')">
          <view class="bank-card-item-lable m-top" :style="{ color: themeStore.text.lable }">{{
            $t("account.bankCard.labels.accountNumber") }}</view>
          <view class="bank-card-item-value" :style="{
            backgroundColor: themeStore.backCardItemBg,
            borderColor: themeStore.backCardItemBorder
          }">
            <view class="bank-card-item-value-icon-content" v-if="themeStore.isShowInputImage">
              <theme-image class="bank-card-item-value-icon" src="@/static/account/icon/password.png"
                mode="aspectFit"></theme-image>
              <theme-image class="bank-card-item-value-segmentation"
                src="@/static/account/icon/segmentation.png"></theme-image>
            </view>

            <input type="number" v-model="accountNumber" maxlength="19" class="bank-card-item-value-input"
              :placeholder-style="JSON.stringify({ color: themeStore.text.placeHolderColor })
                " :style="{ color: themeStore.text.inputColor }"
              :placeholder="$t('account.bankCard.placeholder.accountNumber')" />
          </view>
        </template>
        <template v-if="pageData.withdrawAccountRule.includes('CNIC')">
          <view class="bank-card-item-lable m-top" :style="{ color: themeStore.text.lable }">CNIC</view>
          <view class="bank-card-item-value" :style="{
            backgroundColor: themeStore.backCardItemBg,
            borderColor: themeStore.backCardItemBorder
          }">
            <view class="bank-card-item-value-icon-content" v-if="themeStore.isShowInputImage">
              <div class="ft16 fwbold" :style="{ color: themeStore2.theme.text.theme2 }">CNIC</div>
              <!-- <theme-image
				        class="bank-card-item-value-icon"
				        src="@/static/account/icon/password.png"
				      ></theme-image> -->
              <theme-image class="bank-card-item-value-segmentation"
                src="@/static/account/icon/segmentation.png"></theme-image>
            </view>

            <input type="number" v-model="CNIC" maxlength="13" class="bank-card-item-value-input" :placeholder-style="JSON.stringify({ color: themeStore.text.placeHolderColor })
              " :style="{ color: themeStore.text.inputColor }" placeholder="CNIC" />
          </view>
        </template>
        <template v-if="pageData.withdrawAccountRule.includes('accountIfsc')">
          <view class="bank-card-item-lable m-top" :style="{ color: themeStore.text.lable }">{{
            $t("account.bankCard.labels.accountIfsc") }}</view>
          <view class="bank-card-item-value" :style="{
            backgroundColor: themeStore.backCardItemBg,
            borderColor: themeStore.backCardItemBorder,
          }">
            <view class="bank-card-item-value-icon-content" v-if="themeStore.isShowInputImage">
              <theme-image class="bank-card-item-value-icon" src="@/static/account/icon/IFSC.png"></theme-image>
              <theme-image class="bank-card-item-value-segmentation"
                src="@/static/account/icon/segmentation.png"></theme-image>
            </view>

            <input type="text" v-model="accountIfsc" maxlength="11" :placeholder-style="JSON.stringify({ color: themeStore.text.placeHolderColor })
              " :style="{ color: themeStore.text.inputColor }" class="bank-card-item-value-input"
              :placeholder="$t('account.bankCard.placeholder.accountIfsc')" />
          </view>
        </template>
        <view class="bank-card-btn" @click="submit" :style="{
          background: themeStore2.theme.button.normal,
          color: themeStore2.theme.button.textNormal,
          backgroundSize: '100% 100%',
        }">
          {{ t("account.button.confirmCapital") }}
        </view>
      </view>
    </view>
    <view class="list" v-if="selectVisible" :style="[
      dynamicStyle,
      {
        background: themeStore.newBankCard.selectBgColor,
        borderColor: themeStore.newBankCard.selectBgBorderColor,
      },
    ]">
      <view class="list-content">
        <view class="list-item" :style="{
          color:
            accountType == item.name
              ? themeStore.newBankCard.selectActiveColor
              : themeStore.newBankCard.selectItemColir,
        }" v-for="(item, index) in pageData.withdrawTypes" :key="index" @click="selectAccountTypeCheck(item)">
          {{ item.name }}
        </view>
      </view>
    </view>
  </mobile-sub-layout>
</template>

<script setup>
import { ref, onMounted, reactive, getCurrentInstance } from "vue";
// import { bankCardApi } from "@/api/account.js";
import { getProfileApi } from "@/api/account.js";
import { useAppStore } from "@/store/useAppStore";
import { useUserStore } from "@/store/useUserStore";
import { useI18n } from "vue-i18n";
import { useThemeStore } from "@/store/useThemeStore";
import Toast from "@/module/toast/toast.js";
import { bindWithdrawAccountApi } from "@/api/account.js";
import { onLoad } from "@dcloudio/uni-app"

const appStore = useAppStore()
const userStore = useUserStore()
const themeStore = useThemeStore().theme.account.bankCard;
const themeStore2 = useThemeStore()
const { t } = useI18n();

let accountName = ref("");
let accountNumber = ref("");
let accountIfsc = ref("");
let CNIC = ref("")

let accountType = ref("Select");
let btcAccountNumber = ref("");
let selectVisible = ref(false);

let dynamicStyle = reactive({
  top: 0,
  left: 0,
  height: 0,
});
const pageData = reactive({
  id: '',
  withdrawTypes: [],
  selectAccountType: {},
  withdrawAccountRule: [],
  bankInfo: {}
})

onLoad((options) => {
  pageData.id = options.id || ''
  pageData.withdrawTypes = appStore.appConfig.withdrawTypes.filter(item => item.name == 'Bank')
  setSelectAccountTypeData()

  if (pageData.id) {
    loadData()
  }
  getProfileData()
})

const loadData = async () => {
  Toast.showLoading('Loading')
  const { code, data } = await getProfileApi({
    userId: userStore.userInfo.id
  })
  Toast.hideLoading()
  if (code !== 200 || !data) { return }
  const withdrawAccounts = data.withdrawAccounts || []
  let obj = withdrawAccounts.find(el => {
    return el.id === Number(pageData.id)
  })
  obj.withdrawAccount = JSON.parse(obj.withdrawAccount)

  accountIfsc.value = obj.withdrawAccount.accountIfsc || ''
  accountNumber.value = obj.withdrawAccount.accountNumber || ''
  accountName.value = obj.withdrawAccount.accountName || ''
  CNIC.value = obj.withdrawAccount.CNIC || ''
}
const getProfileData = async () => {
  const { code, data } = await getProfileApi({
    userId: userStore.userInfo.id,
  });
  if (code == 200 && data != null) {
    const list = data.withdrawAccounts || []
    if (list.length > 0) {
      list.forEach((item) => {
        item.withdrawAccount = JSON.parse(item.withdrawAccount);
      })
      pageData.bankInfo = list[0]
      if (pageData.bankInfo.withdrawAccount.accountName) {
        accountName.value = pageData.bankInfo.withdrawAccount.accountName
      }
      if (pageData.bankInfo.withdrawAccount.accountNumber) {
        accountNumber.value = pageData.bankInfo.withdrawAccount.accountNumber
      }
      if (pageData.bankInfo.withdrawAccount.accountIfsc) {
        accountIfsc.value = pageData.bankInfo.withdrawAccount.accountIfsc
      }
      if (pageData.bankInfo.withdrawAccount.CNIC) {
        CNIC.value = pageData.bankInfo.withdrawAccount.CNIC
      }
    }
  }
};
const setSelectAccountTypeData = (id) => {
  if (!pageData.withdrawTypes.length) { return }

  let selectObj = pageData.withdrawTypes[0]
  if (id) {
    const obj = pageData.withdrawTypes.find(el => {
      return el.id === id
    })
    if (obj) {
      selectObj = obj
    }
  }
  accountType.value = selectObj.name
  pageData.selectAccountType = selectObj
  pageData.withdrawAccountRule = JSON.parse(selectObj.withdrawAccountRule)
}

/**
 * 选中银行卡类型
 */
const selectAccountTypeCheck = (item) => {
  accountType.value = item.name

  accountName.value = ""
  accountNumber.value = ""
  accountIfsc.value = ""
  CNIC.value = ""

  pageData.selectAccountType = item
  pageData.withdrawAccountRule = JSON.parse(item.withdrawAccountRule)
  selectVisible.value = false
};

const showSelectList = () => {
  if (pageData.withdrawTypes.length <= 1) {
    return
  }
  selectVisible.value = !selectVisible.value;

  dynamicStyle.top = "306rpx";
  dynamicStyle.left = "30rpx";
  dynamicStyle.height = "0rpx";
  setTimeout(() => {
    dynamicStyle.height = "280rpx";
  }, 0.5);
};

const submit = async () => {
  if (pageData.withdrawAccountRule.includes('accountName') && !/^[A-Za-z\s]+$/.test(accountName.value)) {
    Toast.show(t("account.bankCard.tips.accountName"))
    return
  }
  if (pageData.withdrawAccountRule.includes('accountNumber') && !/^\d+$/.test(accountNumber.value)) {
    Toast.show(t("account.bankCard.tips.accountNumber"))
    return
  }
  if (pageData.withdrawAccountRule.includes('CNIC') && !CNIC.value) {
    return
  }
  if (pageData.withdrawAccountRule.includes('accountIfsc') && !accountIfsc.value) {
    if (accountIfsc.value.split("")[4] !== 0) {
      Toast.show(t("account.bankCard.tips.ifscTips"))
    }
    return
  }

  const params = {
    accountName: accountName.value || null,
    accountIfsc: accountIfsc.value || null,
    accountNumber: accountNumber.value,
    CNIC: CNIC.value || null
  }

  Toast.showLoading('Loading')
  const { code, data } = await bindWithdrawAccountApi({
    withdrawAccount: JSON.stringify(params),
    withdrawTypeId: pageData.selectAccountType.id,
  });
  Toast.hideLoading()
  if (code === 200) {
    Toast.showSuccess()
    setTimeout(() => {
      uni.navigateBack({
        delta: 1,
      });
    }, 1000)
  }
};

// const bindBackCard = async () => {
//   if (accountName.value == "") {
//     return;
//   }
//   if (accountNumber.value == "") {
//     return;
//   }
//   if (accountIfsc.value == "") {
//     return;
//   }
//   const { code, data } = await bankCardApi();
//   if (code == 200) {
//     uni.navigateBack({
//       delta: 1,
//     });
//   }
// };
</script>

<style lang="scss" scoped>
.bank-card-body {
  width: 100vw;
  box-sizing: border-box;
  padding-top: 10rpx;
  position: relative;

  .m-top {
    margin-top: 50rpx;
  }

  .bank-card-content {
    width: 100%;
    height: 100%;
    // background: #610606;
    box-sizing: border-box;
    padding: 30rpx;
    padding-bottom: 151rpx;

    .select-input {
      width: 100%;
      height: 90rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-radius: 20rpx;
      border: 2px solid;
      box-sizing: border-box;
      font-size: 26rpx;
      padding: 0 30rpx;
      margin-top: 40rpx;

      .launch-iamge {
        width: 29rpx;
        height: 16rpx;
      }
    }

    .bank-card-item-lable {
      width: 100%;
      height: 25rpx;
      line-height: 25rpx;
      font-size: 30rpx;
      // color: #fff;
    }

    .bank-card-item-value {
      width: 100%;
      height: 90rpx;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      // background: #3d0303;
      border-radius: 20rpx;
      border: 2px solid;
      box-sizing: border-box;
      // padding-left: 16rpx;
      margin-top: 40rpx;

      .bank-card-item-value-icon-content {
        width: 90rpx;
        height: 90rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-shrink: 0;

        .bank-card-item-value-icon {
          width: 60rpx;
          height: 60rpx;
          margin-right: 8rpx;
        }

        .bank-card-item-value-area {
          line-height: 90rpx;
          font-size: 30rpx;
          // color: #f43939;
        }

        .bank-card-item-value-segmentation {
          width: 4rpx;
          height: 68rpx;
        }
      }

      .bank-card-item-value-input {
        width: calc(100% - 78rpx);
        height: 90rpx;
        line-height: 90rpx;
        border: none;
        outline: none;
        font-size: 26rpx;
        // color: #fff;
        box-sizing: border-box;
        padding-left: 30rpx;
      }

      .bank-card-item-value-input::placeholder {
        font-size: 26rpx;
        // color: #963333;
      }
    }

    .bank-card-btn {
      width: 100%;
      height: 90rpx;
      text-align: center;
      line-height: 90rpx;
      margin-top: 80rpx;
      border-radius: 45rpx;
      font-family: Adobe Heiti Std;
      font-weight: 500;
      font-size: 36rpx;
    }

    .bank-card-item-tips {
      width: 100%;
      font-size: 24rpx;
      // color: #fff;
    }

    .bank-card-item-tips-value {
      font-size: 22rpx;
      line-height: 30rpx;
      word-wrap: break-word;
      // color: #fff;
      margin-top: 20rpx;
    }
  }
}

.list {
  width: 691rpx;
  height: 0rpx;
  // background: #7d1616;
  border-radius: 10rpx;
  border: 2px solid #b13e3e;
  position: absolute;
  overflow: hidden;
  transition: height 0.5s ease;

  .list-content {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    box-sizing: border-box;
    padding: 10rpx 0;
    text-align: center;

    .list-item {
      height: 60rpx;
      // color: #fff;
      line-height: 60rpx;
      font-size: 24rpx;
    }

    .list-item-active {
      color: #ffde00;
      height: 60rpx;
      line-height: 60rpx;
      font-size: 24rpx;
    }
  }
}

.submit-btn-block {
  width: 100%;
  height: 151rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  padding: 0 30rpx;
  // background: #820708;
  position: fixed;
  bottom: 0;
  left: 0;

  .submit-btn {
    width: 100%;
    height: 90rpx;
    // background: linear-gradient(90deg, #f78b22, #e34e04);
    border-radius: 45rpx;
    // color: #fff;
    font-size: 36rpx;
    text-align: center;
    line-height: 90rpx;
  }
}
</style>
