<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="用户ID" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入用户ID" />
      </el-form-item>
      <el-form-item label="产品ID" prop="productId">
        <el-input v-model="formData.productId" placeholder="请输入产品ID" />
      </el-form-item>
      <el-form-item label="购买数量" prop="purchaseQuantity">
        <el-input v-model="formData.purchaseQuantity" placeholder="请输入购买数量" />
      </el-form-item>
      <el-form-item label="实际价格" prop="price">
        <el-input v-model="formData.price" placeholder="请输入实际价格" />
      </el-form-item>
      <el-form-item label="货币类型" prop="currency">
        <el-input v-model="formData.currency" placeholder="请输入货币类型" />
      </el-form-item>
      <el-form-item label="购买时间" prop="purchaseTime">
        <el-date-picker
          v-model="formData.purchaseTime"
          type="date"
          value-format="x"
          placeholder="选择购买时间"
        />
      </el-form-item>
      <el-form-item label="购买类型" prop="purchaseType">
        <el-select v-model="formData.purchaseType" placeholder="请选择购买类型">
          <el-option v-for="item in purchaseTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="购买状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="item in statusOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-input v-model="formData.paymentMethod" placeholder="请输入支付方式" />
      </el-form-item>
      <el-form-item label="交易ID" prop="transactionId">
        <el-input v-model="formData.transactionId" placeholder="请输入交易ID" />
      </el-form-item>
      <el-form-item label="原始交易ID" prop="originalTransactionId">
        <el-input v-model="formData.originalTransactionId" placeholder="请输入原始交易ID" />
      </el-form-item>
      <el-form-item label="产品ID列表" prop="productIds">
        <el-input v-model="formData.productIds" type="textarea" :rows="3" placeholder="请输入产品ID列表" />
      </el-form-item>
      <el-form-item label="苹果购买时间" prop="purchaseDate">
        <el-date-picker
          v-model="formData.purchaseDate"
          type="date"
          value-format="x"
          placeholder="选择苹果购买时间"
        />
      </el-form-item>
      <el-form-item label="苹果过期时间" prop="expiresDate">
        <el-date-picker
          v-model="formData.expiresDate"
          type="date"
          value-format="x"
          placeholder="选择苹果过期时间"
        />
      </el-form-item>
      <el-form-item label="苹果环境" prop="environment">
        <el-input v-model="formData.environment" 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 { UserPurchaseRecordsApi, UserPurchaseRecords } from '@/api/keyboard/userpurchaserecords'

/** 用户内购记录 表单 */
defineOptions({ name: 'UserPurchaseRecordsForm' })

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,
  userId: undefined,
  productId: undefined,
  purchaseQuantity: undefined,
  price: undefined,
  currency: undefined,
  purchaseTime: undefined,
  purchaseType: undefined,
  status: undefined,
  paymentMethod: undefined,
  transactionId: undefined,
  originalTransactionId: undefined,
  productIds: undefined,
  purchaseDate: undefined,
  expiresDate: undefined,
  environment: undefined
})
const formRules = reactive({
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品ID不能为空', trigger: 'blur' }],
  purchaseQuantity: [{ required: true, message: '购买数量不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '实际价格不能为空', trigger: 'blur' }],
  currency: [{ required: true, message: '货币类型不能为空', trigger: 'blur' }],
  purchaseType: [{ required: true, message: '购买类型不能为空', trigger: 'change' }],
  status: [{ required: true, message: '购买状态不能为空', trigger: 'change' }],
  transactionId: [{ required: true, message: '交易ID不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const purchaseTypeOptions = [
  { label: '内购', value: '内购' },
  { label: '订阅', value: '订阅' }
]
const statusOptions = [
  { label: '已支付', value: '已支付' },
  { label: '待支付', value: '待支付' },
  { label: '退款', value: '退款' }
]

/** 打开弹窗 */
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 {
      formData.value = await UserPurchaseRecordsApi.getUserPurchaseRecords(id)
    } 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 UserPurchaseRecords
    if (formType.value === 'create') {
      await UserPurchaseRecordsApi.createUserPurchaseRecords(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserPurchaseRecordsApi.updateUserPurchaseRecords(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    productId: undefined,
    purchaseQuantity: undefined,
    price: undefined,
    currency: undefined,
    purchaseTime: undefined,
    purchaseType: undefined,
    status: undefined,
    paymentMethod: undefined,
    transactionId: undefined,
    originalTransactionId: undefined,
    productIds: undefined,
    purchaseDate: undefined,
    expiresDate: undefined,
    environment: undefined
  }
  formRef.value?.resetFields()
}
</script>
