<script setup lang="ts">
// @ts-ignore
import { defineEmits, ref } from 'vue';
// @ts-ignore
import { useVbenDrawer, useVbenForm } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { drawerFormSchema } from './config-data';

const emit = defineEmits<{ reload: []; confirm: [data: any] }>();
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});
const isUpdateRef = ref<boolean>(false);
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen:any) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        // 如果是编辑模式，这里可以加载数据
        // const recordData = await getRecordDetail(recordId);
        // await formApi.setValues(recordData);
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid, errors } = await formApi.validate();
      if (!valid) {
        return;
      }
      // 手动添加时间范围校验
      const data = await formApi.getValues();
      if (data.startTime && data.endTime) {
        const startTime = new Date(data.startTime);
        const endTime = new Date(data.endTime);
        if (endTime <= startTime) {
          ElMessage.error('下班时间必须大于上班时间');
          return;
        }
      }
      emit('confirm', data);
    } catch (error:any) {
      ElMessage.error(error.message);
    } finally {
      this.confirmLoading = false;
    }
  },
  onClosed() {
    formApi.resetForm();
  },
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑工作记录' : '新增工作记录'">
    <Form />
  </Drawer>
</template>
