<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="键盘皮肤名称" prop="themeName">
        <el-input v-model="formData.themeName" placeholder="请输入键盘皮肤名称" />
      </el-form-item>
      <el-form-item label="键盘价格" prop="themePrice">
        <el-input v-model="formData.themePrice" placeholder="请输入键盘价格" />
      </el-form-item>
      <el-form-item label="主题标签" prop="themeTag">
        <div class="w-full">
          <div class="flex flex-wrap">
            <el-tag v-for="(tag, index) in formData.themeTag" :key="index" class="mr-5px mb-5px" closable
              :style="getTagStyle(tag)" @close="removeTag(index)">
              {{ getTagText(tag) }}
            </el-tag>
            <span v-if="!formData.themeTag?.length" class="text-gray-400">暂无标签</span>
          </div>
          <div class="mt-8px flex items-center gap-8px">
            <el-input v-model="newTagText" placeholder="标签文字" class="!w-200px" @keyup.enter="addTag" />
            <el-color-picker v-model="newTagColor" />
            <el-button type="primary" plain @click="addTag">添加标签</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="主题下载次数" prop="themeDownload">
        <el-input v-model="formData.themeDownload" placeholder="请输入主题下载次数" />
      </el-form-item>
      <el-form-item label="主题风格" prop="themeStyle">
        <el-select v-model="formData.themeStyle" placeholder="请选择主题风格" clearable class="!w-240px">
          <el-option v-for="item in themeStyleOptions" :key="item.id" :label="item.styleName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属国家" prop="local">
        <el-input v-model="formData.local" placeholder="请输入所属国家" />
      </el-form-item>
      <el-form-item label="上架状态" prop="themeStatus">
        <el-radio-group v-model="formData.themeStatus">
          <el-radio v-for="item in themeStatusOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="主题购买次数" prop="themePurchasesNumber">
        <el-input v-model="formData.themePurchasesNumber" placeholder="请输入主题购买次数" />
      </el-form-item>
      <!-- <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker v-model="formData.createdAt" type="date" value-format="x" placeholder="选择创建时间" />
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker v-model="formData.updatedAt" type="date" value-format="x" placeholder="选择更新时间" />
      </el-form-item> -->
      <el-form-item label="预览图" prop="themePreviewImageUrl">
        <UploadImg v-model="formData.themePreviewImageUrl" directory="theme_preview" />
      </el-form-item>
      <el-form-item label="是否免费" prop="isFree">
        <el-radio-group v-model="formData.isFree">
          <el-radio v-for="item in freeOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="下载地址" prop="themeDownloadUrl">
        <UploadFile v-model="formData.themeDownloadUrl" :file-type="['zip']" :limit="1" :is-show-tip="false"
          directory="theme" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="真实下载数量" prop="realDownloadCount">
        <el-input v-model="formData.realDownloadCount" placeholder="请输入真实下载数量" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ThemesApi, Themes } from '@/api/keyboard/themes'
import { KeyboardThemeStylesApi, KeyboardThemeStyles } from '@/api/keyboard-server/themestyles'
import { UploadFile, UploadImg } from '@/components/UploadFile'

/** 键盘皮肤 表单 */
defineOptions({ name: 'ThemesForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  themeName: undefined,
  themePrice: undefined,
  themeTag: [],
  themeDownload: undefined,
  themeStyle: undefined,
  local: undefined,
  themeStatus: undefined,
  themePurchasesNumber: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  themePreviewImageUrl: undefined,
  isFree: undefined,
  themeDownloadUrl: undefined,
  sort: undefined,
  realDownloadCount: undefined
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref
const themeStatusOptions = [
  { label: '已上架', value: true },
  { label: '未上架', value: false }
]
const themeStyleOptions = ref<KeyboardThemeStyles[]>([])
const freeOptions = [
  { label: '免费', value: true },
  { label: '付费', value: false }
]
const newTagText = ref('')
const newTagColor = ref('#409EFF')

const getTagText = (tag: Record<string, any>) => {
  return tag?.label ?? tag?.text ?? tag?.name ?? ''
}

const getTagStyle = (tag: Record<string, any>) => {
  if (!tag?.color) return {}
  return {
    backgroundColor: tag.color,
    borderColor: tag.color,
    color: '#ffffff'
  }
}

const normalizeThemeTags = (raw: unknown) => {
  if (!raw) return []
  if (Array.isArray(raw)) return raw
  if (typeof raw === 'string') {
    try {
      const parsed = JSON.parse(raw)
      if (Array.isArray(parsed)) return parsed
      if (parsed && typeof parsed === 'object') return [parsed]
    } catch {
      return raw ? [{ text: raw, color: newTagColor.value }] : []
    }
  }
  if (typeof raw === 'object') return [raw]
  return []
}

const addTag = () => {
  const text = newTagText.value.trim()
  if (!text) return
  const next = {
    color: newTagColor.value,
    label: text
  }
  formData.value.themeTag = [...formData.value.themeTag, next]
  newTagText.value = ''
}

const removeTag = (index: number) => {
  formData.value.themeTag = formData.value.themeTag.filter((_, idx) => idx !== index)
}

const fetchThemeStyles = async () => {
  const data = await KeyboardThemeStylesApi.getKeyboardThemeStylesPage({ pageNo: 1, pageSize: 100 })
  themeStyleOptions.value = data.list ?? []
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await ThemesApi.getThemes(id)
      formData.value = {
        ...data,
        themeTag: normalizeThemeTags(data?.themeTag)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Themes
    if (formType.value === 'create') {
      await ThemesApi.createThemes(data)
      message.success(t('common.createSuccess'))
    } else {
      await ThemesApi.updateThemes(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    themeName: undefined,
    themePrice: undefined,
    themeTag: [],
    themeDownload: undefined,
    themeStyle: undefined,
    themeStatus: undefined,
    themePurchasesNumber: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    themePreviewImageUrl: undefined,
    isFree: undefined,
    themeDownloadUrl: undefined,
    sort: undefined,
    realDownloadCount: undefined
  }
  formRef.value?.resetFields()
}

onMounted(() => {
  fetchThemeStyles()
})
</script>
