<template>
  <div class="market table_form-container">
    <!-- 搜索 -->
    <MarketSearch
      :search-form="marketSearchForm"
      :buttonLoading="loading"
      :search-options="marketSearchOptions"
      @search="handleSearch"
      @reset="handleReset"
    >
      <template #button="{ form }">
        <el-button type="primary" @click="handleAddMarket()" v-auth="'agent_createAgent'">
          添加
        </el-button>
        <el-button
          type="primary"
          :disabled="!selectedRow"
          v-auth="'agent_editAgent'"
          @click="handleEditMarket()"
        >
          编辑
        </el-button>
      </template>
    </MarketSearch>

    <!-- 表格 -->
    <MarketTable
      :table-data="marketTree"
      :columns="marketTableColumnsOptions"
      row-key="id"
      :show-column-setting="true"
      :loading="loading"
      @row-click="handleRowClick"
      @row-contextmenu="handleRowContextMenu"
    >
      <template #floatProfitLoss="{ row }">
        <span>{{ getMarketFloatProfit(row.id) }}</span>
      </template>
      <template #closeProfitLoss="{ row }">
        <span>{{ getMarketCloseProfit(row.id) }}</span>
      </template>
      <template #pointSpread="{ row }">
        <el-button type="primary" size="small" @click="handleViewPointDiff(row)"> 查看 </el-button>
      </template>
    </MarketTable>
    <!-- 行右键菜单 -->
    <context-menu v-model:show="menuVisible" :options="menuOptions">
      <context-menu-item
        v-if="[3, 4].includes(currentRow.role_id) && userStore!.userInfo!.role_id === 1"
        label="调整基本账户"
        @click="handleAction('account')"
      />
      <context-menu-item
        v-if="
          ([3, 4].includes(currentRow.role_id) && userStore!.userInfo!.role_id === 1)
        "
        label="设置停止接单金额"
        @click="handleAction('acceptOrders')"
      />
      <context-menu-item
        v-if="
          ([3, 4].includes(currentRow.role_id) && userStore!.userInfo!.role_id === 1)
        "
        label="设置持仓转移金额"
        @click="handleAction('transfer')"
      />
      <context-menu-item
        v-if="
          ([1, 2, 3, 4, 5].includes(userStore!.userInfo!.role_id) &&
          userStore!.userInfo!.role_id === currentRow.role_id) ||  [1].includes(userStore!.userInfo!.role_id)
        "
        label="取款"
        divided
        @click="handleAction('deposit')"
      />
      <context-menu-item 
        v-if="
          [1].includes(userStore!.userInfo!.role_id)&&[3, 4].includes(currentRow.role_id) 
        " label="存款" divided @click="handleAction('withdraw')" />
    </context-menu>

    <!-- 分页 -->
    <MarketPagination
      v-model="currentPage"
      v-model:pageSizeValue="pageSize"
      :total="total"
      @pagination-change="handlePaginationChange"
    />
  </div>

  <!-- dialog -->
  <el-drawer
    class="my-drawer"
    :append-to-body="false"
    v-model="dialogVisible"
    :title="dialogTitle"
    :size="dialogType === 'view' ? '60%' : '50%'"
    :destroy-on-close="true"
  >
    <!-- 表单 -->
    <div v-if="dialogType !== 'view'" class="drawer-form">
      <MarketForm
        :form-data="marketForm"
        :form-rules="marketFormRules"
        :form-items="marketFormItemOptions"
        :options-map="marketFormOptionsMap"
        ref="marketFormRef"
      >
        <template #phoneOrEmail="{ formData }" v-if="dialogType === 'add'">
          <div class="phone-email">
            <div class="tab-btn">
              <el-button
                :type="activeTab === 'email' ? 'primary' : 'default'"
                size="small"
                @click="activeTab = 'email'"
              >
                邮箱
              </el-button>
              <el-button
                :type="activeTab === 'phone' ? 'primary' : 'default'"
                size="small"
                @click="activeTab = 'phone'"
              >
                手机号
              </el-button>
            </div>
            <div class="group">
              <el-form-item prop="email" v-if="activeTab === 'email'">
                <el-input v-model="marketForm.email" placeholder="请输入邮箱" />
              </el-form-item>
              <el-form-item prop="phone" class="phone-item" v-if="activeTab === 'phone'">
                <el-select v-model="marketForm.countryCode" placeholder="请选择国家区号">
                  <el-option
                    v-for="item in countryOptions"
                    :key="item.code"
                    :label="item.code"
                    :value="item.code"
                  >
                    <div class="country-option">
                      <span class="country-name">{{ item.name }}</span>
                      <span class="country-code">{{ item.code }}</span>
                    </div>
                  </el-option>
                </el-select>
                <el-input v-model="marketForm.phone" placeholder="请输入手机号" />
              </el-form-item>
            </div>
          </div>
        </template>
      </MarketForm>
    </div>

    <!-- 点差表格 -->
    <div class="drawer-table">
      <div class="table-header" v-if="dialogType !== 'view'">点差配置</div>
      <div class="table-wrapper">
        <MarketTable
          :table-data="marketPointTree"
          :columns="marketPointTableColumnsOptions"
          row-key="id"
        >
          <template #assignedPointDiff="{ row }">
            <el-form :model="row" :rules="rules(marketForm, row)">
              <el-form-item prop="pointDifference">
                <el-input v-model="row.pointDifference" size="small" placeholder="请输入点差" />
              </el-form-item>
            </el-form>
          </template>
        </MarketTable>
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer v-if="dialogType !== 'view'">
      <div class="drawer-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <MarketDialog
    :visible="rightClickDialogVisible"
    :title="rightClickDialogTitleEnum[rightClickDialogType]"
    @confirm="handleRightClickDialogSubmit"
    @cancel="handleRightClickDialogCancel"
    @close="handleRightClickDialogClose"
  >
    <!--   'account' | 'acceptOrders' | 'transfer' | 'deposit' | 'withdraw'   -->
    <!-- 取款表单特殊处理 -->
    <template v-if="rightClickDialogType === 'deposit'">
      <div class="withdraw-form">
        <!-- 账户信息 -->
        <div class="form-section">
          <div class="section-title">账户信息</div>
          <el-form :model="rightClickMarketForm" label-width="120px" label-position="left">
            <el-form-item label="账户名">
              <el-input v-model="rightClickMarketForm.username" disabled />
            </el-form-item>
            <el-form-item label="币种">
              <el-input v-model="rightClickMarketForm.currency" disabled />
            </el-form-item>
          </el-form>
        </div>

        <!-- 金额信息（根据角色显示不同字段） -->
        <div class="form-section">
          <div class="section-title">取款金额</div>
          <el-form ref="withdrawFormRef" :model="rightClickMarketForm" :rules="rightClickMarketFormRules" label-width="140px" label-position="left">
            <!-- 手续费佣金 -->
            <el-form-item label="手续费佣金" prop="withdraw_fee_handle">
              <el-input
                v-model="rightClickMarketForm.withdraw_fee_handle"
                type="number"
                placeholder="请输入手续费佣金"
                @input="handleWithdrawAmountInput('withdraw_fee_handle')"
              >
                <template #append>最大: {{ rightClickMarketForm.commission_fee_handling_max || '0' }}</template>
              </el-input>
            </el-form-item>
            
            <!-- 点差佣金 -->
            <el-form-item label="点差佣金" prop="withdraw_point_diff">
              <el-input
                v-model="rightClickMarketForm.withdraw_point_diff"
                type="number"
                placeholder="请输入点差佣金"
                @input="handleWithdrawAmountInput('withdraw_point_diff')"
              >
                <template #append>最大: {{ rightClickMarketForm.commission_point_diff_max || '0' }}</template>
              </el-input>
            </el-form-item>
            
            <!-- 服务费（平台、承包商、特殊做市商） -->
            <el-form-item
              v-if="[1, 2, 3].includes(currentRow?.role_id * 1)"
              label="服务费"
              prop="withdraw_service_fee"
            >
              <el-input
                v-model="rightClickMarketForm.withdraw_service_fee"
                type="number"
                placeholder="请输入服务费"
                @input="handleWithdrawAmountInput('withdraw_service_fee')"
              >
                <template #append>最大: {{ rightClickMarketForm.service_max || '0' }}</template>
              </el-input>
            </el-form-item>
            
            <!-- 风险金（仅平台） -->
            <el-form-item v-if="currentRow?.role_id === 1" label="风险金" prop="withdraw_risk_fee">
              <el-input
                v-model="rightClickMarketForm.withdraw_risk_fee"
                type="number"
                placeholder="请输入风险金"
                @input="handleWithdrawAmountInput('withdraw_risk_fee')"
              >
                <template #append>最大: {{ rightClickMarketForm.risk_max || '0' }}</template>
              </el-input>
            </el-form-item>
            
            <!-- 盈利（特殊做市商、普通做市商） -->
            <el-form-item
              v-if="[3, 4].includes(currentRow?.role_id * 1)"
              label="盈利"
              prop="withdraw_head_fee"
            >
              <el-input
                v-model="rightClickMarketForm.withdraw_head_fee"
                type="number"
                placeholder="请输入盈利"
                @input="handleWithdrawAmountInput('withdraw_head_fee')"
              >
                <template #append>最大: {{ rightClickMarketForm.closing_profit_max || '0' }}</template>
              </el-input>
            </el-form-item>

            <!-- 合计金额 -->
            <el-form-item label="合计取款金额">
              <el-input :value="calculateTotalWithdrawAmount(rightClickMarketForm)" disabled>
                <template #append>USD</template>
              </el-input>
            </el-form-item>

            <!-- 钱包地址 -->
            <el-form-item label="钱包地址" prop="withdraw_address">
              <el-input
                v-model="rightClickMarketForm.withdraw_address"
                placeholder="请输入钱包地址"
              />
            </el-form-item>

            <!-- 取款渠道 -->
            <el-form-item label="取款渠道" prop="channel_id">
              <el-select
                v-model="rightClickMarketForm.channel_id"
                placeholder="请选择取款渠道"
                style="width: 100%"
              >
                <el-option
                  v-for="item in withdrawChannelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </template>
    
    <!-- 其他表单（保持原有逻辑） -->
    <MarketForm
      v-else
      :form-data="rightClickMarketForm"
      :form-rules="rightClickMarketFormRules"
      :form-items="rightClickMarketFormItemOptions"
    ></MarketForm>
  </MarketDialog>
