<template>
  <cwg-popup :title="t('Ib.Custom.AccountAdjust')" :visible="visible" @close="closeDia" @confirm="confirmDia">
    <view class="dia-content dialog-account-adjust-body">
      <view class="account-adjust-cid-row">
        <text class="account-adjust-cid-label">{{ t('Label.CidAccount') }}：</text>
        <text class="account-adjust-cid-value">{{ dialogForm.cId || '--' }}</text>
      </view>
      <uni-forms :model="dialogForm" ref="formRef" label-width="0" class="dialogCheck_form dialog-account-adjust-form">
        <view class="form-section form-section-commission">
          <view class="section-title">
            <cwg-icon name="crm-option" :size="22" color="#000"></cwg-icon>
            {{ t('Ib.Index.Spread5') }}
          </view>
          <view class="account-type-grid">
            <view class="account-type-card">
              <view class="account-type-label">
                {{ t('AccountType.StandardAccount') }}
              </view>
              <cwg-combox
                v-model:value="commissionAccountTypeSettings.standard.selectedIndex"
                :options="getAvailableSpreadsCommission('7').map((item, index) => ({
                  text: getSpreadLabelCommission(item),
                  value: index
                }))"
                :placeholder="t('placeholder.choose')"
                class="account-select"
                @change="(value) => handleCommissionAccountTypeChange('standard', '7', value)"
              />
            </view>
            <view class="account-type-card">
              <view class="account-type-label">
                {{ t('AccountType.SeniorAccount') }}
              </view>
              <cwg-combox
                v-model:value="commissionAccountTypeSettings.ecn.selectedIndex"
                :options="getAvailableSpreadsCommission('2').map((item, index) => ({
                  text: getSpreadLabelCommission(item),
                  value: index
                }))"
                :placeholder="t('placeholder.choose')"
                class="account-select"
                @change="(value) => handleCommissionAccountTypeChange('ecn', '2', value)"
              />
            </view>
            <view class="account-type-card">
              <view class="account-type-label">
                {{ t('AccountType.CentAccount') }}
              </view>
              <cwg-combox
                v-model:value="commissionAccountTypeSettings.cent.selectedIndex"
                :options="getAvailableSpreadsCommission('8').map((item, index) => ({
                  text: getSpreadLabelCommission(item),
                  value: index
                }))"
                :placeholder="t('placeholder.choose')"
                class="account-select"
                @change="(value) => handleCommissionAccountTypeChange('cent', '8', value)"
              />
            </view>
          </view>
        </view>
      </uni-forms>
    </view>
    <view class="dialog-footer dialog-account-adjust-footer">
      <view class="account-adjust-notes-panel">
        <view class="account-adjust-notes-section">
          <view class="account-adjust-notes-title">
            <cwg-icon name="gy" :size="20" class="account-adjust-notes-title-icon"></cwg-icon>
            <span class="account-adjust-notes-title-text">{{ t('Ib.Custom.AccountAdjustNotesSection2Title') }}</span>
          </view>
          <view class="account-adjust-notes-list">
            <view class="list">{{ t('Ib.Custom.AccountAdjustNotesSection2Item1') }}</view>
            <view class="list">{{ t('Ib.Custom.AccountAdjustNotesSection2Item2') }}</view>
          </view>
        </view>
      </view>
    </view>
  </cwg-popup>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { useI18n } from 'vue-i18n' // uni-app 中已集成，但需配置
  import { customApi } from '@/service/custom'
  import { financialApi } from '@/service/financial'
  import Config from '@/config/index'
  import PaymentMethodsList from './components/PaymentMethodsList.vue'
  import { ibApi } from '@/service/ib'
  import useUserStore from '@/stores/use-user-store'
  import { lang } from '@/composables/config'

  const props = defineProps({
    // 是否显示弹窗
    visible: {
      type: Boolean,
      default: false,
    },
    // 详情formData
    detail: { type: Object, default: () => ({}) },
  })
  const { Code, Host80 } = Config
  const { t } = useI18n()
  const formRef = ref(null)
  const dialogForm = ref({
    cId: '',
  })
  const commissionAccountTypeSettings = ref({
    ecn: { selectedIndex: null, selectedItem: null, loginType: '2' },
    standard: { selectedIndex: null, selectedItem: null, loginType: '7' },
    cent: { selectedIndex: null, selectedItem: null, loginType: '8' },
  })
  const commissionAccountTypeData = ref({
    ecn: [],
    standard: [],
    cent: [],
  })
  const emit = defineEmits(['close', 'confirm'])

  onMounted(() => {
    console.log(props.visible)
  })
  // 佣金调整弹框：拉取点差/价格数据（与 ConsumerShareLink getCustomLinkTypes 一致）
  const loadCommissionAccountTypes = async (ibId) => {
    const params = ibId ? { ibId } : {}
    let res = await ibApi.customLinkTypes(params)
    if (res.code == Code.StatusOK) {
      const data = res.data || []
      commissionAccountTypeData.value = {
        ecn: data.filter(
          (item) => item.loginType === 2 || item.loginType === '2',
        ),
        standard: data.filter(
          (item) => item.loginType === 7 || item.loginType === '7',
        ),
        cent: data.filter(
          (item) => item.loginType === 8 || item.loginType === '8',
        ),
      }
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      commissionAccountTypeData.value = { ecn: [], standard: [], cent: [] }
    }
  }
  const getAvailableSpreadsCommission = (loginType) => {
    if (loginType === '2') return commissionAccountTypeData.value.ecn || []
    if (loginType === '7')
      return commissionAccountTypeData.value.standard || []
    if (loginType === '8') return commissionAccountTypeData.value.cent || []
    return []
  }
  // 佣金调整弹框：根据佣金查看（getLoginPoint）的当前值设置账户类型下拉默认选中
  const setCommissionDefaultsFromLoginPoint = async (customerId) => {
    if (!customerId) return
    try {
      const res = await ibApi.getLoginPoint({ id: customerId })
      if (res.code !== Code.StatusOK || !Array.isArray(res.data)) return
      const list = res.data || []
      const norm = (v) =>
        v === 2 || v === '2'
          ? '2'
          : v === 7 || v === '7'
            ? '7'
            : v === 8 || v === '8'
              ? '8'
              : null
      const byType = { 2: [], 7: [], 8: [] }
      list.forEach((d) => {
        const t = norm(d.loginType)
        if (t && d.groupName) byType[t].push(d.groupName)
      });
      ['2', '7', '8'].forEach((loginType) => {
        const key =
          loginType === '2' ? 'ecn' : loginType === '7' ? 'standard' : 'cent'
        const currentGroupName = byType[loginType][0]
        const options = getAvailableSpreadsCommission(loginType)
        const idx =
          currentGroupName == null
            ? -1
            : options.findIndex(
              (item) => (item.groupName || '') === currentGroupName,
            )
        const setting = commissionAccountTypeSettings.value[key]
        if (idx >= 0) {
          setting.selectedIndex = idx
          setting.selectedItem = options[idx]
        } else {
          setting.selectedIndex = null
          setting.selectedItem = null
        }
      })
    } catch (e) {
      console.error('设置佣金调整默认值失败:', e)
    }
  }

  watch(() => props.detail, (val) => {
    if (val.cId) {
      const { cId, id, comPoint1, hide1 } = val
      dialogForm.value = {
        cId, id, comPoint1, hide1,
      }
        loadCommissionAccountTypes(val.ibId).then(
          () => {
            return setCommissionDefaultsFromLoginPoint(val.id)
          },
        )
    }
  })

  const getSpreadLabelCommission = (item) => {
    return item.groupName || ''
  }

  const handleCommissionAccountTypeChange = (type, loginType) => {
    const setting = commissionAccountTypeSettings.value[type]
    const availableSpreads = getAvailableSpreadsCommission(loginType)
    if (
      setting.selectedIndex !== null &&
      setting.selectedIndex !== undefined
    ) {
      setting.selectedItem = availableSpreads[setting.selectedIndex] || null
    } else {
      setting.selectedItem = null
    }
  }

  const toVerified = () => {
    // 确认按钮点击事件
    emit('confirm')
  }

  const closeDia = () => {
    dialogForm.value = {
      cId: '',
    }
    commissionAccountTypeSettings.value = {
      ecn: { selectedIndex: null, selectedItem: null, loginType: '2' },
      standard: { selectedIndex: null, selectedItem: null, loginType: '7' },
      cent: { selectedIndex: null, selectedItem: null, loginType: '8' },
    }
    emit('close')
  }

  const confirmDia = async () => {
    // 确认按钮点击事件
    const loginConfig = []
    Object.keys(commissionAccountTypeSettings.value).forEach((key) => {
      const setting = commissionAccountTypeSettings.value[key]
      if (setting.selectedItem) {
        loginConfig.push(setting.selectedItem)
      }
    })
    let res = await ibApi.customCommissionPoint({
      id: dialogForm.value.id,
      loginConfig,
    })
    if (res.code == Code.StatusOK) {
      uni.showToast({
        title: t('Msg.ModifySuccess'),
      })
      closeDia()
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
    }
    emit('confirm')
  }
