<template>
  <Dialog title="发起订单" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      v-loading="formLoading"
    >
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="formData.userType" placeholder="请选择用户类型" @change="handleSelectUserType">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MENDUNER_USER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="showEnterpriseId" label="企业编号" prop="enterpriseId">
        <el-input v-model="formData.enterpriseId" placeholder="请输入企业编号" />
      </el-form-item>
      <el-form-item label="用户编号" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入用户编号" />
      </el-form-item>
      <el-form-item label="订单类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择订单类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MENDUNER_TRADE_ORDER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品编号" prop="spuId">
        <el-input v-model="formData.spuId" placeholder="请输入商品编号" />
      </el-form-item>
      <el-form-item label="商品名字" prop="spuName">
        <el-input v-model="formData.spuName" placeholder="请输入商品名字" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number v-model="formData.price" :precision="0" :step="1" :min="1" />
      </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 { TradeOrderApi, TradeOrderVO } from '@/api/menduner/system/order'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'

/** 交易订单	 表单 */
defineOptions({ name: 'TradeOrderForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  userId: undefined,
  type: undefined,
  spuId: undefined,
  spuName: undefined,
  userType: undefined,
  enterpriseId: undefined,
  price: 100,
})
const formRules = reactive({
  userType: [{ required: true, message: '用户类型不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '用户编号不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '订单类型不能为空', trigger: 'change' }],
  spuId: [{ required: true, message: '商品编号不能为空', trigger: 'blur' }],
  spuName: [{ required: true, message: '商品名字不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string) => {
  dialogVisible.value = true
  formType.value = type
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const showEnterpriseId = ref(true)
const handleSelectUserType = (e: string) => {
  showEnterpriseId.value = e === '0' ? false : true
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  if (formData.value.userType === '1' && !formData.value.enterpriseId) return message.warning('企业编号不能为空')

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TradeOrderVO
    data.price = data.price * 100
    await TradeOrderApi.createTradeOrder(data)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    userId: undefined,
    type: undefined,
    spuId: undefined,
    spuName: undefined,
    userType: undefined,
    enterpriseId: undefined,
    price: 100
  }
  formRef.value?.resetFields()
}
</script>