</template>

<script setup lang="ts">
defineOptions({
  name: 'Business',
})
// 组件
import { nextTick } from 'vue'
import MarketSearch from '@/components/common/Search.vue'
import MarketTable from '@/components/common/Table.vue'
import { usePageLoading, useButtonLoading } from '@/composables/useLoading'
import MarketPagination from '@/components/common/Pagination.vue'
import MarketDialog from '@/components/common/Dialog.vue'
import MarketForm from '@/components/common/Form.vue'
//配置选项和表单验证
import {
  marketSearch,
  marketTableColumns,
  marketFormItem,
  marketPointTableColumns,
  countryOptions,
  viewMarketPointTableColumns,
  accountFormItemList,
  accountFormItemRules,
  acceptOrdersFormItemList,
  acceptOrdersFormItemRules,
  transferFormItemList,
  transferFormItemRules,
  getWithdrawFormConfig,
  getWithdrawFormRules,
} from './options'
import { useUserStore } from '@/stores/modules/user.ts'
import { rules } from './rules'

//接口
import {
  getMarketListApi,
  getPointDiffConfigListApi,
  getParAgentListApi,
  getRiskTemplateListApi,
  getBasetsOptionsApi,
  addMarketApi,
  editMarketApi,
  updateCapital,
  editAgentBail,
} from '@/api/modules/profile/business.ts'
import { getAgentWithdrawChannel, agentWithdraw } from '@/api/modules/capital/withdraw'

