<script setup lang="ts">
  import { computed, ref, unref } from 'vue';
  import { SceneLinkageDrawerDataType } from './type';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { DataActionModeEnum, DataActionModeNameEnum } from '/@/enums/toolEnum';
  import { BasicForm, useForm } from '/@/components/Form';
  import { getFormSchemas, FormFieldsEnum } from './config';
  import { createSceneLinkageDrawerContext } from './sceneLinkageDrawerContext';
  import { FlipFlop } from '../FlipFlop';
  import { Divider, Tooltip } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import { ExecutionAction } from '../ExecutionAction';
  import { useSceneLinkageData } from './useSceneLinkedgeData';
  import { screenLinkPageAddApi } from '/@/api/ruleengine/ruleengineApi';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { OrganizationListItem } from '/@/api/system/model/systemModel';
  import { FlipFlopComponentTypeEnum } from '../FlipFlop/types';

  const emit = defineEmits(['success', 'register']);

  const drawerMode = ref(DataActionModeEnum.CREATE);

  const getDrawTitle = computed(() => `${DataActionModeNameEnum[unref(drawerMode)]}场景联动`);

  const disabledDrawer = ref(false);

  const currentUpdateLinkedgeId = ref<string>();

  const [register, { setDrawerProps, closeDrawer }] = useDrawerInner(
    (data: SceneLinkageDrawerDataType) => {
      const { mode, record } = data;
      drawerMode.value = mode;
      disabledDrawer.value = mode === DataActionModeEnum.READ;
      resetFieldsValue?.();

      if (mode === DataActionModeEnum.UPDATE || mode === DataActionModeEnum.READ) {
        currentUpdateLinkedgeId.value = record.id;
        setDrawerProps({ loading: true });
        handleOnOrganizationChange(data.record.organizationId);
        setTimeout(() => {
          setFieldsValue(record);
          setDrawerProps({ loading: false });
        }, 300);
      }

      setDrawerProps({
        showOkBtn: !unref(disabledDrawer),
        cancelText: unref(disabledDrawer) ? '关闭' : '取消',
      });
    }
  );

  const [registerForm, basicFormActionType] = useForm({
    schemas: getFormSchemas(handleOnOrganizationChange, handleOnOrganizationOptionsChange),
    layout: 'horizontal',
    labelWidth: 120,
    showActionButtonGroup: false,
  });

  const organizationId = ref<string>();

  function handleOnOrganizationChange(id: string) {
    organizationId.value = id;
  }

  function handleOnOrganizationOptionsChange(options: OrganizationListItem[]) {
    if (unref(drawerMode) === DataActionModeEnum.CREATE) {
      const [firsetItem] = options;
      organizationId.value = firsetItem?.id;
      basicFormActionType.setFieldsValue({ [FormFieldsEnum.ORGANIZATION_ID]: firsetItem?.id });
    }
  }

  createSceneLinkageDrawerContext({
    organizationId: computed(() => unref(organizationId)),
    disabledDrawer: computed(() => unref(disabledDrawer)),
  });

  const flipFlopElRef = ref<InstanceType<typeof FlipFlop>>();

  const executionConditionElRef = ref<InstanceType<typeof FlipFlop>>();

  const executionActionElRef = ref<InstanceType<typeof ExecutionAction>>();

  const { getFieldsValue, setFieldsValue, validate, resetFieldsValue } = useSceneLinkageData({
    flipFlopElRef,
    executionActionElRef,
    executionConditionElRef,
    basicFormActionType,
  });

  const { createMessage } = useMessage();
  const handleSave = async () => {
    await validate?.();
    setDrawerProps({ loading: true, confirmLoading: true });
    try {
      const value = getFieldsValue();

      if (unref(drawerMode) === DataActionModeEnum.UPDATE) {
        Reflect.set(value, 'id', unref(currentUpdateLinkedgeId));
      }

      await screenLinkPageAddApi(value, unref(drawerMode) === DataActionModeEnum.UPDATE);
      createMessage.success(`${DataActionModeNameEnum[unref(drawerMode)]}成功`);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ loading: false, confirmLoading: false });
    }
  };
</script>

<template>
  <BasicDrawer
    @register="register"
    :title="getDrawTitle"
    width="50%"
    @ok="handleSave"
    show-cancel-btn
    show-footer
  >
    <BasicForm @register="registerForm" :disabled="disabledDrawer">
      <template #flipFlop>
        <Divider orientation="left">
          <Tooltip>
            <template #title> 触发器不可为空，消息只要满足触发条件中任意一个即可触发。 </template>
            <label><span class="text-red-400 mr-1">*</span>触发器</label>
            <Icon icon="ant-design:question-circle-outlined" class="ml-2" />
          </Tooltip>
        </Divider>
        <FlipFlop ref="flipFlopElRef" :type="FlipFlopComponentTypeEnum.FLIP_FLOP" />
      </template>
      <template #executionCondition>
        <Divider orientation="left">
          <Tooltip>
            <template #title> 执行条件可为空，消息需要满足所有执行条件才会被处理。 </template>
            <label>执行条件</label>
            <Icon icon="ant-design:question-circle-outlined" class="ml-2" />
          </Tooltip>
        </Divider>
        <FlipFlop
          ref="executionConditionElRef"
          addButtonName="执行条件 (AND)"
          default-null
          :panel-title="(index) => `执行条件${index}`"
          :type="FlipFlopComponentTypeEnum.EXECUTION_CONDITION"
        />
      </template>
      <template #executionAction>
        <Divider orientation="left">
          <Tooltip>
            <template #title>
              触发器和执行条件都满足时，场景联动会做什么，例如：设备联动、告警通知等。
            </template>
            <label><span class="text-red-400 mr-1">*</span>执行动作</label>
            <Icon icon="ant-design:question-circle-outlined" class="ml-2" />
          </Tooltip>
        </Divider>
        <ExecutionAction ref="executionActionElRef" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
