<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? $t('page.form.dialogTitleAdd') : $t('page.form.dialogTitleEdit')"
    width="680px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item :label="$t('page.form.provider')" prop="provider">
            <el-input v-model="formData.provider" :placeholder="$t('page.form.placeholderProvider')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('page.form.providerCode')" prop="provider_code">
            <el-input v-model="formData.provider_code" :placeholder="$t('page.form.placeholderProviderCode')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item :label="$t('page.form.gameCode')" prop="game_code">
            <el-input v-model="formData.game_code" :placeholder="$t('page.form.placeholderGameCode')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('page.form.gameKey')" prop="game_key">
            <el-input v-model="formData.game_key" :placeholder="$t('page.form.placeholderGameKey')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item :label="$t('page.form.gameName')" prop="game_name">
            <el-input v-model="formData.game_name" :placeholder="$t('page.form.placeholderGameName')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('page.form.gameNameEn')" prop="game_name_en">
            <el-input v-model="formData.game_name_en" :placeholder="$t('page.form.placeholderGameNameEn')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item :label="$t('page.form.gameType')" prop="game_type">
            <el-input v-model="formData.game_type" :placeholder="$t('page.form.placeholderGameType')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('page.form.sort')" prop="sort">
            <el-input-number v-model="formData.sort" :min="1" :step="1" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="$t('page.form.logo')" prop="logo">
        <el-tabs v-model="logoInputMode" class="w-full">
          <el-tab-pane :label="$t('page.form.tabPicker')" name="picker">
            <sa-image-picker
              v-model="formData.logo"
              :multiple="false"
              :limit="1"
              width="120px"
              height="120px"
            />
          </el-tab-pane>
          <el-tab-pane :label="$t('page.form.tabUpload')" name="upload">
            <sa-image-upload
              v-model="formData.logo"
              :multiple="false"
              :limit="1"
              :max-size="5"
              :show-tips="true"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item :label="$t('page.form.gameUrl')" prop="game_url">
        <el-input v-model="formData.game_url" :placeholder="$t('page.form.placeholderGameUrl')" />
      </el-form-item>
      <el-form-item :label="$t('page.form.hallUrl')" prop="hall_url">
        <el-input v-model="formData.hall_url" :placeholder="$t('page.form.placeholderHallUrl')" />
      </el-form-item>
      <el-form-item :label="$t('page.form.status')" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">{{ $t('page.form.statusEnabled') }}</el-radio>
          <el-radio :value="0">{{ $t('page.form.statusDisabled') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('page.form.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          :placeholder="$t('page.form.placeholderRemark')"
        />
      </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/game/index'
  import { useI18n } from 'vue-i18n'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { withChannelDeptParams } from '@/composables/useChannelDeptScope'

  const { t } = useI18n()

  interface Props {
    modelValue: boolean
    dialogType: string
    data?: Record<string, unknown>
  }
  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 visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
  })

  const formRef = ref<FormInstance>()
  const logoInputMode = ref('picker')

  const initialFormData = {
    id: undefined as number | undefined,
    provider: '',
    provider_code: '',
    game_code: '',
    game_key: '',
    game_name: '',
    game_name_en: '',
    game_type: '',
    logo: '',
    game_url: '',
    hall_url: '',
    status: 1,
    sort: 100,
    remark: ''
  }

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

  const rules = computed<FormRules>(() => ({
    provider: [{ required: true, message: t('page.form.ruleProviderRequired'), trigger: 'blur' }],
    provider_code: [{ required: true, message: t('page.form.ruleProviderCodeRequired'), trigger: 'blur' }],
    game_code: [{ required: true, message: t('page.form.ruleGameCodeRequired'), trigger: 'blur' }],
    game_key: [{ required: true, message: t('page.form.ruleGameKeyRequired'), trigger: 'blur' }],
    game_name: [{ required: true, message: t('page.form.ruleGameNameRequired'), trigger: 'blur' }],
    game_type: [{ required: true, message: t('page.form.ruleGameTypeRequired'), trigger: 'blur' }]
  }))

  watch(
    () => props.modelValue,
    async (newVal) => {
      if (!newVal) return
      Object.assign(formData, initialFormData)
      if (!props.data) return
      await nextTick()
      if (typeof props.data.id === 'number') formData.id = props.data.id
      if (typeof props.data.provider === 'string') formData.provider = props.data.provider
      if (typeof props.data.provider_code === 'string') formData.provider_code = props.data.provider_code
      if (typeof props.data.game_code === 'string') formData.game_code = props.data.game_code
      if (typeof props.data.game_key === 'string') formData.game_key = props.data.game_key
      if (typeof props.data.game_name === 'string') formData.game_name = props.data.game_name
      if (typeof props.data.game_name_en === 'string') formData.game_name_en = props.data.game_name_en
      if (typeof props.data.game_type === 'string') formData.game_type = props.data.game_type
      if (typeof props.data.logo === 'string') formData.logo = props.data.logo
      if (typeof props.data.game_url === 'string') formData.game_url = props.data.game_url
      if (typeof props.data.hall_url === 'string') formData.hall_url = props.data.hall_url
      formData.status = Number(props.data.status ?? 1) === 1 ? 1 : 0
      const sortValue = Number(props.data.sort ?? 100)
      formData.sort = Number.isFinite(sortValue) ? sortValue : 100
      if (typeof props.data.remark === 'string') formData.remark = props.data.remark
    }
  )

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

  async function handleSubmit() {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      if (props.dialogType === 'add') {
        await api.save(withChannelDeptParams(formData))
        ElMessage.success(t('page.form.addSuccess'))
      } else {
        await api.update(withChannelDeptParams(formData))
        ElMessage.success(t('page.form.editSuccess'))
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log(error)
    }
  }
</script>