const userStore = useUserStore()

/**
 * @description 定义搜索数据
 */

const marketSearchForm = ref({
  accountName: '',
})
const marketSearchOptions = ref(marketSearch)

const { loading, startLoading, stopLoading } = usePageLoading()
const { buttonLoading: submitLoading, startButtonLoading: startSubmitLoading, stopButtonLoading: stopSubmitLoading } = useButtonLoading()
/**
 * @description 定义表格数据
 */
const marketTree = ref([])
const marketTableColumnsOptions = ref(marketTableColumns)

// 引入 transactionStore 用于动态浮动盈亏
import { useTransactionStore } from '@/stores/modules/transaction.ts'
const transactionStore = useTransactionStore()

/**
 * @description 获取做市商的浮动盈亏值
 */
const getMarketFloatProfit = (accountId: string | number): string => {
  const profit = transactionStore.marketFloatProfitMap.get(String(accountId))
  if (!profit) return '--'
  const parts = profit.split('.')
  if (parts.length === 1) return profit + '.00'
  return parts[0] + '.' + (parts[1] + '00').slice(0, 2)
}

/**
 * @description 获取做市商的平仓盈亏值
 */
const getMarketCloseProfit = (accountId: string | number): string => { 
  const profit = transactionStore.marketCloseProfitMap.get(String(accountId))
  if (!profit) return '--'
  const parts = profit.split('.')
  if (parts.length === 1) return profit + '.00'
  return parts[0] + '.' + (parts[1] + '00').slice(0, 2)
}

/**
 * @description 获取浮动盈亏样式类
 */
const getFloatProfitClass = (value: string | number) => {
  const num = Number(value)
  if (isNaN(num)) return ''
  if (num > 0) return 'profit-positive'
  if (num < 0) return 'profit-negative'
  return ''
}

/**
 * @description 定义分页数据
 */
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

/**
 * @description 定义dialog数据
 */
const dialogVisible = ref<boolean>(false)
const dialogTitle = ref<string>('')
const dialogType = ref<string>('add')

/**
 * @description 定义dialog表单数据
 */
const marketForm = ref({
  //邮箱或手机号
  email: '',
  phone: '',
  countryCode: '+86',
  accountName: '',
  level: '',
  parentAccountName: '',
  riskControlTemplate: '',
  positionRatio: '',
  commissionRatio: '',
  //拿最大去比较值
  maxPositionRatio: '',
  maxCommissionRatio: '',
})
const marketFormRules = computed(() => rules(marketForm.value, undefined, dialogType.value === 'edit'))
const marketFormRef = ref()
const marketFormItemOptions = computed(() => {
  return marketFormItem.map((item) => {
    // 编辑时禁用账户名称、所属上级、级别
    if (item.prop === 'accountName' || item.prop === 'parentAccountName' || item.prop === 'level') {
      return { ...item, disabled: dialogType.value === 'edit' }
    }
    // 只有当级别为特殊做市(level='3')时才显示 is_base_ts，且编辑时禁用
    if (item.prop === 'is_base_ts') {
      const show = marketForm.value.level === '3'
      return { ...item, show, disabled: dialogType.value === 'edit' }
    }
    // 只有当级别为特殊做市(level='3')且 is_base_ts=2 时才显示 base_ts
    if (item.prop === 'base_ts') {
      if (marketForm.value.level !== '3' || marketForm.value.is_base_ts !== 2) {
        return { ...item, show: false }
      }
      return { ...item, show: true }
    }
    return item
  })
})
interface SelectOption {
  label: string
  value: string | number
  row?: any // 存储完整对象
}
const marketFormOptionsMap = ref<{
  level: SelectOption[]
  parentAccountName: SelectOption[]
  riskControlTemplate: SelectOption[]
  is_base_ts: SelectOption[]
  base_ts: SelectOption[]
}>({
  level: [
    // { label: '平台', value: '1' },
    { label: '承包商', value: '2' },
    { label: '特殊做市', value: '3' },
    { label: '普通做市', value: '4' },
    { label: '一级代理', value: '5' },
    { label: '二级代理', value: '6' },
  ],
  parentAccountName: [],
  riskControlTemplate: [],
  is_base_ts: [
    { label: '是', value: 1 },
    { label: '否', value: 2 },
  ],
  base_ts: [],
})
const activeTab = ref('email')
/**
 * @description 定义点差表格数据
 */

