<template>
  <div class="p-2">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" :draggable="draggable">
      <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="所属账户Id" prop="userId">
          <el-input v-model="formData.userId" placeholder="请输入所属账户Id" />
        </el-form-item>
        <el-form-item label="卡流水号" prop="cardNo">
          <el-input v-model="formData.cardNo" placeholder="请输入卡流水号" />
        </el-form-item>
        <el-form-item label="卡片有效期" prop="lifespan">
          <el-date-picker v-model="formData.lifespan" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择卡片有效期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="物理卡号" prop="factoryId">
          <el-input v-model="formData.factoryId" placeholder="请输入物理卡号" />
        </el-form-item>
        <el-form-item label="是否主卡,见sys_yes_no字典类别" prop="mainCard">
          <el-select v-model="formData.mainCard" placeholder="请选择是否主卡,见sys_yes_no字典类别">
            <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡片状态，见KZT字典类别" prop="status">
          <el-select v-model="formData.status" placeholder="请选择卡片状态，见KZT字典类别">
            <el-option
                v-for="dict in KZT"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡状态变更时间" prop="changeTime">
          <el-date-picker v-model="formData.changeTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择卡状态变更时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="当日消费金额" prop="dayTotal">
          <el-input v-model="formData.dayTotal" placeholder="请输入当日消费金额" />
        </el-form-item>
        <el-form-item label="当日消费次数" prop="dayCount">
          <el-input v-model="formData.dayCount" placeholder="请输入当日消费次数" />
        </el-form-item>
        <el-form-item label="当餐交易金额" prop="mealTotal">
          <el-input v-model="formData.mealTotal" placeholder="请输入当餐交易金额" />
        </el-form-item>
        <el-form-item label="当餐消费次数" prop="mealCount">
          <el-input v-model="formData.mealCount" placeholder="请输入当餐消费次数" />
        </el-form-item>
        <el-form-item label="最后交易时间" prop="lastPay">
          <el-date-picker v-model="formData.lastPay" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择最后交易时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="最后交易餐类，对应营业时段的编号" prop="lastMeal">
          <el-input v-model="formData.lastMeal" 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="PtCardForm" lang="ts">
import * as PtCardApi from '@/api/cardCenter/cardOperation/ptCard';
import { PtCardForm } from '@/api/cardCenter/cardOperation/ptCard/types';
import { useI18n } from 'vue-i18n';

defineOptions({ name: 'PtCardForm' });

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

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

/** 数据字典 */
const { KZT, sys_yes_no } = toRefs<any>(proxy?.useDict('KZT', 'sys_yes_no'));
// 对话框
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<PtCardForm>({
  cardId: undefined,
  userId: undefined,
  cardNo: undefined,
  cardType: undefined,
  lifespan: undefined,
  factoryId: undefined,
  mainCard: '',
  status: '',
  changeTime: undefined,
  dayTotal: undefined,
  dayCount: undefined,
  mealTotal: undefined,
  mealCount: undefined,
  lastPay: undefined,
  lastMeal: undefined,
});
// 表单校验规则
const formRules = reactive({
  cardId: [{ required: true, message: '卡片Id,主键不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '所属账户Id不能为空', trigger: 'blur' }],
  cardNo: [{ required: true, message: '卡流水号不能为空', trigger: 'blur' }],
  cardType: [{ required: true, message: '卡片类型不能为空', trigger: 'change' }],
  lifespan: [{ required: true, message: '卡片有效期不能为空', trigger: 'blur' }],
  factoryId: [{ required: true, message: '物理卡号不能为空', trigger: 'blur' }],
  mainCard: [{ required: true, message: '是否主卡,见sys_yes_no字典类别不能为空', trigger: 'change' }],
  status: [{ required: true, message: '卡片状态，见KZT字典类别不能为空', 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 PtCardApi.getPtCard(id);
      Object.assign(formData.value, res.data);
    } finally {
      formLoading.value = false;
    }
  }
};
/** 表单重置 */
const resetForm = () => {
  formData.value = {
    cardId: undefined,
    userId: undefined,
    cardNo: undefined,
    cardType: undefined,
    lifespan: undefined,
    factoryId: undefined,
    mainCard: '',
    status: '',
    changeTime: undefined,
    dayTotal: undefined,
    dayCount: undefined,
    mealTotal: undefined,
    mealCount: undefined,
    lastPay: undefined,
    lastMeal: undefined,
  };
  formRef.value?.resetFields();
};
// 传回给父组件的属性与方法
// 提供 open 方法，用于打开弹窗
defineExpose({ open });
/** 触发父组件的事件 */
/** 定义 success 事件，用于操作成功后的回调 */
const emit = defineEmits(['success']);
/** 提交按钮 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return;
  const valid = await formRef.value?.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as PtCardForm;
    if (formType.value === 'create') {
      await PtCardApi.addPtCard(data);
      proxy?.$modal.msgSuccess('新增成功');
    } else {
      await PtCardApi.updatePtCard(data);
      proxy?.$modal.msgSuccess('修改成功');
    }
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

/** 初始化 */
onMounted(() => {});
</script>
