<template>
  <cwg-popup :title="t('Ib.Custom.AccountAdjust')" :visible="visible" @close="closeDia" @confirm="confirmDia">
    <view class="dia-content dialog-account-adjust-body">

    </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 { ibApi } from '@/service/ib'
  import useUserStore from '@/stores/use-user-store'
  import { lang } from '@/composables/config'

  const props = defineProps({
    // 是否显示弹窗
    visible: {
      type: Boolean,
      default: false,
    },
    // 详情tableData
    tableData: { type: Array, default: () => ([]) },
  })
  const { Code, Host80 } = Config
  const { t } = useI18n()
  const formRef = ref(null)
  const dialogForm = ref({
    cId: '123',
  })
  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) {
      const { cId, id, comPoint1, hide1 } = val
      dialogForm.value = {
        cId, id, comPoint1, hide1,
      }
      if (val.ibId) {
        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 cancel = () => {
    // 取消按钮点击事件
    emit('close')
  }

  const closeDia = () => {
    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'),
      })
      this.cancel()
    } 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;
  }

  .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(14);
  }

  .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>