<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema, Platform } from './config';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { saveOrUpdateBigScreenCenter } from '/@/api/bigscreen/center/bigscreenCenter';
  import { FileItem } from '/@/components/Form/src/components/ApiUpload.vue';
  import { buildUUID } from '/@/utils/uuid';

  export default defineComponent({
    name: 'BigScreenDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          if (data.record.thumbnail) {
            data.record.thumbnail = [
              { uid: buildUUID(), name: 'name', url: data.record.thumbnail } as FileItem,
            ];
          }
          if (data.record.organizationDTO) {
            await setFieldsValue(data.record);
          } else {
            Reflect.deleteProperty(data.record, 'organizationId');
            await setFieldsValue(data.record);
          }
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增大屏' : '编辑大屏'));

      const getDefaultContent = (platform: Platform) => {
        if (platform === Platform.PC) {
        }
      };

      async function handleSubmit() {
        try {
          const { createMessage } = useMessage();
          const values = await validate();
          if (Reflect.has(values, 'thumbnail')) {
            const file = (values.thumbnail || []).at(0) || {};
            values.thumbnail = file.url || null;
          }
          setDrawerProps({ confirmLoading: true });
          let saveMessage = '添加成功';
          let updateMessage = '修改成功';
          values.defaultContent = getDefaultContent(values.platform);
          await saveOrUpdateBigScreenCenter(values, unref(isUpdate));
          closeDrawer();
          emit('success');
          createMessage.success(unref(isUpdate) ? updateMessage : saveMessage);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        getTitle,
        registerDrawer,
        registerForm,
        handleSubmit,
      };
    },
  });
</script>
