<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? $t('page.form.dialogTitleAdd') : $t('page.form.dialogTitleEdit')"
    width="600px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item :label="$t('page.form.user')" prop="player_id">
        <el-select
          v-model="formData.player_id"
          :placeholder="$t('page.form.placeholderUser')"
          clearable
          filterable
          style="width: 100%"
          :disabled="dialogType === 'edit'"
          @change="onPlayerChange"
        >
          <el-option
            v-for="item in playerOptions"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('page.form.type')" prop="type">
        <el-select
          v-model="formData.type"
          :placeholder="$t('page.form.placeholderType')"
          clearable
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        >
          <el-option :label="$t('page.form.typeRecharge')" :value="0" />
          <el-option :label="$t('page.form.typeWithdraw')" :value="1" />
          <el-option :label="$t('page.form.typeBuyTicket')" :value="2" />
          <el-option :label="$t('page.form.typeAdminAdd')" :value="3" />
          <el-option :label="$t('page.form.typeAdminSub')" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('page.form.coinChange')" prop="coin">
        <el-input-number
          v-model="formData.coin"
          :placeholder="$t('page.form.placeholderCoinChange')"
          :precision="2"
          style="width: 100%"
          @change="onCoinChange"
          :disabled="dialogType === 'edit'"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.walletBefore')" prop="wallet_before">
        <el-input-number
          v-model="formData.wallet_before"
          :placeholder="$t('page.form.placeholderWalletBefore')"
          :precision="2"
          disabled
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.walletAfter')" prop="wallet_after">
        <el-input-number
          v-model="formData.wallet_after"
          :placeholder="$t('page.form.placeholderWalletAfter')"
          :precision="2"
          disabled
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="$t('form.labelRemark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          :placeholder="$t('page.form.placeholderRemark')"
          maxlength="500"
          show-word-limit
          :disabled="dialogType === 'edit'"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleSubmit">{{ $t('table.form.submit') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '../../../api/player_wallet_record/index'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    modelValue: boolean
    dialogType: string
    data?: Record<string, any>
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dialogType: 'add',
    data: undefined
  })

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()

  /** 玩家下拉选项（id、username） */
  const playerOptions = ref<{ id: number; username: string }[]>([])

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

  const rules = reactive<FormRules>({
    player_id: [{ required: true, message: '请选择用户', trigger: 'change' }],
    coin: [{ required: true, message: '平台币变化必填', trigger: 'blur' }],
    type: [{ required: true, message: '请选择类型', trigger: 'change' }]
  })

  const initialFormData = {
    id: null as number | null,
    player_id: null as number | null,
    coin: 0 as number,
    type: null as number | null,
    wallet_before: 0 as number,
    wallet_after: 0 as number,
    remark: '' as string
  }

  const formData = reactive({ ...initialFormData })

  /** 选择用户后拉取当前平台币作为钱包操作前 */
  async function onPlayerChange(playerId: number | null) {
    if (playerId == null) {
      formData.wallet_before = 0
      calcWalletAfter()
      return
    }
    try {
      const res = await api.getPlayerWalletBefore(playerId)
      const before = res?.wallet_before ?? 0
      formData.wallet_before = Number(before)
      calcWalletAfter()
    } catch {
      formData.wallet_before = 0
      calcWalletAfter()
    }
  }

  /** 平台币变化时重算钱包操作后 */
  function onCoinChange() {
    calcWalletAfter()
  }

  /** 钱包操作后 = 钱包操作前 + 平台币变化 */
  function calcWalletAfter() {
    const before = Number(formData.wallet_before) || 0
    const coin = Number(formData.coin) || 0
    formData.wallet_after = Math.round((before + coin) * 100) / 100
  }

  watch(
    () => props.modelValue,
    async (open) => {
      if (open) {
        initPage()
        try {
          const list = await api.getPlayerOptions()
          playerOptions.value = Array.isArray(list) ? list : []
        } catch {
          playerOptions.value = []
        }
      }
    }
  )

  const initPage = async () => {
    Object.assign(formData, initialFormData)
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  const numKeys = ['id', 'player_id', 'coin', 'type', 'wallet_before', 'wallet_after']

  const initForm = () => {
    if (!props.data) return
    for (const key of Object.keys(formData)) {
      if (!(key in props.data)) continue
      const val = props.data[key]
      if (numKeys.includes(key)) {
        if (key === 'id' || key === 'player_id' || key === 'type') {
          ;(formData as any)[key] = val != null && val !== '' ? Number(val) : null
        } else {
          ;(formData as any)[key] = val != null && val !== '' ? Number(val) : 0
        }
      } else {
        ;(formData as any)[key] = val ?? ''
      }
    }
  }

  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }

  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      calcWalletAfter()
      const payload = { ...formData }
      if (props.dialogType === 'add') {
        await api.save(payload)
        ElMessage.success('新增成功')
      } else {
        await api.update(payload)
        ElMessage.success('修改成功')
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
</script>
