<template>
  <div>
    <BasicDrawer
      v-bind="$attrs"
      @register="registerDrawer"
      :title="getTitle"
      width="800px"
      showFooter
    >
      <BasicForm @register="registerForm" />
      <template #footer>
        <a-button @click="handleCancel">取消</a-button>
        <Authority value="api:yt:notice:save:post">
          <a-button :disabled="draftDisable" @click="handleSaveDraft">保存草稿</a-button>
        </Authority>
        <a-button :disabled="sendDisable" type="primary" @click="handleSend">发布通知</a-button>
      </template>
    </BasicDrawer>
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed, unref, ref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './config.d';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    notifyAddDraftApi,
    notifyAddLeaseApi,
  } from '/@/api/stationnotification/stationnotifyApi';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Authority } from '/@/components/Authority';
  import { useUserStore } from '/@/store/modules/user';
  import headerImg from '/@/assets/images/logo.png';

  export default defineComponent({
    name: 'ConfigDrawer',
    components: { BasicDrawer, BasicForm, Authority },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const draftDisable = ref(false);
      const sendDisable = ref(false);
      const { createMessage } = useMessage();
      const isUpdate = ref<Boolean>();
      const getTitle = computed(() => (!unref(isUpdate) ? '新增通知' : '编辑通知'));
      const noticeId = ref('');
      const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data.isUpdate;
        //编辑
        if (data.isUpdate) {
          noticeId.value = data.record.id;
          Reflect.set(data.record, 'receiverType', data.record.receiverType === 0 ? 0 : 1);
          if (data.record.receiverType === 1) {
            if (!data.record.pointId.length) return;
            const organizationId = data.record.pointId.split(',');
            Reflect.set(data.record, 'organizationId', organizationId);
          }
          setFieldsValue(data.record);
        }
      });
      const userStore = useUserStore();
      const avatar = ref<string | undefined>('');
      avatar.value = userStore.getUserInfo?.avatar || headerImg;
      // 发布通知
      const handleSend = async () => {
        try {
          sendDisable.value = true;
          const valid = await validate();
          if (!valid) return;
          const field = getFieldsValue();
          const pointId = field.receiverType === 1 ? field.organizationId + '' : null;
          // 新增情况
          const editNotice = {
            ...field,
            pointId,
            id: unref(isUpdate) ? unref(noticeId) : undefined,
            avatar: avatar.value,
          };
          await notifyAddLeaseApi(editNotice);
          emit('success');
          closeDrawer();
          createMessage.success('发布成功');
        } catch {
          sendDisable.value = false;
        } finally {
          setTimeout(() => {
            sendDisable.value = false;
          }, 300);
        }
      };
      // 保存草稿
      const handleSaveDraft = async () => {
        draftDisable.value = true;
        try {
          await validate();
          const field = getFieldsValue();
          const pointId = field.receiverType === 1 ? field.organizationId + '' : null;
          if (!unref(isUpdate)) {
            const saveDraft = {
              ...field,
              pointId,
            };
            await notifyAddDraftApi(saveDraft);
          } else {
            const editDraft = {
              ...field,
              pointId,
              id: unref(noticeId),
              avatar: avatar.value,
            };
            await notifyAddDraftApi(editDraft);
          }
          emit('success');
          closeDrawer();
          createMessage.success('保存草稿成功');
        } catch {
          draftDisable.value = false;
        } finally {
          setTimeout(() => {
            draftDisable.value = false;
          }, 300);
        }
      };
      const handleCancel = () => {
        // resetFields();
        closeDrawer();
      };
      return {
        draftDisable,
        sendDisable,
        getTitle,
        handleSend,
        handleCancel,
        handleSaveDraft,
        registerForm,
        registerDrawer,
        setFieldsValue,
      };
    },
  });
</script>
