<template>
  <BasicDrawer v-bind="$attrs" width="50%" :title="getTitle" @register="registerDrawer">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, computed } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { schemas } from './schemas';
  import { itemUpdateApi, itemSaveApi } from '/@/api/advertisement/list';
  export default defineComponent({
    components: { BasicDrawer, BasicForm },
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const modelRef = ref({});
      const isUpdate = ref(true);
      const [registerForm, { validate, setProps, resetFields, setFieldsValue }] = useForm({
        labelCol: {
          span: 4,
        },
        wrapperCol: {
          span: 18,
        },
        schemas: schemas,
        actionColOptions: {
          offset: 8,
          span: 8,
        },
        submitButtonOptions: {
          text: '提交',
        },
        submitFunc: summitAddDrawer,
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增轮播资讯' : '编辑轮播资讯'));
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        modelRef.value = data.record;
        if (unref(isUpdate)) {
          console.log('data.record', data.record);
          setFieldsValue({
            ...data.record,
            image: [data.record.image],
          });
        }
      });

      async function summitAddDrawer() {
        try {
          let data = await validate();
          let httpApi = unref(isUpdate) ? itemUpdateApi : itemSaveApi;
          setProps({
            submitButtonOptions: {
              loading: true,
            },
          });
          console.log('data', data, modelRef.value);
          httpApi({
            ...modelRef.value,
            ...data,
            image:
              'http://zfb-4dkankan.oss-cn-shenzhen.aliyuncs.com/scene/1546422941329_测试.png' ??
              data.image.toString(),
          }).then((res) => {
            console.log('itemUpdateApi', res);
            setProps({
              submitButtonOptions: {
                loading: false,
              },
            });
            createMessage.success('提交成功！');
            emit('reload');
            closeDrawer();
          });

          // setTimeout(() => {

          // }, 2000);
        } catch (error) {}
      }

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