const marketPointTree = ref<any>([])
const marketPointTableColumnsOptions = computed(() => {
  return dialogType.value !== 'view' ? marketPointTableColumns : viewMarketPointTableColumns
})
//保存当前选中的表格行
const selectedRow = ref<any>(null)

// 菜单状态
const menuVisible = ref(false)
const menuOptions = reactive({ x: 0, y: 0, zIndex: 3000 })
const currentRow = ref<any>(null)
const rightClickDialogVisible = ref(false)
const rightClickDialogType = ref<'account' | 'acceptOrders' | 'transfer' | 'deposit' | 'withdraw'>(
  'account',
)
const rightClickDialogTitleEnum = {
  account: '调整基本账户',
  acceptOrders: '设置停止接单金额',
  transfer: '设置持仓转移金额',
  deposit: '取款',
  withdraw: '存款',
}
const rightClickMarketForm = ref<any>({})
const rightClickMarketFormRules = ref<Record<string, any>>(accountFormItemRules)
const rightClickMarketFormItemOptions = ref(accountFormItemList)
const withdrawFormRef = ref()

// 计算调整后余额
const calculateAmountNew = () => {
  if (rightClickMarketForm.value.amount !== null && rightClickMarketForm.value.amount !== '') {
    rightClickMarketForm.value.amount_new =
      Number(rightClickMarketForm.value.amount_old) + Number(rightClickMarketForm.value.amount)
  }
}

// 监听调整金额变化，计算调整后余额
watch(
  () => rightClickMarketForm.value.amount,
  () => {
    if (rightClickDialogType.value === 'account') {
      calculateAmountNew()
    }
  },
)

// 行右键点击
const handleRowContextMenu = (row: any, column: any, event: any) => {
  console.log('handleRowContextMenu', row, column, event)
  if (userStore?.userInfo?.role_id !== 1 && userStore?.userInfo?.id !== row.wallet_capital.user_id)
    return
  event?.preventDefault()
  currentRow.value = row
  menuOptions.x = event?.clientX
  menuOptions.y = event?.clientY
  menuOptions.zIndex = 3000
  menuVisible.value = true
}

/**
 * @description 处理右键菜单
 * */
const handleAction = (key: 'account' | 'acceptOrders' | 'transfer' | 'deposit' | 'withdraw') => {
  console.log('handleAction', key, currentRow.value)
  if (!currentRow.value) return
  // 先重置表单数据，确保使用全新对象
  rightClickMarketForm.value = {}
  nextTick(() => {
    switch (key) {
      case 'account':
        rightClickMarketFormItemOptions.value = accountFormItemList
        rightClickMarketFormRules.value = accountFormItemRules
        rightClickMarketForm.value = {
          target_user_id: currentRow.value!.wallet_capital.user_id,
          username: currentRow.value!.username,
          currency: 'USD',
          amount_old: currentRow.value!.wallet_capital.amount,
          amount: null,
          amount_new: null,
        }
        break
      case 'acceptOrders':
        rightClickMarketFormItemOptions.value = acceptOrdersFormItemList
        rightClickMarketFormRules.value = acceptOrdersFormItemRules
        rightClickMarketForm.value = {
          target_user_id: currentRow.value!.wallet_capital.user_id,
          username: currentRow.value!.username,
          currency: 'USD',
          bail_stop_order_old: currentRow.value!.wallet_capital.bail_stop_order,
          bail_stop_order: '',
        }
        break
      case 'transfer':
        rightClickMarketFormItemOptions.value = transferFormItemList
        rightClickMarketFormRules.value = transferFormItemRules
        rightClickMarketForm.value = {
          target_user_id: currentRow.value!.wallet_capital.user_id,
          username: currentRow.value!.username,
          currency: 'USD',
          bail_change_order_old: currentRow.value!.wallet_capital.bail_change_order,
          bail_change_order: '',
        }
        break
      case 'deposit':
        // 获取当前行的角色ID
        const targetRoleId = currentRow.value!.role_id * 1
        // 设置取款表单配置
        rightClickMarketFormItemOptions.value = getWithdrawFormConfig(targetRoleId)
        rightClickMarketFormRules.value = getWithdrawFormRules(targetRoleId)
        // 获取取款渠道列表
        fetchWithdrawChannel()
        // 初始化表单数据
        rightClickMarketForm.value = {
          target_user_id: currentRow.value!.wallet_capital.user_id,
          username: currentRow.value!.username,
          currency: 'USD',
          // 各角色的最大金额
          commission_fee_handling_max: currentRow.value!.wallet_capital.commission_fee_handling || '0', // 手续费佣金最大值
          commission_point_diff_max: currentRow.value!.wallet_capital.commission_point_diff || '0', // 点差佣金最大值
          service_max: currentRow.value!.wallet_capital.service || '0', // 服务费最大值
          risk_max: currentRow.value!.wallet_capital.risk || '0', // 风险金最大值
          closing_profit_max: currentRow.value!.wallet_capital.closing_profit || '0', // 盈利最大值
          // 表单输入值
          withdraw_fee_handle: '',
          withdraw_point_diff: '',
          withdraw_service_fee: '',
          withdraw_risk_fee: '',
          withdraw_head_fee: '',
          // 钱包地址和渠道（必填）
          withdraw_address: '',
          channel_id: '',
        }
        break
      case 'withdraw':
        ElMessage.warning('暂无此功能')
        return
    }
    rightClickDialogType.value = key
    rightClickDialogVisible.value = true
  })
}

