<template>
  <el-dialog
    v-model="visible"
    :title="$t('page.form.dialogTitleEdit')"
    width="600px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" 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
        >
          <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
        >
          <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"
          :step="1"
          style="width: 100%"
          disabled
        />
      </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
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">{{ $t('form.close') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '../../../api/player_wallet_record/index'
  import { getChannelDeptRequestParams } from '@/composables/useChannelDeptScope'
  import type { FormInstance } 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: 'edit',
    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 initialFormData: {
    id: number | null
    player_id: number | null
    coin: number
    type: number | null
    wallet_before: number
    wallet_after: number
    remark: string
  } = {
    id: null,
    player_id: null,
    coin: 0,
    type: null,
    wallet_before: 0,
    wallet_after: 0,
    remark: ''
  }

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

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

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

  function normalizeMoney2(val: unknown, fallback: number): number {
    if (val === '' || val === null || val === undefined) return fallback
    const n = typeof val === 'number' ? val : Number(val)
    if (!Number.isFinite(n)) return fallback
    return Number(n.toFixed(2))
  }

  const initForm = () => {
    if (!props.data) return

    formData.id = props.data.id != null && props.data.id !== '' ? Number(props.data.id) : null
    formData.player_id =
      props.data.player_id != null && props.data.player_id !== '' ? Number(props.data.player_id) : null
    formData.type = props.data.type != null && props.data.type !== '' ? Number(props.data.type) : null
    formData.coin = normalizeMoney2(props.data.coin, 0)
    formData.wallet_before = normalizeMoney2(props.data.wallet_before, 0)
    formData.wallet_after = normalizeMoney2(props.data.wallet_after, 0)
    formData.remark = props.data.remark ?? ''
  }

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