<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #alarmContactSlot="{ model, field }">
        <p style="display: none">{{ field }}</p>
        <p style="display: none">{{ orgFunc(model['organizationId']) }}</p>
        <a-select
          placeholder="请选择告警联系人"
          mode="multiple"
          v-model:value="model[field]"
          :options="alarmContactOptions.map((item) => ({ value: item.value, label: item.label }))"
        >
          <template #dropdownRender="{ menuNode: menu }">
            <v-nodes :vnodes="menu" />
            <a-divider style="margin: 4px 0" />
            <div @click="handleOpenAlarmContact" style="padding: 4px 8px; cursor: pointer">
              <plus-outlined />
              新增告警联系人
            </div>
          </template>
        </a-select>
      </template>
    </BasicForm>
  </BasicDrawer>
  <AlarmContactDrawer @register="registerAlarmContactDrawer" @success="handleSuccess" />
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive, watch } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './config.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { saveOrEditAlarmConfig, byOrgIdGetAlarmContact } from '/@/api/alarm/config/alarmConfig';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { useDrawer } from '/@/components/Drawer';
  import AlarmContactDrawer from '../../alarm/contacts/ContactDrawer.vue';

  export default defineComponent({
    name: 'ContactDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      AlarmContactDrawer,
      PlusOutlined,
      VNodes: (_, { attrs }) => {
        return attrs.vnodes;
      },
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const alarmContactOptions: any = ref([]);
      const orgId = ref('');
      const orgFunc = (e) => {
        orgId.value = e;
      };
      watch(
        () => orgId.value,
        async (newValue: string) => {
          if (newValue) {
            setFieldsValue({ alarmContactId: [] });
            //获取告警联系人
            const res = await byOrgIdGetAlarmContact(newValue);
            if (res) {
              alarmContactOptions.value = res.map((m) => {
                return { label: m.username, value: m.id };
              });
            } else {
              alarmContactOptions.value = [];
            }
          } else {
            alarmContactOptions.value = [];
          }
        }
      );
      const [registerAlarmContactDrawer, { openDrawer }] = useDrawer();
      async function handleSuccess() {
        //获取告警联系人
        const res = await byOrgIdGetAlarmContact(orgId.value);
        if (res) {
          alarmContactOptions.value = res.map((m) => {
            return { label: m.username, value: m.id };
          });
        } else {
          alarmContactOptions.value = [];
        }
      }
      // 新增或编辑
      const handleOpenAlarmContact = () => {
        openDrawer(true, {
          isUpdate: false,
        });
      };
      const isUpdate = ref(true);
      let allData: any = reactive({});
      const editId = ref('');
      const [registerForm, { validate, setFieldsValue, resetFields, updateSchema }] = 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.record?.id) {
          editId.value = data.record?.id;
        }
        if (unref(isUpdate)) {
          const res = await byOrgIdGetAlarmContact(data.record.organizationId);
          if (res.length !== 0) {
            const opts = res.map((m) => {
              return { label: m.username, value: m.id };
            });
            updateSchema({
              field: 'alarmContactId',
              componentProps: {
                mode: 'multiple',
                options: opts,
              },
            });
          }
          await setFieldsValue(data.record);
          await setFieldsValue({
            alarmContactId: data.record?.alarmContactId.split(','),
            messageMode: data.record?.messageMode.split(','),
          });
        } else {
          updateSchema({
            field: 'alarmContactId',
            componentProps: {
              mode: 'multiple',
              options: [],
            },
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增告警配置' : '编辑告警配置'));

      async function handleSubmit() {
        setDrawerProps({ confirmLoading: true });
        try {
          const { createMessage } = useMessage();
          const values = await validate();
          if (!values) return;
          const alarmContactIdD = {
            alarmContactId: values.alarmContactId.join(','),
          };
          const messageModeD = {
            messageMode: values.messageMode.join(','),
          };
          const editIdVal = !unref(isUpdate) ? '' : editId.value;

          allData = {
            ...{ id: editIdVal },
            ...values,
            ...alarmContactIdD,
            ...messageModeD,
          };
          if (!unref(isUpdate)) {
            delete allData.id;
          }
          let saveMessage = '添加成功';
          let updateMessage = '修改成功';
          await saveOrEditAlarmConfig(allData);
          closeDrawer();
          emit('success');
          createMessage.success(unref(isUpdate) ? updateMessage : saveMessage);
        } finally {
          setTimeout(() => {
            setDrawerProps({ confirmLoading: false });
          }, 300);
        }
      }

      return {
        getTitle,
        registerDrawer,
        registerForm,
        handleSubmit,
        alarmContactOptions,
        orgFunc,
        handleOpenAlarmContact,
        registerAlarmContactDrawer,
        handleSuccess,
      };
    },
  });
</script>