const handleRightClickDialogSubmit = async () => {
  try {
    switch (rightClickDialogType.value) {
      case 'account':
        await updateCapital({
          target_user_id: rightClickMarketForm.value.target_user_id,
          amount: rightClickMarketForm.value.amount,
        })
        break
      case 'acceptOrders':
        await editAgentBail({
          user_id: rightClickMarketForm.value.target_user_id,
          bail: null,
          bail_change_order: null,
          bail_stop_order: rightClickMarketForm.value.bail_stop_order,
        })
        break
      case 'transfer':
        await editAgentBail({
          user_id: rightClickMarketForm.value.target_user_id,
          bail: null,
          bail_change_order: rightClickMarketForm.value.bail_change_order,
          bail_stop_order: null,
        })
        break
      case 'deposit':
        // 取款提交由 handleWithdrawSubmit 内部处理弹窗关闭
        handleWithdrawSubmit()
        return
      case 'withdraw':
        ElMessage.warning('暂无此功能')
        break
    }
    rightClickDialogVisible.value = false
    // 刷新列表
    getMarketList()
  } catch (error) {
    console.error('操作失败', error)
  }
}

const handleRightClickDialogCancel = () => {
  rightClickDialogVisible.value = false
}

const handleRightClickDialogClose = () => {
  rightClickDialogVisible.value = false
}

// 取款渠道列表
const withdrawChannelOptions = ref<{ label: string; value: number }[]>([])

// 获取取款渠道列表
const fetchWithdrawChannel = async () => {
  try {
    const res = await getAgentWithdrawChannel()
    withdrawChannelOptions.value = res.map((item: any) => ({
      label: item.name,
      value: item.id,
    }))
  } catch (error) {
    console.error('获取取款渠道列表失败', error)
  }
}

// 处理取款提交
const handleWithdrawSubmit = async () => {
  // 验证表单
  if (!withdrawFormRef.value) return
  try {
    await withdrawFormRef.value.validate()
  } catch (error) {
    console.log('表单验证失败')
    return
  }
  
  const form = rightClickMarketForm.value
  
  // 构建提交参数
  const params = {
    user_id: form.target_user_id,
    amount: calculateTotalWithdrawAmount(form),
    channel_id: form.channel_id,
    withdraw_address: form.withdraw_address,
    withdraw_fee_handle: form.withdraw_fee_handle || '0',
    withdraw_point_diff: form.withdraw_point_diff || '0',
    withdraw_service_fee: form.withdraw_service_fee || '0',
    withdraw_head_fee: form.withdraw_head_fee || '0',
    withdraw_risk_fee: form.withdraw_risk_fee || '0',
  }
  
  try {
    startSubmitLoading()
    await agentWithdraw(params)
    ElMessage.success('取款申请提交成功')
    rightClickDialogVisible.value = false
    // 刷新列表
    getMarketList()
  } catch (error) {
    console.error('取款提交失败', error)
  } finally {
    stopSubmitLoading()
  }
}

// 计算取款总金额
const calculateTotalWithdrawAmount = (form: any): string => {
  const feeHandle = parseFloat(form.withdraw_fee_handle) || 0
  const pointDiff = parseFloat(form.withdraw_point_diff) || 0
  const serviceFee = parseFloat(form.withdraw_service_fee) || 0
  const headFee = parseFloat(form.withdraw_head_fee) || 0
  const riskFee = parseFloat(form.withdraw_risk_fee) || 0
  return String(feeHandle + pointDiff + serviceFee + headFee + riskFee)
}

// 验证输入金额不能超过最大值
const validateWithdrawAmount = (value: string, maxValue: string): boolean => {
  if (!value || !maxValue) return true
  return parseFloat(value) <= parseFloat(maxValue)
}

// 处理取款金额输入
const handleWithdrawAmountInput = (field: string) => {
  const form = rightClickMarketForm.value
  const maxFieldMap: Record<string, string> = {
    withdraw_fee_handle: 'commission_fee_handling_max',
    withdraw_point_diff: 'commission_point_diff_max',
    withdraw_service_fee: 'service_max',
    withdraw_risk_fee: 'risk_max',
    withdraw_head_fee: 'closing_profit_max',
  }
  const maxField = maxFieldMap[field]
  if (!maxField) return
  
  const currentValue = parseFloat(form[field]) || 0
  const maxValue = parseFloat(form[maxField]) || 0
  
  if (currentValue > maxValue) {
    ElMessage.warning(`输入金额不能超过最大可取金额 ${maxValue}`)
    // 自动截断到最大值
    form[field] = String(maxValue)
  }
}

/**
 * @description 数据处理方法
 * 映射表格数据
 */
