<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="merchantId">
        <el-input v-model="formData.merchantId" placeholder="请输入商户编号" />
      </el-form-item>
      <el-form-item label="渠道编号" prop="channelId">
        <el-input v-model="formData.channelId" placeholder="请输入渠道编号" />
      </el-form-item>
      <el-form-item label="渠道编码" prop="channelCode">
        <el-input v-model="formData.channelCode" placeholder="请输入渠道编码" />
      </el-form-item>
      <el-form-item label="商户订单编号" prop="merchantOrderId">
        <el-input v-model="formData.merchantOrderId" placeholder="请输入商户订单编号" />
      </el-form-item>
      <el-form-item label="商品标题" prop="subject">
        <el-input v-model="formData.subject" placeholder="请输入商品标题" />
      </el-form-item>
      <el-form-item label="商品描述" prop="body">
        <el-input v-model="formData.body" placeholder="请输入商品描述" />
      </el-form-item>
      <el-form-item label="异步通知地址" prop="notifyUrl">
        <el-input v-model="formData.notifyUrl" placeholder="请输入异步通知地址" />
      </el-form-item>
      <el-form-item label="支付金额，单位：分" prop="amount">
        <el-input v-model="formData.amount" placeholder="请输入支付金额，单位：分" />
      </el-form-item>
      <el-form-item label="渠道手续费，单位：百分比" prop="channelFeeRate">
        <el-input v-model="formData.channelFeeRate" placeholder="请输入渠道手续费，单位：百分比" />
      </el-form-item>
      <el-form-item label="渠道手续金额，单位：分" prop="channelFeeAmount">
        <el-input v-model="formData.channelFeeAmount" placeholder="请输入渠道手续金额，单位：分" />
      </el-form-item>
      <el-form-item label="支付状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择支付状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PAY_ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户 IP" prop="userIp">
        <el-input v-model="formData.userIp" placeholder="请输入用户 IP" />
      </el-form-item>
      <el-form-item label="订单失效时间" prop="expireTime">
        <el-date-picker
          v-model="formData.expireTime"
          type="date"
          value-format="x"
          placeholder="选择订单失效时间"
        />
      </el-form-item>
      <el-form-item label="订单支付成功时间" prop="successTime">
        <el-date-picker
          v-model="formData.successTime"
          type="date"
          value-format="x"
          placeholder="选择订单支付成功时间"
        />
      </el-form-item>
      <el-form-item label="订单支付通知时间" prop="notifyTime">
        <el-date-picker
          v-model="formData.notifyTime"
          type="date"
          value-format="x"
          placeholder="选择订单支付通知时间"
        />
      </el-form-item>
      <el-form-item label="支付成功的订单拓展单编号" prop="successExtensionId">
        <el-input
          v-model="formData.successExtensionId"
          placeholder="请输入支付成功的订单拓展单编号"
        />
      </el-form-item>
      <el-form-item label="退款次数" prop="refundTimes">
        <el-input v-model="formData.refundTimes" placeholder="请输入退款次数" />
      </el-form-item>
      <el-form-item label="退款总金额，单位：分" prop="refundAmount">
        <el-input v-model="formData.refundAmount" placeholder="请输入退款总金额，单位：分" />
      </el-form-item>
      <el-form-item label="渠道用户编号" prop="channelUserId">
        <el-input v-model="formData.channelUserId" placeholder="请输入渠道用户编号" />
      </el-form-item>
      <el-form-item label="渠道订单号" prop="channelOrderNo">
        <el-input v-model="formData.channelOrderNo" 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 { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as PayOrderApi from '@/api/member/payOrder'
import { reactive, ref } from 'vue'

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,
  merchantId: undefined,
  channelId: undefined,
  channelCode: undefined,
  merchantOrderId: undefined,
  subject: undefined,
  body: undefined,
  notifyUrl: undefined,
  notifyStatus: undefined,
  amount: undefined,
  channelFeeRate: undefined,
  channelFeeAmount: undefined,
  status: undefined,
  userIp: undefined,
  expireTime: undefined,
  successTime: undefined,
  notifyTime: undefined,
  successExtensionId: undefined,
  refundStatus: undefined,
  refundTimes: undefined,
  refundAmount: undefined,
  channelUserId: undefined,
  channelOrderNo: undefined
})
const formRules = reactive({
  amount: [{ required: true, message: '支付金额，单位：分不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '支付状态不能为空', trigger: 'change' }],
  userIp: [{ required: true, message: '用户 IP不能为空', trigger: 'blur' }],
  expireTime: [{ required: true, message: '订单失效时间不能为空', trigger: 'blur' }],
  refundStatus: [{ required: true, message: '退款状态不能为空', trigger: 'blur' }],
  refundTimes: [{ required: true, message: '退款次数不能为空', trigger: 'blur' }],
  refundAmount: [{ required: true, message: '退款总金额，单位：分不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 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 {
      formData.value = await PayOrderApi.getPayOrder(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    merchantId: undefined,
    channelId: undefined,
    channelCode: undefined,
    merchantOrderId: undefined,
    subject: undefined,
    body: undefined,
    notifyUrl: undefined,
    notifyStatus: undefined,
    amount: undefined,
    channelFeeRate: undefined,
    channelFeeAmount: undefined,
    status: undefined,
    userIp: undefined,
    expireTime: undefined,
    successTime: undefined,
    notifyTime: undefined,
    successExtensionId: undefined,
    refundStatus: undefined,
    refundTimes: undefined,
    refundAmount: undefined,
    channelUserId: undefined,
    channelOrderNo: undefined
  }
  formRef.value?.resetFields()
}
</script>
