<template>
  <view class="cwg-sidebar">
    <view class="wallet-widget">
      <view class="wallet-header" :class="{ 'header-bottom': isWalletOpen }" @click="isWalletOpen = !isWalletOpen">
        <view v-if="mode == 'follow'" class="wallet-header-left">
          <cwg-icon name="crm-payment" :size="16" color="#97A1C0" />
          <text>{{ t('Documentary.console.item14') }}</text>
          <text class="wallet-header-text">{{ followBalance }} USD</text>
        </view>
        <view v-else class="wallet-header-left">
          <cwg-icon name="crm-payment" :size="16" color="#97A1C0" />
          <text>{{ t(mode === 'customer' ? 'wallet.item5' : 'news_add_field.Label.Balance') }}</text>
          <text class="wallet-header-text">{{ mode === 'customer' ? formattedBalance : ibBalance }} USD</text>
        </view>
        <view class="wallet-header-right" :class="{ 'expanded': isWalletOpen }">
          <cwg-icon name="crm-chevron-down" :size="16" color="#6c8595" />
        </view>
      </view>

      <view class="wallet-body" v-if="isWalletOpen">
        <view class="wallet-body-header">
          <text class="drawer-title">隐藏余额</text>
          <switch :checked="!isShow" @change="toggleShow" color="#97A1C0"
            style="transform:scale(0.7); margin-right: -10px;" />
        </view>

        <view class="wallet-body-content">
          <template v-if="mode === 'follow'">
            <view class="balance-amount">{{ followBalance }} USD</view>
          </template>
          <template v-else>
            <view class="balance-amount">{{ mode === 'customer' ? formattedBalance : ibBalance }} USD</view>
            <view class="wallet-type">{{ mode === 'customer' ? t('wallet.pendingWithdraw') :
              t('Ib.Index.TotalRevenue') }}
            </view>
            <view class="wallet-id-box">
              ${{ mode === 'customer' ? formattedPendingWithdrawAmount : ibTotalBalance }}
            </view>
          </template>

        </view>

        <view class="wallet-actions" v-if="mode === 'customer'">
          <button class="action-btn btn btn-outline-danger waves-effect waves-light" @click.stop="goPages(1)" v-t="'wallet.item6'"></button>
          <button class="action-btn btn btn-outline-danger waves-effect waves-light" @click.stop="goPages(2)" v-t="'wallet.item7'"></button>
        </view>
        <view class="wallet-actions" v-if="mode === 'ib'">
          <button class="action-btn btn btn-outline-danger waves-effect waves-light" @click.stop="goIbPages(1)" v-t="'Custom.Index.Withdrawals'"></button>
          <button class="action-btn btn btn-outline-danger waves-effect waves-light" @click.stop="goIbPages(2)" v-t="'Home.page_ib.item4'"></button>
          <!--                  <button class="action-btn" @click.stop="goIbPages(3)" v-t="'Ib.Transfer.CommissionIssue'"></button>-->
        </view>
        <view class="wallet-actions" v-if="mode === 'follow'">
          <button class="action-btn btn btn-outline-danger waves-effect waves-light" @click.stop="goFollow()" v-t="'Documentary.console.item17'"></button>
        </view>
      </view>
    </view>

    <view class="menu-list">
      <view class="menu" v-for="(item, index) in menus" :key="item.path">
        <view class="menu-item" @click="handleClick(index)">
          <cwg-icon :name="item.icon" :size="20" color="#6c8595" />
          <view class="menu-label" v-t="item.label" />
          <view class="chevron-icon" :class="{ 'expanded': item.isOpenMenu }">
            <cwg-icon v-if="item.children && item.children.length" name="crm-chevron-down" :size="20" color="#6c8595" />
          </view>
        </view>
        <view :ref="(el) => setSubmenuRef(index, el)" class="submenu-box" :a="index" :key1="item.path + index" :b="item"
          :style="{
            height: !(item.children && item.children.length) ? '0px' : item.isOpenMenu ? item.submenuHeight + 'px' : '0px',
            transition: 'height 281ms cubic-bezier(0.4, 0, 0.2, 1)'
          }" :class="{ 'active': item.isOpenMenu }">
          <cwg-submenu v-if="item.children && item.children.length" :submenu-items="item.children"
            @submenu-click="handleClick1" />
        </view>
      </view>
    </view>
    <view class="menu fixed">
      <view
        class="menu-item btn-outline-danger btn btn-app-nav  btn-shadow mb-2 w-100 waves-effect ib-box btn-mode menu-item ib-box"
        @click="setMode('customer')" v-if="mode !== 'customer'">
        <cwg-icon name="crm-trade" :size="20" color="#000" />
        <view class="menu-label" v-t="'Home.msg.Custom'" />
      </view>
      <view
        class="menu-item btn-outline-danger btn btn-app-nav  btn-shadow mb-2 w-100 waves-effect ib-box btn-mode menu-item ib-box"
        @click="setMode('ib')" v-if="mode !== 'ib' && ibStatus">
        <cwg-icon name="crm-ib" :size="20" color="#000" />
        <view class="menu-label" v-t="'Home.msg.Ib'" />
      </view>
      <view
        class="menu-item btn-outline-danger btn btn-app-nav  btn-shadow mb-2 w-100 waves-effect ib-box btn-mode menu-item ib-box"
        @click="setMode('follow')" v-if="mode !== 'follow'">
        <cwg-icon name="crm-gd" :size="20" color="#000" />
        <view class="menu-label" v-t="'Documentary.title'" />
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import useUserStore from '@/stores/use-user-store'
import { useMenuSplit } from '@/composables/useMenuSplit'
import { storeToRefs } from 'pinia'
import { drawApi } from '@/service/draw'
import { ibApi } from '@/service/ib'
import { userToken } from '@/composables/config'
import useRouter from '@/hooks/useRouter'
import { useI18n } from 'vue-i18n'
import { documentaryApi } from '@/service/documentary'
import useGlobalStore from '@/stores/use-global-store'
const globalStore = useGlobalStore()
const isDark = computed(() => globalStore.theme === 'dark')