const mapMarketTree = (data: any) => {
  console.log('mapMarketTree', data)
  return data.map((item: any) => ({
    ...item,
    id: item.id, //id
    agentRelation: item.path_name, //代理关系
    accountName: item.username, //账户名
    level: item.role_id * 1 === 5 && item.type * 1 === 2 ? 6 : item.role_id, //级别
    is_base_ts: item.is_base_ts, //是否为承接特殊做市
    base_ts: item.base_ts, //承接特殊做市ID
    basicAccount: item.wallet_capital.amount, //基本账户
    margin: item.wallet_capital.bail, //保证金
    stopOrderMargin: item.wallet_capital.bail_stop_order, //停止接单保证金
    positionTransferMargin: item.wallet_capital.bail_change_order, //持仓转移保证金
    positionRatio: (item.wallet_capital.toucun_percent * 1).toFixed(2), //头寸比率
    pointSpreadCommission: item.wallet_capital.commission_point_diff, //点差返佣
    commissionRatio: (item.wallet_capital.fee_handling_percent * 1).toFixed(2), //手续费比例
    commissionReturn: item.wallet_capital.commission_fee_handling, //手续费返佣
    floatProfitLoss: '后续添加', //浮动盈亏（已废弃，使用transactionStore动态获取）
    closeProfitLoss: item.wallet_capital.closing_profit, //平仓盈亏
    riskMargin: item.wallet_capital.risk, //风险保证金
    serviceFee: item.wallet_capital.service, //服务费
    flag: item.role_id * 1 === 5 ? item.type * 1 : null,
    //使用这个字段来判断是否是做市商
    mobile: item.mobile || '--',
    email: item.email || '--',
    // 保存账户ID用于动态获取浮动盈亏
    accountId: item.wallet_capital.account_id,
  }))
}

/**
 * @description 统一处理做市商表单联动逻辑
 * @param type 联动类型：level(级别变更) / parentAccountName(上级账户变更)
 * @param value 选中的值（级别值/上级账户名）
 * @returns {Promise<void>}
 */
const handleMarketFormLinkage = async (type: 'level' | 'parentAccountName', value: string) => {
  try {
    let flag: number | undefined = undefined
    // 1. 级别变更：获取所属上级账户列表
    if (type === 'level') {
      // 清空关联数据，避免脏数据
      marketForm.value.parentAccountName = ''
      marketFormOptionsMap.value.parentAccountName = []
      marketPointTree.value = []

      if (!value) return // 未选择级别，直接返回

      // 调用获取上级账户列表接口
      const levelNum = Number(marketForm.value?.level)
      if (levelNum === 5) flag = 1
      if (levelNum === 6) flag = 2
      console.log('datasssssssssssss', marketForm.value) 
      const data = await getParAgentListApi({ role_id: +value === 6 ? 5 : value, flag })
      // 格式化下拉选项
      marketFormOptionsMap.value.parentAccountName = data.map((item: any) => ({
        label: item.username,
        value: String(item.id), // 按实际接口返回字段调整
        row: item,
      }))
    }

    // 2. 上级账户变更：获取点差列表（仅添加模式）
    if (type === 'parentAccountName' && dialogType.value === 'add') {
      // 清空点差数据
      marketPointTree.value = []

      if (!value) return // 未选择上级账户，直接返回

      // 新增：根据选中的value匹配完整的上级账户对象
      const rulesData = marketFormOptionsMap.value.parentAccountName.find(
        (item) => item.value === value,
      )
      if (!rulesData) return // 未找到匹配项，直接返回

      console.log('rulesData:', rulesData);
      // 赋值最大头寸和手续费比例
      marketForm.value.maxPositionRatio = String(rulesData.row.wallet_capital.toucun_percent)
      marketForm.value.maxCommissionRatio = String(rulesData.row.wallet_capital.fee_handling_percent)

      // 调用获取点差列表接口
      const data = await getPointDiffConfigListApi({ user_id: value, flag })
      // 格式化点差表格数据（按实际需求调整）
      marketPointTree.value = data.map((item: any) => ({
        ...item,
        varietyName: item.name,
        varietyCode: item.code,
        point_diff: item.target_point_diff, // 添加时：可分配点差取 target_point_diff
        pointDifference: 0, // 添加时已分配点差初始化为0
        assignedPointDifference: '',
      }))
    }
  } catch (error) {
    console.error(`[${type}] 联动数据获取失败:`, error)
  }
}

/**
 * @description 统一数据获取
 */
//获取做市商列表
const getMarketList = async () => {
  startLoading()
  const params = {
    page: currentPage.value,
    page_size: pageSize.value,
    user_name: marketSearchForm.value.accountName,
  }
  const data = await getMarketListApi(params)
  // 表格数据
  marketTree.value = mapMarketTree(data.data)
    total.value = data.total
  requestAllMarketFloatProfit()
  //分页数据
  stopLoading()
  currentPage.value = data.current_page
  pageSize.value = Number(data.per_page)
}

//获取风控模板选列表
const getRiskTemplateList = async () => {
  const data = await getRiskTemplateListApi()
  // 格式化下拉选项
  marketFormOptionsMap.value.riskControlTemplate = data.map((item: any) => ({
    label: item.name,
    value: item.id, // 按实际接口返回字段调整
  }))
}

//获取承接特殊做市选项
const getBasetsOptions = async () => {
  const data = await getBasetsOptionsApi()
  // 格式化下拉选项
  marketFormOptionsMap.value.base_ts = data.map((item: any) => ({
    label: item.username,
    value: item.id, // 按实际接口返回字段调整
  }))
}

/**
 * @description 请求所有做市商的浮动盈亏数据
 */
const requestAllMarketFloatProfit = () => { 
      transactionStore.requestMarketFloatProfit()
}

/**
 * @description 页面加载完成后需要获取的数据
 */