</script>
<style lang="scss" scoped>
  @import "@/uni.scss";

  .dialog-account-adjust-body {
    padding: 20rpx;
  }

  .account-adjust-cid-row {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    font-size: px2rpx(20);
  }

  .account-adjust-cid-label {
    color: #606266;
    margin-right: px2rpx(5);
  }

  .account-adjust-cid-value {
    font-weight: bold;
    color: #303133;
  }

  .form-section {
    margin-bottom: 20rpx;
  }

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: px2rpx(15);
    font-weight: bold;
    font-size: px2rpx(18);
  }

  .section-title i {
    margin-right: 10rpx;
  }

  .account-type-grid {
  }

  .account-type-card {
    display: flex;
    flex-direction: column;
    margin-bottom: px2rpx(20);
  }

  .account-type-label {
    margin-bottom: 10rpx;
    font-size: 14rpx;
  }

  .account-select {
    width: 100%;
  }

  .dialog-account-adjust-footer {
    padding: 20rpx;
  }

  .account-adjust-notes-panel {
    margin-bottom: 20rpx;
  }

  .account-adjust-notes-section {
    background-color: #f5f7fa;
    padding: 15rpx;
    border-radius: 8rpx;
  }

  .account-adjust-notes-title {
    display: flex;
    align-items: center;
    margin-bottom: px2rpx(10);
    font-weight: bold;
    font-size: px2rpx(13);
  }

  .account-adjust-notes-title-icon {
    margin-right: px2rpx(10);
  }

  .account-adjust-notes-list {
    margin-left: px2rpx(20);
    color: #606266;
    font-size: px2rpx(13);
  }

  .account-adjust-notes-list .list {
    margin-bottom: px2rpx(5);
    margin-left: px2rpx(10);
  }

  .account-adjust-footer-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 15rpx;
  }

  .account-adjust-footer-buttons button {
    min-width: 120rpx;
  }
</style>