<template>
  <div class="page">
    <h-navbar title="Sacar" />
    <div class="page-body">
      <div class="container">
        <div class="top flex-ct">
          <h-img width="2.5rem" src="base/icon_qianbao.png" />
          <span>
            R$
            {{
              formatDigit(Number(userStore.userInfo.coins / 10000).toFixed(2))
            }}
          </span>
        </div>
      </div>
      <!-- 左右滑动选择 -->
      <div
        class="bank"
        :style="{ gridTemplateColumns: `repeat(${list.length},1fr)` }"
      >
        <div
          class="bank-item"
          :class="currentIndex == index ? 'active' : ''"
          v-for="(item, index) in list"
          :key="index"
          @click="change(index)"
        >
          <div class="top">
            <h-img type="local" class="icon" src="deposit/pix2.png" />
            <span>({{ item.txt }})</span>
          </div>
        </div>
      </div>
      <div
        class="bank"
        :style="{ gridTemplateColumns: `repeat(${newMethods.length},1fr)` }"
      >
        <div
          class="text"
          :class="bankIndex == index ? 'activeBank' : ''"
          v-for="(item, index) in newMethods"
          :key="index"
          @click="changeBank(index)"
        >
          {{ item.txt }}
        </div>
      </div>
      <div class="info">
        <div class="block">
          <div class="label">Montante de retirada</div>
          <input
            v-model="data.amount"
            type="number"
            style="text-align: center"
            :placeholder="`Min.${formatDigit(payLimit[0] / 10000)} ~ Max.${formatDigit(payLimit[1] / 10000)}`"
          />
        </div>
        <div class="block">
          <div class="label">conta bancária</div>
          <input v-model="data.account" :placeholder="accountPlaceholder" />
        </div>
        <div class="block">
          <div class="label">Titular de cartões</div>
          <input
            v-model="data.holder"
            placeholder="Entre no titular da conta"
          />
        </div>
      </div>

      <div class="box">
        <van-tabs
          v-model:active="active"
          shrink
          sticky
          color="#20caa0"
          title-active-color="#20caa0"
          title-inactive-color="#0d5e48"
        >
          <van-tab title="Canais">
            <Channel
              ref="channelRef"
              :disabled-visible="disabledVisible"
              @show-account="onShowAccount"
              @submit="onSubmit"
            />
          </van-tab>
          <van-tab title="Historico">
            <Log />
          </van-tab>
        </van-tabs>
      </div>

      <h-center-popup
        v-model="showAccount"
        title="User Account"
        contentBgcolor="#053230"
      >
        <div class="account">
          <div
            class="account-item"
            v-for="(item, index) in accountList"
            :key="index"
            @click="selectAccount(index)"
          >
            <span>Account: {{ item.account }}</span>
            <span>Holder: {{ item.holder }}</span>
            <span>Method: {{ channelList(item.method) }}</span>
          </div>
          <van-empty description="No Card" image-size="100" />
        </div>
      </h-center-popup>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import Channel from "./components/channel.vue";
import Log from "./components/log.vue";
import { useUserStore } from "@/stores/modules/user";
import { formatDigit } from "@/utils";
import { toast, showLoading, closeLoading } from "@/utils/toast";
import socketApi from "@/socket/socketApi";
import router from "@/router";
import http from "@/https";
import keyData from "@/socket/config/Global";
interface DataProps {
  amount?: number;
  method?: number;
  account?: number;
  holder?: number;
  classValue?: number;
}
interface listData {
  newMethods?: Array<any>;
  method?: Array<any>;
  txt?: any;
  value?: number;
  amountLimitArea?: Array<any>;
}
const list = ref<Array<any>>([]);

const bankIndex = ref(0);

const newMethods = ref<Array<any>>([]);

const accountPlaceholder = computed(() => {
  if (newMethods.value[bankIndex.value]?.value === 1) {
    //MOBILE
    return "MOBILE:Número de Celular";
  } else if (newMethods.value[bankIndex.value]?.value === 2) {
    //EMAIL
    return "EMAIL";
  } else if (newMethods.value[bankIndex.value]?.value === 3) {
    // CPF
    return "CPF:000.000.000-00";
  } else if (newMethods.value[bankIndex.value]?.value === 4) {
    // EVP
    return "EVP:00000000-0000-0000-0000-000000000000";
  } else {
    return "";
  }
});

const currentIndex = ref(0);

const userStore = useUserStore();

const channelRef = ref();

const active = ref(0);

const showAccount = ref(false);
// 用户账户管理
const accountList = ref<Array<any>>([]);

let data = reactive<DataProps>({});

const payLimit = ref<Array<any>>([]);

const getData = async () => {
  http.getTransMethodList().then((res: any) => {
    if (res.code !== 0) return;
    if (res.data.length == 0) return;
    list.value = res.data;
    console.log(list.value, "列表");
    for (let i = 0; i < list.value.length; i++) {
      let newMethods: Array<any> = [];
      for (let j = 0; j < list.value[i].method.length; j++) {
        for (let key in keyData.TRANS_METHOD_TYPE) {
          if (
            list.value[i].method[j] === keyData.TRANS_METHOD_TYPE[key].value
          ) {
            newMethods.push({ ...keyData.TRANS_METHOD_TYPE[key] });
          }
        }
      }
      list.value[i].newMethods = newMethods;
    }
    console.log(list.value)
    payLimit.value = list.value[0].amountLimitArea;
    data.classValue = list.value[currentIndex.value].value;
    newMethods.value = list.value[currentIndex.value].newMethods || [];
    console.log(list.value, "新列表");
    change(0);
});
};