onMounted(async () => {
  getMarketList()
  getRiskTemplateList()
  
  // 初始化 MQTT 连接（已登录且未连接时才初始化）
  if (userStore.isLoggedIn && !transactionStore.isConnected()) {
    transactionStore.initMarketConditionsMQTT()
  }
})
 

// 页面卸载时不主动断开连接（由logout统一处理）

/**
 * @description 监听数据变化
 */

// 监听级别变化
watch(
  () => marketForm.value.level,
  (newLevel) => {
    handleMarketFormLinkage('level', newLevel)
  },
  { immediate: false }, // 初始不触发，选择后触发
)

// 监听上级账户变化
watch(
  () => marketForm.value.parentAccountName,
  (newParentAccountName) => {
    handleMarketFormLinkage('parentAccountName', newParentAccountName)
  },
  { immediate: false },
)

// 监听是否为承接特殊做市变化
watch(
  () => marketForm.value.is_base_ts,
  (newVal) => {
    if (newVal === 1) {
      marketForm.value.base_ts = ''
    }
  },
)

// 是否显示承接特殊做市下拉框
const showBaseTsSelect = computed(() => {
  return marketForm.value.level === '3' && marketForm.value.is_base_ts === 2
})

// 是否禁用承接特殊做市单选框（编辑时禁用）
const isBaseTsDisabled = computed(() => {
  return dialogType.value === 'edit'
})

/**
 * @description 定义表单初始值方法
 */
// 1. 定义表单初始值常量（方便复用）
const initMarketForm = {
  email: '',
  phone: '',
  countryCode: '+86',
  accountName: '',
  level: '',
  is_base_ts: 1,
  base_ts: '',
  parentAccountName: '',
  riskControlTemplate: '',
  positionRatio: '',
  commissionRatio: '',
  maxPositionRatio: '',
  maxCommissionRatio: '',
}

/**
 * @description search方法
 */
// 搜索
const handleSearch = async () => {
  await getMarketList()
}

// 重置
const handleReset = async () => {
  marketSearchForm.value = {
    accountName: '',
  }
  currentPage.value = 1
  pageSize.value = 10
  await getMarketList()
}

// 添加做市商
const handleAddMarket = async () => {
  getBasetsOptions()
  dialogVisible.value = true
  dialogTitle.value = '添加'
  dialogType.value = 'add'
  // 2. 重置表单数据
  marketForm.value = { ...initMarketForm }
}

// 编辑做市商
const handleEditMarket = async () => {
  getBasetsOptions()
  const row = selectedRow.value
  console.log('rowrowrowrowrow', row)

  // 解析上级ID
  const getParentIdFromPath = (path: string, level: number) => {
    const segments = path.split('/').filter(Boolean)
    const levelNum = Number(level)
    const parentIndex = levelNum - 2
    if (levelNum <= 1 || segments.length <= parentIndex) return ''
    return segments[parentIndex]
  }
  const parentId = getParentIdFromPath(row.path, row.level)
  console.log('解析后的上级ID:', parentId)

  // 先初始化表单数据
  marketForm.value = {
    ...initMarketForm,
    accountName: row.accountName || '',
    level: row.level+ '' || '',
    is_base_ts: row.is_base_ts || 1,
    base_ts: row.base_ts || '',
    parentAccountName: '',
    riskControlTemplate: row.wallet_capital.risk_control_id || '',
    positionRatio: row.positionRatio || '',
    commissionRatio: row.commissionRatio || '',
    maxPositionRatio: row.wallet_capital.toucun_percent || '',
    maxCommissionRatio: row.wallet_capital.fee_handling_percent || '',
  }
  console.log(marketForm.value)

  try {
    // 先设置编辑模式，避免 watch 触发获取点差接口
    dialogType.value = 'edit'

    // 先加载上级选项
    await handleMarketFormLinkage('level', marketForm.value.level)
    if (parentId) {
      marketForm.value.parentAccountName = parentId
    }

    // 再加载点差数据
    if (row.id) {
      const data = await getPointDiffConfigListApi({ user_id: row.id })
      marketPointTree.value = data.map((item: any) => ({
        ...item,
        varietyName: item.name,
        varietyCode: item.code,
        point_diff: item.point_diff, // 编辑时：可分配点差取 point_diff
        pointDifference: item.target_point_diff,
        assignedPointDifference: item.target_point_diff || '',
      }))
    }

    // 所有数据加载完成后，再打开抽屉
    dialogVisible.value = true
    dialogTitle.value = '编辑'
  } catch (error) {
    console.error('编辑数据加载失败:', error)
  }
}

/**
 * @description 表格方法
 */
// 查看点差
const handleViewPointDiff = async (row: any) => {
  try {
    const data = await getPointDiffConfigListApi({ user_id: row.id })
    marketPointTree.value = data.map((item: any) => ({
      ...item,
      varietyName: item.name,
      varietyCode: item.code,
      pointDifference: item.point_diff,
      assignedPointDifference: item.target_point_diff || '',
    }))

    // 数据加载完成后再打开抽屉
    dialogVisible.value = true
    dialogTitle.value = '查看点差'
    dialogType.value = 'view'
  } catch (error) {
    console.error('加载点差数据失败:', error)
  }
}

// 点击行事件
const handleRowClick = (row: any) => {
  if (!row) {
    selectedRow.value = null
    return
  }
  selectedRow.value = row
}

/**
 * @description 分页方法
 */
