<template>
  <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
    <cwg-header :title="params.type === 1 ? t('Ib.NewAccount.TitleM') : t('Ib.NewAccount.TitleP')">
      <template #right>
        <view class="header-btn" @click="backIndex">
          <cwg-icon name="icon_back" :size="18" />
          <text>{{ t('Ib.Settings.Title') }}</text>
        </view>
      </template>
    </cwg-header>

    <view class="main-content account-content" v-if="showPage">
      <view class="box" v-if="isAllLoginTypesHidden">
        <view style="margin: 20px 0; font-size: 14px; line-height: 1.7;">
          <text>{{ t('news_add_field.OpenAccount.Des3') }}</text>
        </view>
      </view>
      <view class="box" v-else>
        <view class="tit">
          <cwg-icon name="icon_arrow_right" :size="16" />
          <text>{{ t('Ib.NewAccount.Title1') }}</text>
        </view>
        <view class="des">{{ t('Ib.NewAccount.Des1') }}</view>

        <view class="b-card">
          <uni-forms ref="formRef" :model="params" :rules="rules" label-position="top">
            <uni-row :gutter="20">
              <uni-col :xs="24" :sm="12" :md="8">
                <uni-forms-item :label="t('Ib.NewAccount.Platform')" name="platform" required>
                  <cwg-combox v-model:value="params.platform" :options="[{ text: 'MT4', value: 'MT4' }]"
                    :placeholder="t('placeholder.choose')" />
                </uni-forms-item>
              </uni-col>
              <uni-col :xs="24" :sm="12" :md="8">
                <uni-forms-item :label="t('Ib.NewAccount.LoginType')" name="accountType" required>
                  <cwg-combox v-model:value="params.accountType" :options="accountTypeOptions"
                    :placeholder="t('placeholder.choose')" @change="onAccountTypeChange" />
                </uni-forms-item>
              </uni-col>
              <uni-col :xs="24" :sm="12" :md="8">
                <uni-forms-item :label="t('Ib.NewAccount.Lever')" name="leverage" required>
                  <cwg-combox v-model:value="params.leverage" :options="formatOptions(optionsLev)"
                    :placeholder="t('placeholder.choose')" />
                </uni-forms-item>
              </uni-col>
              <uni-col :xs="24" :sm="12" :md="8">
                <uni-forms-item :label="t('Ib.NewAccount.Currency')" name="currency" required>
                  <cwg-combox v-model:value="params.currency" :options="formatOptions(optionsCur)"
                    :placeholder="t('placeholder.choose')" />
                </uni-forms-item>
              </uni-col>
              <uni-col :xs="24" :sm="12" :md="8">
                <uni-forms-item :label="t('Ib.NewAccount.Commission')" name="commission" required>
                  <cwg-combox v-model:value="params.commission" :options="formatOptions(optionsCom)"
                    :placeholder="t('placeholder.choose')" />
                </uni-forms-item>
              </uni-col>
              <uni-col :span="24">
                <button class="s-btn" type="primary" @click="newAccount">{{ t('Ib.NewAccount.Btn') }}</button>
              </uni-col>
            </uni-row>
          </uni-forms>
        </view>
      </view>

      <view class="box">
        <view style="margin: 20px 0; font-size: 14px; line-height: 1.7;">
          <template v-if="params.type === 1">
            <view style="font-weight: bold; margin-bottom: 5px;">{{ t('Ib.NewAccount.Dec1') }}</view>
            <view>{{ t('Ib.NewAccount.Dec2') }}</view>
          </template>
          <template v-if="params.type === 2">
            <view style="font-weight: bold; margin-bottom: 5px;">{{ t('Ib.NewAccount.Dec3') }}</view>
            <view>{{ t('Ib.NewAccount.Dec4') }}</view>
          </template>
        </view>
      </view>

      <view class="box" v-if="params.accountType === 6">
        <view style="margin: 20px 0; font-size: 14px; line-height: 1.7;">
          <view>
            <text>{{ t('Ib.NewAccount.Dec5') }}</text>
            <text class="crm-cursor" style="color: #368FEC;" @click="openLeverageMargin">{{ t('Ib.NewAccount.Dec6')
              }}</text>
            <text>{{ t('Ib.NewAccount.Dec7') }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 提交结果弹窗 -->
    <cwg-popup :visible="dialogCheck" :showClose="false" :showFooters="true" :confirmText="t('Btn.Confirm')"
      :cancelText="t('Btn.Cancel')" @confirm="closeDia" @close="closeDia">
      <view class="result-dialog">
        <view v-if="dialogVisible" class="icon-wrap">
          <cwg-icon name="icon_success" :size="50" color="#67C23A" />
          <view class="result-text">{{ t('ApplicationDialog.Des1') }}</view>
          <view class="result-sub-text">{{ t('ApplicationDialog.Des12') }}</view>
        </view>
        <view v-else class="icon-wrap">
          <cwg-icon name="icon_warning" :size="50" color="#E6A23C" />
          <view class="result-text">{{ RES }}</view>
        </view>
      </view>
    </cwg-popup>

  </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { ibApi } from '@/service/ib'
import { isAfterJuly28 } from '@/utils/dateUtils'
import Config from '@/config/index'

const { t, locale } = useI18n()
const { Code } = Config

const pictLoading = ref(false)
const showPage = ref(false)
const showLogin = ref<string[]>([])
const showData = ref<any[]>([])

const flag = ref(false)
const RES = ref('')
const dialogCheck = ref(false)
const dialogVisible = ref(false)

const optionsLev = ref<string[]>([])
const optionsCur = ref<string[]>([])
const optionsCom = ref<string[]>([])

const formRef = ref()

const params = reactive({
  type: 1,
  currency: '',
  commission: '',
  leverage: '',
  accountType: '' as string | number,
  platform: '',
})

const rules = {
  currency: { rules: [{ required: true, errorMessage: t('vaildate.select.empty') }] },
  commission: { rules: [{ required: true, errorMessage: t('vaildate.select.empty') }] },
  leverage: { rules: [{ required: true, errorMessage: t('vaildate.select.empty') }] },
  accountType: { rules: [{ required: true, errorMessage: t('vaildate.select.empty') }] },
  platform: { rules: [{ required: true, errorMessage: t('vaildate.select.empty') }] },
}

// 是否全部类型被隐藏
const isAllLoginTypesHidden = computed(() => {
  const hiddenStr = showLogin.value.join(',')
  return hiddenStr.includes('1') && hiddenStr.includes('2') && hiddenStr.includes('3') &&
    hiddenStr.includes('6') && hiddenStr.includes('7') && hiddenStr.includes('8')
})

// 动态计算下拉类型选项
const accountTypeOptions = computed(() => {
  const list = []
  if (!showLogin.value.includes('1')) list.push({ value: 1, text: t('AccountType.ClassicAccount') })
  if (!showLogin.value.includes('2')) list.push({ value: 2, text: t('AccountType.SeniorAccount') })
  if (!showLogin.value.includes('3') && !isAfterJuly28()) list.push({ value: 3, text: t('AccountType.AgencyAccount') })
  if (!showLogin.value.includes('6')) list.push({ value: 6, text: t('AccountType.SpeedAccount') })
  if (!showLogin.value.includes('7')) list.push({ value: 7, text: t('AccountType.StandardAccount') })
  if (!showLogin.value.includes('8')) list.push({ value: 8, text: t('AccountType.CentAccount') })
  return list
})

// 格式化普通数组为 combox 所需的 [{text, value}] 格式
const formatOptions = (arr: string[]) => {
  return (arr || []).map(item => ({ text: String(item), value: item }))
}

// 监听账户类型切换以回填下拉框
const onAccountTypeChange = (type: number) => {
  params.leverage = ''
  params.currency = ''
  params.commission = ''

  const target = showData.value.find(item => item.type == type)
  if (target) {
    optionsLev.value = target.leverage || []
    optionsCur.value = target.currency || []
    optionsCom.value = target.commission || []
  }
}

// 获取必填配置项
const getMustData = async () => {
  const res = await ibApi.MamApplyData({})
  if (res.code === Code.StatusOK) {
    showData.value = res.data || []
  } else {
    uni.showToast({ title: res.msg, icon: 'none' })
  }
}

// 获取排除类型
const getExcludeShowLogin = async () => {
  pictLoading.value = true
  try {
    const res = await ibApi.excludeShowLogin({})
    if (res.code === Code.StatusOK) {
      showLogin.value = res.data?.excludeShowLoginTypes || []
      showPage.value = true
    } else {
      uni.showToast({ title: res.msg, icon: 'none' })
    }
  } finally {
    pictLoading.value = false
  }
}

// 提交申请
const newAccount = async () => {
  try {
    await formRef.value?.validate()
  } catch (error) {
    return
  }

  if (flag.value) return
  flag.value = true

  try {
    const res = await ibApi.MamApplyAdd({ ...params })
    if (res.code === Code.StatusOK) {
      dialogCheck.value = true
      dialogVisible.value = true
    } else {
      RES.value = res.msg
      dialogCheck.value = true
      dialogVisible.value = false
    }
  } catch (err) {
    RES.value = t('Msg.Fail')
    dialogCheck.value = true
    dialogVisible.value = false
  } finally {
    flag.value = false
  }
}

// 关闭弹窗
const closeDia = () => {
  formRef.value?.clearValidate()
  // 也可以选择重置表单:
  Object.assign(params, { currency: '', commission: '', leverage: '', accountType: '', platform: '' })
  dialogCheck.value = false
  dialogVisible.value = false
}

const backIndex = () => {
  uni.navigateBack({ delta: 1 })
}

const openLeverageMargin = () => {
  const url = ['cn', 'zhHant'].includes(locale.value)
    ? 'https://www.cwgvu.com/cn/leveragemargin'
    : 'https://www.cwgvu.com/en/leveragemargin'
  // #ifdef H5
  window.open(url, '_blank')
  // #endif
  // #ifndef H5
  uni.showToast({ title: t('Msg.NotSupportedInApp'), icon: 'none' })
  // #endif
}

onLoad((options: any) => {
  if (options && options.type) {
    params.type = Number(options.type)
  } else {
    params.type = 1
  }
  getExcludeShowLogin()
  getMustData()
})
</script>

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

.header-btn {
  display: flex;
  align-items: center;
  font-size: px2rpx(14);
  color: var(--bs-heading-color);
  cursor: pointer;

  text {
    margin-left: px2rpx(5);
  }
}

.main-content {
  padding: px2rpx(10);
  min-height: calc(100vh - 100px);
}

.box {
  padding: px2rpx(15) px2rpx(20);
  background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  border-radius: px2rpx(4);
  margin-bottom: px2rpx(20);

  .tit {
    display: flex;
    align-items: center;
    font-size: px2rpx(16);
    font-weight: bold;
    margin-bottom: px2rpx(10);

    text {
      margin-left: px2rpx(5);
    }
  }

  .des {
    font-size: px2rpx(14);
    font-weight: bold;
    line-height: 1.5;
    margin-bottom: px2rpx(20);
    color: var(--bs-heading-color);
  }
}

.b-card {
  margin-top: px2rpx(15);
}

.s-btn {
  margin-top: px2rpx(10);
  min-width: px2rpx(120);
}

.crm-cursor {
  cursor: pointer;
  text-decoration: underline;
}

.result-dialog {
  text-align: center;
  padding: px2rpx(20);

  .icon-wrap {
    margin-bottom: px2rpx(20);
  }

  .result-text {
    font-size: px2rpx(16);
    font-weight: bold;
    margin-top: px2rpx(20);
    margin-bottom: px2rpx(10);
  }

  .result-sub-text {
    font-size: px2rpx(12);
    color: var(--bs-heading-color);
    margin-bottom: px2rpx(20);
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: px2rpx(15);
    margin-top: px2rpx(30);

    button {
      min-width: px2rpx(100);
      margin: 0;
    }
  }
}
</style>