<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.player')" prop="player_id">
        <el-select
          v-model="formData.player_id"
          :placeholder="$t('page.form.placeholderPlayer')"
          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.useCoins')" prop="use_coins">
        <el-input-number
          v-model="formData.use_coins"
          :placeholder="$t('page.form.placeholderUseCoins')"
          :min="0"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.paidDrawCount')" prop="paid_ticket_count">
        <el-input-number
          v-model="formData.paid_ticket_count"
          :placeholder="$t('page.form.placeholderPaidDrawCount')"
          :min="0"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.freeDrawCount')" prop="free_ticket_count">
        <el-input-number
          v-model="formData.free_ticket_count"
          :placeholder="$t('page.form.placeholderFreeDrawCount')"
          :min="0"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.totalDrawCount')" prop="total_ticket_count">
        <el-input-number
          :model-value="totalTicketCountComputed"
          :placeholder="$t('page.form.placeholderTotalDrawCount')"
          :min="0"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('form.labelRemark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          :placeholder="$t('page.form.placeholderRemark')"
          maxlength="500"
          show-word-limit
          style="width: 100%"
          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_ticket_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>()

  /**
   * 弹窗显示状态双向绑定
   */
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

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

  /** total_ticket_count = paid_ticket_count + free_ticket_count（只读展示） */
  const totalTicketCountComputed = computed(() => {
    const paid = Number(formData.paid_ticket_count) || 0
    const free = Number(formData.free_ticket_count) || 0
    return paid + free
  })

  /**
   * 初始数据
   */
  const initialFormData = {
    id: null,
    player_id: null,
    use_coins: null as number | null,
    total_ticket_count: null as number | null,
    paid_ticket_count: null as number | null,
    free_ticket_count: null as number | null,
    remark: ''
  }

  /**
   * 表单数据
   */
  const formData = reactive({ ...initialFormData })

  /**
   * 监听弹窗打开，初始化表单并拉取玩家选项
   */
  watch(
    () => props.modelValue,
    async (open) => {
      if (open) {
        initPage()
        try {
          const list = await api.getPlayerOptions(getChannelDeptRequestParams())
          const arr = Array.isArray(list) ? list : (list as any)?.data
          playerOptions.value = Array.isArray(arr)
            ? (arr as Array<{ id: number; username: string }>)
            : []
        } catch {
          playerOptions.value = []
        }
      }
    }
  )

  /**
   * 初始化页面数据
   */
  const initPage = async () => {
    Object.assign(formData, { ...initialFormData })
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  /**
   * 回填表单数据
   */
  const initForm = () => {
    if (!props.data) return
    const keys = [
      'id',
      'player_id',
      'use_coins',
      'total_ticket_count',
      'paid_ticket_count',
      'free_ticket_count',
      'remark'
    ]
    keys.forEach((key) => {
      const val = props.data![key]
      if (val != null && val !== undefined) {
        ;(formData as Record<string, unknown>)[key] = val
      }
    })
  }

  /**
   * 关闭弹窗
   */
  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }
</script>