const { t } = useI18n()
const router = useRouter()
const handleClick1 = (item: MenuItem) => {
  emit('handle-click', item)
}
const { menus, setSubmenuRef, setMode, handleClick, handleSubmenuClick, mode } = useMenuSplit(handleClick1)
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const emit = defineEmits(['handle-click'])

// ib按钮展示
const ibStatus = computed(() => {
  const info: any = userInfo.value
  return !!info && !!info.customInfo && info.customInfo.ibInvalid == 0 && !!info.ibInfo
})

const isWalletOpen = ref(true)
const isShow = ref(true)
const walletbalance = ref(0)
const pendingWithdrawAmount = ref(0)
const ibData = ref({} as any)
const walletData = ref({} as any)

const NumberDecimal = (value: any) => {
  let realVal = ''
  if (!isNaN(value) && value !== '') {
    realVal = value// parseFloat(value).toFixed(2)
  } else {
    realVal = '0.00'
  }
  return realVal
}
const NumberDesensitization = (value: any) => {
  let realVal = ''
  if (!isNaN(value) && value !== '') {
    value = value.toString()
    realVal = '*****'
  } else {
    realVal = '--'
  }
  return realVal
}

const formattedBalance = computed(() => {
  const value = walletbalance.value || '0'
  const decimalValue = NumberDecimal(value)
  return isShow.value ? decimalValue : NumberDesensitization(decimalValue)
})

const ibBalance = computed(() => {
  const value = NumberDecimal(ibData.value?.balance || 0)
  return isShow.value ? value : NumberDesensitization(value)
})

const formattedPendingWithdrawAmount = computed(() => {
  const value = pendingWithdrawAmount.value || '0'
  const decimalValue = NumberDecimal(value)
  return isShow.value ? decimalValue : NumberDesensitization(decimalValue)
})

const ibTotalBalance = computed(() => {
  const value = NumberDecimal(ibData.value?.all || 0)
  return isShow.value ? value : NumberDesensitization(value)
})
// 跟单分润
const followBalance = computed(() => {
  const value = NumberDecimal(walletData.value?.walletAmount || 0)
  return isShow.value ? value : NumberDesensitization(value)
})
const getWalletList = async () => {
  let res = await drawApi.walletbalance({})
  if (res.code == 200) {
    if (res.data != null) {
      walletbalance.value = res.data
    }
  } else {
    uni.showToast({ title: res.msg, icon: 'none' })
  }
}

//获取处理中出金金额
const getPendingWithdrawAmount = async () => {
  let res = await drawApi.pendingWithdrawAmount({})
  if (res.code == 200) {
    if (res.data != null) {
      pendingWithdrawAmount.value = res.data
    }
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
  }
}

const getIbData = async () => {
  const res = await ibApi.IbData()
  if (res.code === 200) {
    if (res.data != null) ibData.value = res.data
  } else {
    uni.showToast({ title: res.msg, icon: 'none' })
  }
}
//跟单金额
const getMoneyList = async () => {
  let res = await documentaryApi.followWalletSingle({})
  if (res.code == 200) {
    if (res.data != null) {
      walletData.value = res.data
    }
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
  }
}

const toggleShow = (e: any) => {
  isShow.value = !e.detail.value
}

const goPages = (type: number) => {
  let path = ''
  if (type == 1) {
    path = '/pages/customer/wallet-transfer'
  } else if (type == 2) {
    path = '/pages/customer/wallet-history'
  }
  if (path) router.push(path)
}
const goFollow = (type: number) => {
  router.push('/pages/follow/transfer')
}

