<template>
  <div class="p-2">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="35%" :draggable="draggable">
      <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="卡类" prop="cardType">
          <el-select v-model="formData.cardType" placeholder="请选择卡类" clearable style="width: 100%">
            <el-option v-for="item in cardTypeOptions" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="餐类" prop="mealType">
          <el-select v-model="formData.mealType" placeholder="请选择餐类" clearable style="width: 100%">
            <el-option v-for="item in mealTypeOptions" :key="item.mealId" :label="item.mealName" :value="item.mealId" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-checkbox v-model="formData.status" true-value="1" false-value="0" label="启用折扣消费" border />
        </el-form-item>
        <el-form-item label="按日折扣" prop="rateType">
          <el-checkbox v-model="formData.rateType" true-value="1" false-value="0" label="启用" border />
        </el-form-item>
        <el-form-item label="折扣率1" prop="oneRate">
          <el-input v-model="formData.oneRate" type="number" placeholder="请输入折扣率1" style="width: 40%">
            <template #suffix>
              <span>%</span>
            </template>
          </el-input>
          <span class="text-red-400"> （各种费率如填入0则表示不限制）</span>
        </el-form-item>
        <el-form-item label="折扣率2" prop="twoRate">
          <el-input v-model="formData.twoRate" type="number" placeholder="请输入折扣率2" style="width: 40%" >
            <template #suffix>
              <span>%</span>
            </template>
          </el-input>
          <span class="text-red-400">（各种费率如填入0则表示不限制）</span>
        </el-form-item>
        <el-form-item label="折扣率3" prop="threeRate">
          <el-input v-model="formData.threeRate" ttype="number" placeholder="请输入折扣率3" style="width: 40%" >
            <template #suffix>
              <span>%</span>
            </template>
          </el-input>
          <span class="text-red-400">（各种费率如填入0则表示不限制）</span>
        </el-form-item>
        <el-form-item label="折扣率4" prop="fourRate">
          <el-input v-model="formData.fourRate" type="number" placeholder="请输入折扣率4" style="width: 40%" >
            <template #suffix>
              <span>%</span>
            </template>
          </el-input>
          <span class="text-red-400">（各种费率如填入0则表示不限制）</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="formLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="XfDiscountForm" lang="ts">
import * as XfDiscountApi from '@/api/consumption/xfDiscount';
import { listUsePtCardType } from '@/api/basics/basicParameter/ptCardtype';
import { getAllPtMealType } from '@/api/basics/basicParameter/ptMealtype';
import { XfDiscountForm } from '@/api/consumption/xfDiscount/types';
import { useI18n } from 'vue-i18n';
import { PtMealTypeVO } from '@/api/basics/basicParameter/ptMealtype/types';
import { PtCardTypeVO } from '@/api/basics/basicParameter/ptCardtype/types';

defineOptions({ name: 'XfDiscountForm' });

// 接收父组件传入属性
// const props = defineProps({})

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 国际化
const { t } = useI18n();

// 对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 窗体是否可以拖动
const draggable = ref(true);
// 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formLoading = ref(false);
// 表单的类型：create - 新增；update - 修改
const formType = ref('');
// 表单引用
const formRef = ref<ElFormInstance>();
// 表单数据
const formData = ref<XfDiscountForm>({
  discountId: undefined,
  cardType: undefined,
  mealType: undefined,
  rateType: '0',
  oneRate: undefined,
  twoRate: undefined,
  threeRate: undefined,
  fourRate: undefined,
  remark: '',
  status: '1'
});
// 表单校验规则
const formRules = reactive({
  /* discountId: [{ required: true, message: '折扣Id,主键不能为空', trigger: 'blur' }], */
  cardType: [{ required: true, message: '卡类Id不能为空', trigger: 'change' }],
  mealType: [{ required: true, message: '餐类Id不能为空', trigger: 'change' }],
  status: [{ required: true, message: '启用状态不能为空', trigger: 'change' }]
});
/** 当前组件方法 */
/** 窗体打开事件 */
const open = async (type: string, id?: number) => {
  dialog.visible = true;
  dialog.title = t('action.' + type);
  formType.value = type;
  resetForm();
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      const res = await XfDiscountApi.getXfDiscount(id);
      Object.assign(formData.value, res.data);
    } finally {
      formLoading.value = false;
    }
  }
};
/** 表单重置 */
const resetForm = () => {
  formData.value = {
    discountId: undefined,
    cardType: undefined,
    mealType: undefined,
    rateType: '0',
    oneRate: undefined,
    twoRate: undefined,
    threeRate: undefined,
    fourRate: undefined,
    remark: '',
    status: '1'
  };
  formRef.value?.resetFields();
};
// 传回给父组件的属性与方法
// 提供 open 方法，用于打开弹窗
defineExpose({ open });
/** 触发父组件的事件 */
/** 定义 success 事件，用于操作成功后的回调 */
const emit = defineEmits(['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 XfDiscountForm;
    if (formType.value === 'create') {
      await XfDiscountApi.addXfDiscount(data);
      proxy?.$modal.msgSuccess('新增成功');
    } else {
      await XfDiscountApi.updateXfDiscount(data);
      proxy?.$modal.msgSuccess('修改成功');
    }
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

// const cardTypeOptions = await listUsePtCardType();
// const mealTypeOptions = await getAllPtMealtype();

const cardTypeOptions = ref<PtCardTypeVO[]>([]);
const mealTypeOptions = ref<PtMealTypeVO[]>([]);
/** 初始化 */
onMounted(() => {
  listUsePtCardType().then((res) => {
    cardTypeOptions.value = res.data;
  });
  getAllPtMealType().then((res) => {
    mealTypeOptions.value = res.data;
  });
});
</script>