// 分页变更
const handlePaginationChange = async (page: { currentPage: number; pageSize: number }) => {
  currentPage.value = page.currentPage
  pageSize.value = page.pageSize
  await getMarketList()
}

/**
 * @description dialog方法
 */
// 提交之前构造数据:格式化点差为 { "1":"42", "2":"38" } 格式的对象
const formatPointDiffToObject = () => {
  if (!marketPointTree.value || !marketPointTree.value.length) return {}

  // 初始化空对象
  const pointDiffObj: Record<string, string> = {}

  console.log(marketPointTree.value)

  // 遍历表格数据，构造 { 编号: 点差值 } 的对象
  for (let i = 0; i < marketPointTree.value.length; i++) {
    const item = marketPointTree.value[i]
    if (item.pointDifference > item.point_diff) {
      ElMessage.error('已分配差值不能大于可分配点差')
      return false
    }
    pointDiffObj[String(item.id)] = item.pointDifference || '0'
  }

  return pointDiffObj // 返回纯对象，而非数组
}

//提交
const handleSubmit = async () => {
  startSubmitLoading()
  try {
    // console.log('提交', marketPointTree.value);
    await marketFormRef.value?.validate()
    const pointDiffObj = formatPointDiffToObject()
    console.log('pointDiffObj', pointDiffObj)
    if (!pointDiffObj) return
    if (dialogType.value === 'add') {
      const params: Record<string, any> = {
        role_id: marketForm.value.level,
        reg_type: activeTab.value === 'email' ? '1' : '2',
        username: marketForm.value.accountName,
        par_user_id: marketForm.value.parentAccountName,
        mobile: activeTab.value === 'phone' ? marketForm.value.phone : '',
        email: activeTab.value === 'email' ? marketForm.value.email : '',
        password: '888888',
        toucun_percent: marketForm.value.positionRatio,
        fee_handling_percent: marketForm.value.commissionRatio,
        point_diffs_json: JSON.stringify(pointDiffObj),
        risk_control_id: marketForm.value.riskControlTemplate,
        fee_setting_id: '',
      }
      if (marketForm.value.level === '5') params.flag = 1
      if (marketForm.value.level === '6') {
        params.flag = 2
        params.role_id = '5'
      }
      // 添加承接特殊做市字段（统一传递，未选择时传null）
      params.is_base_ts = marketForm.value.level === '3' ? marketForm.value.is_base_ts : null
      params.base_ts = marketForm.value.level === '3' && marketForm.value.is_base_ts !== 1 ? marketForm.value.base_ts : null
      await addMarketApi(params)
      // 5. 刷新表格数据
      await getMarketList()
      dialogVisible.value = false
      marketForm.value = { ...initMarketForm }
    } else if (dialogType.value === 'edit') {
      let flag = null
      if (selectedRow.value.role_id * 1 === 5 && selectedRow.value.type * 1 === 1) flag = 1
      if (selectedRow.value.role_id * 1 === 6 && selectedRow.value.type * 1 === 2) flag = 2
      const params: Record<string, any> = {
        user_id: selectedRow.value.id,
        username: marketForm.value.accountName,
        toucun_percent: marketForm.value.positionRatio,
        point_diffs_json: JSON.stringify(pointDiffObj),
        risk_control_id: marketForm.value.riskControlTemplate,
        fee_handling_percent: marketForm.value.commissionRatio,
        flag: flag,
        fee_setting_id: '',
      }
      // 添加承接特殊做市字段（统一传递，未选择时传null）
      params.is_base_ts = marketForm.value.level === '3' ? marketForm.value.is_base_ts : null
      params.base_ts = marketForm.value.level === '3' && marketForm.value.is_base_ts !== 1 ? marketForm.value.base_ts : null
      // 4. 调用编辑接口
      await editMarketApi(params)
      // 5. 刷新表格数据
      await getMarketList()
      dialogVisible.value = false
      marketForm.value = { ...initMarketForm }
    }
  } finally {
    stopSubmitLoading()
  }
}

// 取消
const handleCancel = async () => {
  dialogVisible.value = false
  // 重置点差数据和drawer类型
}
</script>

<style scoped lang="scss">
:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

.market {
  .search-container {
    :deep(.el-form) {
      .el-form-item {
        flex: none;
      }
    }
  }
}

.phone-email {
  display: flex;
  flex: 1;

  .tab-btn {
    display: flex;
    margin-right: 10px;

    .el-button {
      height: 32px;
      margin-left: 0;
    }
  }

  .group {
    display: flex;
    flex: 1;

    .el-form-item {
      flex: 1;
    }

    .phone-item {
      :deep(.el-form-item__content) {
        flex-wrap: nowrap;
      }

      .el-select {
        width: 120px;
      }
    }
  }
}

.table-container {
  max-width: 100%;
  height: 100%;
}

// 抽屉样式
.drawer-form {
  flex-shrink: 0;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.drawer-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
  max-height: 100%;

  .table-header {
    flex-shrink: 0;
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
  }

  .table-wrapper {
    flex: 1;
    min-height: 0;
  }
}

.drawer-footer {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
// 浮动盈亏样式
.profit-positive {
  color: #67C23A;
}

.profit-negative {
  color: #F56C6C;
}

// 取款表单样式
.withdraw-form {
  padding: 0 10px;

  .form-section {
    margin-bottom: 24px;

    .section-title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid #ebeef5;
    }

    .el-form-item {
      margin-bottom: 16px;
    }
  }
}
</style>
