<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { LaborCostApi } from '#/api/hr/laborCost';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { apiAdd, apiUpdate } from '#/api/hr/laborCost';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits<{
  success: [];
}>();
const isUpdate = ref(false);

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
    label: 'id',
  },
  {
    component: 'DatePicker',
    fieldName: 'recordDate',
    label: '记录时间',
    rules: 'required',
  },
  {
    component: 'FileUpload',
    componentProps: {
      maxCount: 1,
    },
    fieldName: 'ossId',
    formItemClass: 'items-start',
    label: '文件',
    rules: 'required',
  },
  // {
  //   component: 'Input',
  //   fieldName: 'fileKey',
  //   label: '文件Key',
  //   rules: 'required',
  // },
  {
    component: 'Textarea',
    fieldName: 'remark',
    label: '备注',
    // rules: 'required',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 90,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    const data = drawerApi.getData<LaborCostApi.LaborCost>();
    isUpdate.value = !!data?.id;
    if (isUpdate.value) {
      await formApi.setValues(data);
    } else {
      formApi.resetForm();
    }
    await markInitialized();
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<LaborCostApi.LaborCost>();
    try {
      await (isUpdate.value ? apiUpdate(data) : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const getDrawerTitle = computed(() =>
  isUpdate.value ? '修改人工成本档案' : '新增人工成本档案',
);
</script>
<template>
  <Drawer class="w-full max-w-[800px]" :title="getDrawerTitle">
    <BasicForm class="mx-4" />
  </Drawer>
</template>
