<template>
  <BasicDrawer
    v-bind="$attrs"
    width="50%"
    :showDetailBack="false"
    :title="getTitle"
    @register="registerDrawer"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, computed, ref, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { padsSchemas } from './schemas';
  import { padsSaveApi, padsUpdateApi } from '/@/api/advertisement/list';

  export default defineComponent({
    components: { BasicDrawer, BasicForm },
    props: {
      type: {
        type: String,
        default: '0',
      },
    },
    emits: ['reload'],
    setup(props, { emit }) {
      const { createMessage } = useMessage();
      const modelRef = ref({
        type: props.type,
      });
      const isUpdate = ref(true);
      const [registerForm, { validate, setProps, resetFields, setFieldsValue }] = useForm({
        labelCol: {
          span: 4,
        },
        wrapperCol: {
          span: 18,
        },
        schemas: padsSchemas,
        actionColOptions: {
          offset: 8,
          span: 8,
        },
        submitButtonOptions: {
          text: '提交',
        },
        submitFunc: summitAddDrawer,
      });

      async function summitAddDrawer() {
        try {
          let data = await validate();
          let httpApi = unref(isUpdate) ? padsUpdateApi : padsSaveApi;
          setProps({
            submitButtonOptions: {
              loading: true,
            },
          });
          httpApi({
            ...modelRef.value,
            ...data,
            image: data.image[0],
          }).then((_) => {
            setProps({
              submitButtonOptions: {
                loading: false,
              },
            });
            createMessage.success('提交成功！');
            emit('reload');
            closeDrawer();
          });
        } catch (error) {
          console.log('error', error);
        }
      }
      const getTitle = computed(() => (!unref(isUpdate) ? '新增推荐位' : '编辑推荐位'));
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        modelRef.value = {
          ...data.record,
          type: props.type,
        };

        if (unref(isUpdate)) {
          console.log('data.record', data.record);
          setFieldsValue({
            ...data.record,
            image: [data.record.image],
          });
        }
      });
      return {
        registerForm,
        getTitle,
        registerDrawer,
        closeDrawer,
      };
    },
  });
</script>