const disabledVisible = computed(() => {
  let arr = Object.values(data).filter((el: any) => {
    if (el !== null && el !== "") {
      return true;
    }
  });
  console.log(arr);
  if (arr.length === 5) {
    return false;
  }
  return true;
});

const channelList = (method: number) => {
  const ch = list.value.find((i: any) => i.value == method);
  return ch?.txt;
};

const onShowAccount = () => {
  http.withdrawList().then((res: any) => {
    console.log(res, "res!!!!!!!!!!!!!!!");
    if (res.code !== 0) {
      toast(res.txt);
      return;
    }
    accountList.value = res.data;
    showAccount.value = true;
  });
};

const selectAccount = (index: number) => {
  const ac = accountList.value[index];
  data.account = ac.account;
  data.method = ac.method;
  data.holder = ac.holder;
  showAccount.value = false;
};

const onSubmit = async () => {
  console.log({
    ...data,
    amount: data.amount! * 10000,
  });
  // 未绑定手机号前往绑定
  if (!userStore.userInfo.mobile) {
    router.push("bind-phone");
    return;
  }
  showLoading();
  if (data.amount! * 10000 > userStore.userInfo.coins) {
    closeLoading();
    return toast("Por favor, introduz a quantidade correta de retirada");
  }
  console.log(payLimit.value);
  
  if(data.amount < (payLimit.value[0] / 10000) || (data.amount > payLimit.value[1] / 10000)){
      closeLoading();
      toast("Não atende ao valor mínimo de saque");
      return;
  }
  let params: DataProps = {
    ...data,
    amount: data.amount! * 10000,
  };
  http.withdraw(params).then((res: any) => {
    if (res.code !== 0) {
      if (res.code == 33101) {
        closeLoading();
        toast("Formato incorrecto de entrada");
        return;
      }
      closeLoading();
      toast(res.txt);
      return;
    }
    closeLoading();
    toast("Subposto com sucesso para revisão!");
    data = {
      amount: undefined,
      method: newMethods.value[0].value,
      account: undefined,
      classValue: list.value[0].value,
      holder: undefined,
    };
    userStore.getUserInfo();
  });
};
const change = (index: number) => {
  currentIndex.value = index;
  newMethods.value = list.value[index].newMethods || [];
  bankIndex.value = 0;
  data.method = newMethods.value[0].value;
  data.classValue = list.value[index].value;
  payLimit.value = list.value[index].amountLimitArea;
  // emit("update:method", list.value[index].value);
};
const changeBank = (index: number) => {
  bankIndex.value = index;
  data.method = newMethods.value[index].value;
};
onMounted(() => {
  getData();
});
</script>

<style lang="scss" scoped>
.prompt-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  > div {
    color: #ecc119;
    font-size: 0.4rem;
    padding: 0.4rem 0.6rem;
  }
  > .van-button {
    width: 50%;
    font-size: 0.4rem;
    margin: 0.4rem;
  }
}
.page-body {
  .bank {
    // margin: 0.2rem 0;
    display: grid;
    gap: 0.2rem;
    overflow: auto;
    padding: 0.2rem 0;
    &-item {
      font-size: 0.3rem;
      width: 3.7rem;
      background: #232323;
      border-radius: 0.2rem;
      padding: 0.25rem 0.1rem;
      border: 1px solid #232323;
      @extend .transition;

      .top {
        display: flex;
        align-items: center;
        justify-content: center;
        .icon {
          width: 2rem;
        }
        span {
          font-size: 0.3rem;
          color: #b1b1b1;
        }
      }
    }
    .text {
      font-size: 0.3rem;
      background: #232323;
      border-radius: 0.2rem;
      padding: 0.3rem 0.1rem;
      border: 1px solid #232323;
      @extend .transition;
    }
    .activeBank {
      background-color: #045845;
      border: 1px solid #33f5af;
      color: #33f5af;
    }
    .active {
      border: 1px solid $other-color;
      .bottom {
        color: $other-color;
      }
    }
  }
  .container {
    padding: 0.4rem;
    background: $nav-bar;
    border-radius: 0.2rem;
    .top {
      span {
        font-size: 0.6rem;
        margin: 0 0.3rem;
        background: #011912;
        display: block;
        flex: 1;
        border-radius: 0.2rem;
        padding: 0 0.3rem;
        color: #ffe726;
        @extend .more;
      }
    }
  }
  .info {
    display: flex;
    flex-direction: column;
    margin: 0.3rem 0;
    .block {
      margin-bottom: 0.2rem;
      display: flex;
      align-items: center;
      .label {
        width: 4rem;
        font-size: 0.38rem;
        text-align: center;
        color: #35ffb5;
      }
      input {
        flex: 1;
        height: 0.7rem;
        padding: 0.1rem 0;
        border-radius: 1rem;
        color: #ffe726;
        font-size: 0.38rem;
        text-align: center;
        background: #062e23;
        border: none;
        &::-webkit-input-placeholder {
          color: #1b9964;
        }
      }
    }
  }
  .box {
    .van-tabs {
      --van-tab-font-size: 0.45rem;
      :deep(.van-tabs__nav) {
        background: transparent;
      }
    }
  }
  .account {
    font-size: 0.4rem;
    color: #fff;
    height: 6rem;
    overflow: auto;

    &-item {
      display: flex;
      flex-direction: column;
      justify-content: center;
      font-weight: 500;
      height: 1.8rem;
      background: linear-gradient(
        to bottom,
        #262b31,
        #1c3236,
        #184039,
        #1d493c
      );
      border-radius: 0.25rem;
      padding: 0.2rem;
    }
  }
}
</style>

<style>
.place {
  &::-webkit-input-placeholder {
    color: #1b9964;
  }
}
</style>
