<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="450px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <!-- 当前余额/积分/钻石 -->
      <el-form-item :label="currentLabel">
        <span class="current-value">{{ currentValueDisplay }}</span>
      </el-form-item>

      <!-- 操作类型 -->
      <el-form-item label="操作类型" prop="operation">
        <el-radio-group v-model="formData.operation">
          <el-radio :value="1">充值（增加）</el-radio>
          <el-radio :value="2">扣除（减少）</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 金额输入 -->
      <el-form-item :label="amountLabel" prop="amount">
        <el-input-number
          v-model="formData.amount"
          :min="0.01"
          :max="999999999"
          :precision="precision"
          :step="step"
          style="width: 100%"
          placeholder="请输入金额"
        />
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入操作备注（选填）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 操作预览 -->
      <el-form-item label="操作预览">
        <div class="preview-info">
          <span>{{ currentLabel }}：{{ currentValueDisplay }}</span>
          <span class="operation-symbol">{{ formData.operation === 1 ? '+' : '-' }}</span>
          <span class="amount-value">{{ formData.amount || 0 }}</span>
          <span class="result-symbol">=</span>
          <span :class="['result-value', resultClass]">{{ resultValueDisplay }}</span>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { changeUserMoney, type UserMoneyChangeRequest, type UserListItem } from '@/api/business/user'
import { getAppSetting, type AppSetting } from '@/api/business/config'

interface Props {
  modelValue: boolean
  user: UserListItem | null
  type: number  // 1-余额 2-积分 3-钻石
  action?: 'add' | 'sub'  // 预设操作类型
}

const props = withDefaults(defineProps<Props>(), {
  action: 'add'
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const appSetting = ref<AppSetting>()

const formData = reactive<UserMoneyChangeRequest>({
  type: 1,
  amount: 0,
  operation: 1,
  remark: ''
})

// 获取应用设置
const loadAppSetting = async () => {
  try {
    const res = await getAppSetting()
    if (res.data?.value) {
      appSetting.value = res.data.value
    }
  } catch (error) {
    console.error('获取应用设置失败:', error)
  }
}

// 组件挂载时加载配置
onMounted(() => {
  loadAppSetting()
})

// 表单验证规则
const formRules = computed<FormRules>(() => ({
  operation: [{ required: true, message: '请选择操作类型', trigger: 'change' }],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (formData.operation === 2 && value > currentValue.value) {
          callback(new Error(`扣除金额不能超过当前${typeLabel.value}`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}))

// 类型标签 - 从系统配置中获取
const typeLabel = computed(() => {
  if (!appSetting.value) {
    // 默认值
    const labels: Record<number, string> = { 1: '钻石', 2: 'HH币', 3: '哈尼券' }
    return labels[props.type] || '钻石'
  }
  
  const labels: Record<number, string> = {
    1: appSetting.value.balance_name || '钻石',      // 余额/钻石
    2: appSetting.value.currency1_name || 'HH币',    // 积分/HH币
    3: appSetting.value.currency2_name || '哈尼券'   // 钻石/哈尼券
  }
  return labels[props.type] || '钻石'
})

// 对话框标题
const dialogTitle = computed(() => {
  return `${typeLabel.value}变动`
})

// 当前值标签
const currentLabel = computed(() => `当前${typeLabel.value}`)

// 金额输入标签
const amountLabel = computed(() => `${typeLabel.value}数量`)

// 当前值
const currentValue = computed(() => {
  if (!props.user) return 0
  const valueMap: Record<number, number> = {
    1: props.user.balance || 0,
    2: props.user.integral || 0,
    3: props.user.diamond || 0
  }
  return valueMap[props.type] || 0
})

// 当前值显示
const currentValueDisplay = computed(() => {
  if (props.type === 1) {
    return `¥${currentValue.value.toFixed(2)}`
  }
  return currentValue.value.toString()
})

// 精度和步长
const precision = computed(() => props.type === 1 ? 2 : 0)
const step = computed(() => props.type === 1 ? 1 : 1)

// 结果值
const resultValue = computed(() => {
  const amount = formData.amount || 0
  if (formData.operation === 1) {
    return currentValue.value + amount
  } else {
    return Math.max(0, currentValue.value - amount)
  }
})

// 结果值显示
const resultValueDisplay = computed(() => {
  if (props.type === 1) {
    return `¥${resultValue.value.toFixed(2)}`
  }
  return resultValue.value.toString()
})

// 结果样式
const resultClass = computed(() => {
  if (formData.operation === 1) return 'positive'
  return resultValue.value < currentValue.value ? 'negative' : ''
})

// 监听对话框打开，初始化表单
watch(() => props.modelValue, (val) => {
  if (val) {
    formData.type = props.type
    formData.operation = props.action === 'add' ? 1 : 2
    formData.amount = 0
    formData.remark = ''
    formRef.value?.resetFields()
  }
})

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 提交表单
const handleSubmit = async () => {
  if (!props.user) {
    ElMessage.warning('用户信息不存在')
    return
  }

  const valid = await formRef.value?.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    await changeUserMoney(props.user.id, formData)
    ElMessage.success('操作成功')
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
.current-value {
  color: #e6a23c;
  font-weight: 600;
  font-size: 16px;
}

.preview-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.operation-symbol {
  font-weight: 600;
  color: #409eff;
}

.amount-value {
  color: #409eff;
  font-weight: 500;
}

.result-symbol {
  color: #909399;
}

.result-value {
  font-weight: 600;
}

.result-value.positive {
  color: #67c23a;
}

.result-value.negative {
  color: #f56c6c;
}
</style>
