<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="760px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-divider content-position="left">基础信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="应用标识" prop="appId">
            <el-input v-model="formData.appId" placeholder="如：main" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="平台" prop="platform">
            <el-select v-model="formData.platform" placeholder="请选择平台">
              <el-option label="Android" value="android" />
              <el-option label="iOS" value="ios" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="渠道" prop="channel">
            <el-input v-model="formData.channel" placeholder="如：official" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="构建号" prop="buildNumber">
            <el-input v-model="formData.buildNumber" placeholder="iOS 可选" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">版本策略</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="展示版本" prop="versionName">
            <el-input v-model="formData.versionName" placeholder="如：1.2.3" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本码" prop="versionCode">
            <el-input-number v-model="formData.versionCode" :min="1" controls-position="right" class="!w-full" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最低版本码" prop="minSupportedCode">
            <el-input-number v-model="formData.minSupportedCode" :min="1" controls-position="right" class="!w-full" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发布时间" prop="releasedAt">
            <el-date-picker
              v-model="formData.releasedAt"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择发布时间"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="强制更新" prop="isForceUpdate">
            <el-radio-group v-model="formData.isForceUpdate">
              <el-radio :value="true">是</el-radio>
              <el-radio :value="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否生效" prop="isActive">
            <el-radio-group v-model="formData.isActive">
              <el-radio :value="true">生效</el-radio>
              <el-radio :value="false">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">更新内容</el-divider>
      <el-form-item label="更新说明" prop="releaseNotes">
        <el-input
          v-model="formData.releaseNotes"
          type="textarea"
          :rows="3"
          placeholder="展示给用户的更新内容"
        />
      </el-form-item>
      <el-form-item label="下载地址" prop="downloadUrl">
        <el-input v-model="formData.downloadUrl" placeholder="APK 直链 / App Store 链接" />
      </el-form-item>
      <el-form-item label="商店链接" prop="storeUrl">
        <el-input v-model="formData.storeUrl" placeholder="可选" />
      </el-form-item>
      <el-form-item label="扩展元数据" prop="metadataText">
        <el-input
          v-model="formData.metadataText"
          type="textarea"
          :rows="4"
          placeholder='JSON 格式，例如：{"size":"20MB","md5":"xxx"}'
        />
      </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 { AppVersionsApi, AppVersions } from '@/api/keyboard/appversions'

defineOptions({ name: 'AppVersionsForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  appId: undefined,
  platform: undefined,
  channel: undefined,
  versionName: undefined,
  versionCode: 1,
  buildNumber: undefined,
  minSupportedCode: 1,
  isForceUpdate: false,
  isActive: true,
  releaseNotes: undefined,
  downloadUrl: undefined,
  storeUrl: undefined,
  metadataText: undefined,
  releasedAt: undefined
})

const formRules = reactive({
  appId: [{ required: true, message: '应用标识不能为空', trigger: 'blur' }],
  platform: [{ required: true, message: '请选择平台', trigger: 'change' }],
  channel: [{ required: true, message: '渠道不能为空', trigger: 'blur' }],
  versionName: [{ required: true, message: '展示版本不能为空', trigger: 'blur' }],
  versionCode: [{ required: true, message: '版本码不能为空', trigger: 'change' }],
  minSupportedCode: [{ required: true, message: '最低版本码不能为空', trigger: 'change' }],
  isForceUpdate: [{ required: true, message: '请选择是否强制更新', trigger: 'change' }],
  isActive: [{ required: true, message: '请选择是否生效', trigger: 'change' }],
  releaseNotes: [{ required: true, message: '更新说明不能为空', trigger: 'blur' }],
  downloadUrl: [{ required: true, message: '下载地址不能为空', trigger: 'blur' }]
})
const formRef = ref()

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 AppVersionsApi.getAppVersions(id)
      formData.value = {
        ...data,
        versionCode: data.versionCode || 1,
        minSupportedCode: data.minSupportedCode || 1,
        isForceUpdate: !!data.isForceUpdate,
        isActive: !!data.isActive,
        metadataText: data.metadata ? JSON.stringify(data.metadata, null, 2) : undefined
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()

  let metadata: Record<string, any> | undefined
  if (formData.value.metadataText) {
    try {
      metadata = JSON.parse(formData.value.metadataText)
    } catch {
      message.warning('扩展元数据不是有效 JSON，请检查格式')
      return
    }
  }

  formLoading.value = true
  try {
    const { metadataText, ...rest } = formData.value
    const data = { ...rest, metadata } as unknown as AppVersions
    if (formType.value === 'create') {
      await AppVersionsApi.createAppVersions(data)
      message.success(t('common.createSuccess'))
    } else {
      await AppVersionsApi.updateAppVersions(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    appId: undefined,
    platform: undefined,
    channel: undefined,
    versionName: undefined,
    versionCode: 1,
    buildNumber: undefined,
    minSupportedCode: 1,
    isForceUpdate: false,
    isActive: true,
    releaseNotes: undefined,
    downloadUrl: undefined,
    storeUrl: undefined,
    metadataText: undefined,
    releasedAt: undefined
  }
  formRef.value?.resetFields()
}
</script>