const goIbPages = (type: number) => {
  let path = ''
  let query = {}
  if (type == 1) {
    path = '/pages/ib/withdraw-select'
  } else if (type == 2) {
    path = '/pages/ib/transfer'
  } else if (type == 3) {
    path = '/pages/ib/transfer'
    query = { tab: 2 }
  }
  if (path) router.push({ path, query })
}

const getPay = (newMode) => {
  if (newMode == 'customer') {
    getWalletList()
    getPendingWithdrawAmount()
  } else if (newMode == 'ib') {
    getIbData()
  } else if (newMode == 'follow') {
    getMoneyList()
  }
}
watch(() => mode.value, (newMode) => {
  if (!userToken.value) return
  console.log(newMode, 'mode')
  getPay(newMode)
},
  { immediate: true })
onMounted(() => {
  uni.$on('updatePayment', () => {
    getPay(mode.value)
  })
})
onUnmounted(() => {
  uni.$off('updatePayment')
})
</script>

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

.cwg-sidebar {
  width: px2rpx(280);
  color: #6c8595;
  height: calc(100vh - (56px + var(--status-bar-height)));
  overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: px2rpx(8);
  padding-top: px2rpx(20);
  box-sizing: border-box;
  gap: px2rpx(8);
  border-right: 1px solid rgba(108, 133, 149, 0.12);

  .wallet-widget {
    width: 100%;
    //border-radius: px2rpx(4);
    border-top: 1px solid rgba(108, 133, 149, 0.12);
    border-bottom: 1px solid rgba(108, 133, 149, 0.12);
    overflow: hidden;
    margin-bottom: px2rpx(4);

    .header-bottom {
      border-bottom: 1px solid rgba(108, 133, 149, 0.12);
    }

    .wallet-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: px2rpx(10) px2rpx(12);
      //background: #f4f6f8;

      cursor: pointer;

      .wallet-header-left {
        display: flex;
        align-items: center;
        gap: px2rpx(8);
      }

      .wallet-header-text {
        font-size: 14px;
        color: var(--bs-emphasis-color);
        font-weight: 500;
      }

      .wallet-header-right {
        transition: transform 0.3s;

        &.expanded {
          transform: rotate(180deg);
        }
      }
    }

    .wallet-body {
      padding: px2rpx(12);

      .wallet-body-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: px2rpx(12);

        .drawer-title {
          font-size: 13px;
          color: #6c8595;
        }
      }

      .wallet-body-content {
        margin-bottom: px2rpx(16);

        .balance-amount {
          font-size: 16px;
          font-weight: 600;
          color: var(--bs-emphasis-color);
          margin-bottom: px2rpx(4);
        }

        .wallet-type {
          font-size: 12px;
          color: var(--cwg-placeholder-color);
          margin-bottom: px2rpx(4);
        }

        .wallet-id-box {
          display: flex;
          align-items: center;
          gap: px2rpx(4);
          color: var(--cwg-placeholder-color);
          .wallet-id {
            font-size: 12px;

          }
        }
      }

      .wallet-actions {
        display: flex;
        gap: px2rpx(8);

        .action-btn {
          flex: 1;
          height: px2rpx(32);
          line-height: px2rpx(32);
          font-size: 13px;
          margin: 0;
          padding: 0 px2rpx(8);

          &::after {
            border: none;
          }
        }
      }
    }
  }

  .logo {
    width: px2rpx(54);
  }

  .menu-list {
    flex: 1;
    width: 100%;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: px2rpx(8);
  }

  .submenu-box {
    width: 100%;
    height: 0;
    overflow: hidden;
  }

  .menu {
    width: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-sizing: border-box;

  }

  .menu-item {
    width: 100%;
    height: px2rpx(40);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: px2rpx(8);
    padding: px2rpx(10);
    box-sizing: border-box;
    font-size: 14px;


    .menu-label {
      flex: 1;
    }

    &:hover {
      border-radius: px2rpx(4);
    }

    .expanded .icon {
      transform: rotate(180deg);
    }
  }

  .ib-box {
    border: var(--bs-btn-border-width) solid var(--bs-btn-border-color);
    border-radius: var(--bs-btn-border-radius);
    background-color: var(--bs-btn-bg);
    font-size: px2rpx(18);
    font-weight: 600;
    justify-content: center;
    align-items: center;
    gap: px2rpx(8);
    display: flex;
    color: var(--bs-emphasis-color);

    :deep(.zui-svg-icon-image) {
      transition: filter 0.15s ease;
    }

    &:hover {
      color: var(--bs-btn-hover-color);
      background-color: var(--bs-btn-hover-bg);
      border-color: var(--bs-btn-hover-border-color);

      :deep(.zui-svg-icon-image) {
        filter: brightness(0) invert(1);
      }
    }
  }

  .zy-box {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .fixed {
    position: relative;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: px2rpx(8);

    .menu-label {
      flex: none;
    }
  }
}
</style>
