<template>
  <ArtTableFullScreen>
    <div class="withdrawal-settings-page" id="table-full-screen">
      <!-- 配置列表 -->
      <ElCard shadow="never" class="art-table-card">
        <!-- 表格头部 -->
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <ElButton type="primary" @click="showDialog" v-permission="'withdrawal_settings:add'"
              >新增配置</ElButton
            >
          </template>
        </ArtTableHeader>

        <!-- 表格 -->
        <ArtTable
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :data="settingsList"
          :marginTop="10"
        >
          <template #default>
            <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </ArtTable>
      </ElCard>

      <!-- 新增配置对话框 -->
      <ElDialog v-model="dialogVisible" title="新增提现配置" width="500px">
        <ElForm ref="formRef" :model="form" :rules="rules" label-width="110px">
          <ElFormItem label="最低提现金额" prop="min_withdrawal_amount">
            <ElInputNumber
              v-model="form.min_withdrawal_amount"
              :min="1"
              :precision="2"
              :step="10"
              style="width: 100%"
            />
            <div class="form-tip">单位：元</div>
          </ElFormItem>

          <ElFormItem label="手续费率" prop="fee_rate">
            <ElInputNumber
              v-model="form.fee_rate"
              :min="0"
              :max="100"
              :precision="2"
              :step="0.1"
              style="width: 100%"
            />
            <div class="form-tip">单位：%（百分比）</div>
          </ElFormItem>

          <ElFormItem label="每日提现次数" prop="daily_withdrawal_limit">
            <ElInputNumber
              v-model="form.daily_withdrawal_limit"
              :min="1"
              :max="100"
              :step="1"
              style="width: 100%"
            />
            <div class="form-tip">单位：次</div>
          </ElFormItem>
        </ElForm>
        <template #footer>
          <div class="dialog-footer">
            <ElButton @click="dialogVisible = false">取消</ElButton>
            <ElButton type="primary" @click="handleSubmit(formRef)" :loading="submitLoading">
              提交
            </ElButton>
          </div>
        </template>
      </ElDialog>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { CommissionService } from '@/api/modules'
  import { ElMessage, ElTag } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import type { WithdrawalSettingItem } from '@/types/api/commission'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { useAuth } from '@/composables/useAuth'
  import { formatDateTime, formatMoney, formatFeeRate } from '@/utils/business/format'

  defineOptions({ name: 'WithdrawalSettings' })

  const { hasAuth } = useAuth()

  const dialogVisible = ref(false)
  const loading = ref(false)
  const submitLoading = ref(false)
  const tableRef = ref()
  const formRef = ref<FormInstance>()

  // 配置列表
  const settingsList = ref<WithdrawalSettingItem[]>([])

  // 表单数据（使用元和百分比）
  const form = reactive({
    min_withdrawal_amount: 100,
    fee_rate: 0.2,
    daily_withdrawal_limit: 3
  })

  // 表单验证规则
  const rules = reactive<FormRules>({
    min_withdrawal_amount: [
      { required: true, message: '请输入最低提现金额', trigger: 'blur' },
      { type: 'number', min: 1, message: '最低提现金额必须大于0', trigger: 'blur' }
    ],
    fee_rate: [
      { required: true, message: '请输入手续费率', trigger: 'blur' },
      { type: 'number', min: 0, max: 100, message: '手续费率必须在0-100之间', trigger: 'blur' }
    ],
    daily_withdrawal_limit: [
      { required: true, message: '请输入每日提现次数', trigger: 'blur' },
      { type: 'number', min: 1, message: '每日提现次数必须大于0', trigger: 'blur' }
    ]
  })

  // 列配置
  const columnOptions = [
    { label: '最低提现金额', prop: 'min_withdrawal_amount' },
    { label: '手续费率', prop: 'fee_rate' },
    { label: '每日提现次数', prop: 'daily_withdrawal_limit' },
    { label: '到账天数', prop: 'arrival_days' },
    { label: '是否生效', prop: 'is_active' },
    { label: '创建人', prop: 'creator_name' },
    { label: '创建时间', prop: 'created_at' }
  ]

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'min_withdrawal_amount',
      label: '最低提现金额',
      formatter: (row: WithdrawalSettingItem) => formatMoney(row.min_withdrawal_amount)
    },
    {
      prop: 'fee_rate',
      label: '手续费率',
      formatter: (row: WithdrawalSettingItem) => formatFeeRate(row.fee_rate)
    },
    {
      prop: 'daily_withdrawal_limit',
      label: '每日提现次数',
      formatter: (row: WithdrawalSettingItem) => `${row.daily_withdrawal_limit} 次`
    },
    {
      prop: 'arrival_days',
      label: '到账天数',
      formatter: (row: WithdrawalSettingItem) => {
        return row.arrival_days === 0 ? '实时到账' : `${row.arrival_days} 天`
      }
    },
    {
      prop: 'is_active',
      label: '是否生效',
      formatter: (row: WithdrawalSettingItem) => {
        return h(ElTag, { type: row.is_active ? 'success' : 'info' }, () =>
          row.is_active ? '生效中' : '已失效'
        )
      }
    },
    {
      prop: 'creator_name',
      label: '创建人',
      formatter: (row: WithdrawalSettingItem) => row.creator_name || '-'
    },
    {
      prop: 'created_at',
      label: '创建时间',
      formatter: (row: WithdrawalSettingItem) => formatDateTime(row.created_at)
    }
  ])

  onMounted(() => {
    loadSettingsList()
  })

  // 加载配置列表
  const loadSettingsList = async () => {
    loading.value = true
    try {
      const res = await CommissionService.getWithdrawalSettings()
      if (res.code === 0) {
        settingsList.value = res.data.items || []
      }
    } catch (error) {
      console.error('获取配置列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 刷新数据
  const handleRefresh = () => {
    loadSettingsList()
  }

  // 显示新增对话框
  const showDialog = () => {
    dialogVisible.value = true
    // 重置表单
    form.min_withdrawal_amount = 100
    form.fee_rate = 0.2
    form.daily_withdrawal_limit = 3
    formRef.value?.clearValidate()
  }

  // 提交表单
  const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        try {
          // 转换单位：元 -> 分，百分比 -> 基点
          const params = {
            min_withdrawal_amount: Math.round(form.min_withdrawal_amount * 100), // 元转分
            fee_rate: Math.round(form.fee_rate * 100), // 百分比转基点
            daily_withdrawal_limit: form.daily_withdrawal_limit
          }

          await CommissionService.createWithdrawalSetting(params)
          ElMessage.success('新增配置成功')
          dialogVisible.value = false
          formEl.resetFields()
          loadSettingsList()
        } catch (error) {
          console.error(error)
        } finally {
          submitLoading.value = false
        }
      }
    })
  }
</script>

<style lang="scss" scoped>
  .withdrawal-settings-page {
    .form-tip {
      margin-top: 4px;
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
</style>
