<template>
  <div>
    <BasicDrawer
      v-bind="$attrs"
      @register="registerDrawer"
      @ok="handleSubmit"
      destroy-on-close
      width="50%"
      showFooter
      @close="handleClose"
      :title="title"
    >
      <div>
        <!-- 基础表单 -->
        <BasicForm @register="registerForm" />
        <!-- 基础表单 -->
        <!-- 触发器-begin -->
        <!-- <Divider orientation="left">触发器</Divider> -->
        <Divider orientation="left">
          <a-tooltip>
            <template #title>触发器不可为空，消息只要满足触发条件中任意一个即可触发。</template>
            触发器
            <QuestionCircleOutlined :style="{ fontSize: '14px', marginLeft: '5px' }" />
          </a-tooltip>
        </Divider>
        <div>
          <template v-for="(item, index) in triggerData" :key="item">
            <TriggerOrCondition
              class="mt-4"
              title="触发器"
              :index="index"
              :provideOrgid="provideOrgid"
              :ref="skipUnwrap.triggerItemRefs"
              @delete="deleteTriggerOrCondition"
            />
          </template>
          <!-- 按钮 -->
          <a-button type="primary" class="mt-4" @click="addTrigger" v-if="isView">
            <PlusOutlined />
            触发器（OR）<span style="visibility: hidden">发</span>
          </a-button>
          <!-- 按钮 -->
        </div>
        <!-- 触发器-end -->

        <!-- 执行条件-begin -->
        <Divider orientation="left">
          <a-tooltip>
            <template #title>执行条件可为空，消息需要满足所有执行条件才会被处理。</template>
            执行条件
            <QuestionCircleOutlined :style="{ fontSize: '14px', marginLeft: '5px' }" />
          </a-tooltip>
        </Divider>
        <div>
          <template v-for="(item, index) in conditionData" :key="item">
            <TriggerOrCondition
              class="mt-4"
              title="执行条件"
              :index="index"
              :provideOrgid="provideOrgid"
              :ref="skipUnwrap.conditionItemRefs"
              @delete="deleteTriggerOrCondition"
            />
          </template>
          <!-- 按钮 -->
          <a-button type="primary" class="mt-4" @click="addCondition" v-if="isView">
            <PlusOutlined />
            执行条件（AND）
          </a-button>
          <!-- 按钮 -->
        </div>
        <!-- 执行条件-end -->

        <!-- 执行动作-begin -->
        <Divider orientation="left">
          <a-tooltip>
            <template #title
              >触发器和执行条件都满足时，场景联动会做什么，例如：设备联动、告警通知等。</template
            >
            执行动作
            <QuestionCircleOutlined :style="{ fontSize: '14px', marginLeft: '5px' }" />
          </a-tooltip>
        </Divider>
        <div>
          <template v-for="(item, index) in actionData" :key="item">
            <Action
              class="mt-4"
              :actionIndex="index"
              :actionData="actionData"
              :triggerData="triggerData"
              :ref="skipUnwrap.actionItemRefs"
              :provideOrgid="provideOrgid"
              :deviceList="getMasterDeviceList"
              :arr="arr"
              @deleteAction="deleteAction"
              @getActionFormArr="getActionFormArr"
              @dynamicChangeAlarmConfig="handleDynamicChangeAlarmConfig"
            />
          </template>
          <!-- 按钮 -->
          <a-button type="primary" class="mt-4" @click="addAction" v-if="isView">
            <PlusOutlined />
            新增执行动作
          </a-button>
          <!-- 按钮 -->
        </div>
        <!-- 执行动作-end -->
      </div>
    </BasicDrawer>
  </div>
</template>
<script lang="ts" setup>
  import { ref, watch, unref, computed, nextTick } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { formSchema, organizationId as organizationIdRef } from './config/config.data';
  import { BasicForm, useForm } from '/@/components/Form';
  import { genTriggerOrConditionData, genActionData } from './config/formatData';
  import { Divider } from 'ant-design-vue';
  import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    screenLinkPageAddApi,
    screenLinkPageByDeptIdGetDevice,
    getOrganizationAlarmConfig,
  } from '/@/api/ruleengine/ruleengineApi';
  import TriggerOrCondition from './cpns/Trigger-Condition.vue';
  import Action from './cpns/Action.vue';
  import { findOperation } from './config/formatData';
  import { formatToDateTime } from '/@/utils/dateUtil';
  import ObjectModelValidateForm from '/@/components/Form/src/externalCompns/components/ObjectModelValidateForm/ObjectModelValidateForm.vue';
  import { add } from '/@/components/Form/src/componentMap';

  add('ObjectModelValidateForm', ObjectModelValidateForm);

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

  const { createMessage } = useMessage();
  const triggerData = ref<number[]>([]);
  const conditionData = ref<number[]>([]);
  const actionData = ref<number[]>([]);
  const skipUnwrap = {
    triggerItemRefs: ref<InstanceType<typeof TriggerOrCondition>[]>([]),
    conditionItemRefs: ref<InstanceType<typeof TriggerOrCondition>[]>([]),
    actionItemRefs: ref<InstanceType<typeof Action>[]>([]),
  };
  const title = computed(
    () => `${isUpdate.value === 3 ? '查看' : isUpdate.value ? '编辑' : '新增'}场景联动`
  );
  let getTriggerFormValue = ref([]);
  let getConditionFormValue = ref([]);
  let getActionFormValue = ref([]);
  const editEntryIdData = ref([]);
  const editAlarmConfigData = ref([]);
  const isUpdate = ref(false);
  const id = ref(undefined);
  const tenantId = ref(undefined);
  const isView = ref(true);
  const [registerForm, { resetFields, validate, setFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ confirmLoading: false, loading: true });
    isUpdate.value = data.isUpdate;
    getActionFormArr();
    if (!unref(isUpdate)) {
      resetFields();
      //初始化执行动作
      actionData.value = [Date.now()];
    } else {
      // 取值
      const {
        id: recordId,
        tenantId: recordTenantId,
        organizationId,
        triggers,
        doConditions,
        doActions,
      } = data.record;
      organizationIdRef.value = organizationId;
      // 赋值
      await setFieldsValue(data.record);
      id.value = recordId;
      tenantId.value = recordTenantId;
      //TODO-fengtao-把组织id传给子组件
      provideOrgid.value = organizationId;
      //TODO-fengtao获取当前执行动作下的设备(master那个接口)
      // getMasterDeviceList.value = await byOrganizationIdGetMasterDevice(organizationId);
      //TODO-fengtao
      // 获取当前组织下的设备列表
      const options = await screenLinkPageByDeptIdGetDevice({
        organizationId,
      });
      // 获取当前组织下的告警配置
      const alarmConfig = await getOrganizationAlarmConfig({ organizationId });

      // 生成回显时对应得组件数量
      triggerData.value = [...new Array(triggers.length).keys()];
      conditionData.value = [...new Array(doConditions.length).keys()];
      actionData.value = [...new Array(doActions.length).keys()];
      // 回显设备列表
      editEntryIdData.value = options.items.map((item) => {
        return {
          value: item.tbDeviceId,
          label: item.name,
        };
      });
      editAlarmConfigData.value = alarmConfig.map((item) => {
        return {
          value: item.id,
          label: item.name,
        };
      });
      deviceList.value = editEntryIdData.value;
      nextTick(() => {
        setEditFields(skipUnwrap.triggerItemRefs, editEntryIdData);
        setEditFields(skipUnwrap.conditionItemRefs, editEntryIdData);
        setEditFields(skipUnwrap.actionItemRefs, getMasterDeviceList);
        setEditAlarmConfig(skipUnwrap.actionItemRefs, editAlarmConfigData);
      });

      const map = {
        ANY_TIME: 0,
        SPECIFIC_TIME: 1,
        CUSTOM: 2,
      };
      // 回显触发器数据---此处是个闭包!
      triggers.forEach((trigger, index) => {
        nextTick(async () => {
          const selectProductId = ref('');
          // 回显启用规则
          unref(skipUnwrap.triggerItemRefs)[index].currentIndex =
            map[trigger.triggerCondition.schedule.type];
          unref(skipUnwrap.triggerItemRefs)[index].scheduleData = trigger.triggerCondition.schedule;
          unref(skipUnwrap.triggerItemRefs)[index].isUpdate = true;
          unref(skipUnwrap.triggerItemRefs)[index].alarmScheduleRef.scheduleData =
            trigger.triggerCondition.schedule;
          unref(skipUnwrap.triggerItemRefs)[index].setFieldsFormValueFun({
            triggered: trigger?.triggerCondition?.condition?.spec?.type,
            device: trigger?.entityType,
            deviceType: trigger?.deviceType,
            triggerType: trigger?.triggerType,
            type1: trigger?.triggerCondition?.condition?.condition[0]?.key?.type,
            type2: trigger?.triggerCondition?.condition?.condition[0]?.key?.key,
            operationType: trigger?.triggerCondition?.condition?.condition[0]?.valueType,
            detail: trigger?.triggerCondition?.alarmDetails,
            entityId: trigger?.entityId,
            deviceProfileId: trigger?.deviceProfileId,
            replaceValue: trigger?.triggerCondition?.condition?.spec?.predicate?.defaultValue,
            time: trigger?.triggerCondition?.condition?.spec?.predicate?.defaultValue,
            timeUnit: trigger?.triggerCondition?.condition?.spec?.unit,
          });
          if (trigger.deviceProfileId != undefined) {
            selectProductId.value = trigger?.deviceProfileId;
          }
          //fengtao-把设备id回传给子组件
          unref(skipUnwrap.triggerItemRefs)[index].updateFieldAttributeFunc(selectProductId.value);
          //fengtao
          // 设置值operationType
          unref(skipUnwrap.triggerItemRefs)[index].operationType =
            trigger.triggerCondition?.condition.condition[0].valueType;

          const ConditionScreeningForm = await unref(skipUnwrap.triggerItemRefs)[
            index
          ].getRefItemConditionScreeningRefs();

          // 设置对应条件筛选的个数
          unref(skipUnwrap.triggerItemRefs)[index].setConditionScreeningList([
            ...new Array(trigger.triggerCondition.condition.condition.length).keys(),
          ]);
          // 操作符类型 NUMERIC|String|Boolean|DATE_TIME
          const valueType = trigger.triggerCondition?.condition.condition[0].valueType;

          // 循环设置条件筛选值。TODO:此处设置顺序有问题
          nextTick(() => {
            const richTextList = [];
            trigger.triggerCondition.condition.condition.forEach((item, index) => {
              const formItem = {
                operation: item.predicate.operation,
                value:
                  valueType === 'DATE_TIME'
                    ? formatToDateTime(
                        Number(item.predicate.value.defaultValue),
                        'YYYY-MM-DD HH:mm:ss'
                      )
                    : String(item.predicate.value.defaultValue),
                ignoreCase: item.valueType === 'STRING' ? item.predicate.ignoreCase : undefined,
              };
              richTextList.push({
                // 查询中文操作符
                operation: findOperation(valueType, item.predicate.operation).label,
                value:
                  valueType === 'DATE_TIME'
                    ? formatToDateTime(
                        Number(item.predicate.value.defaultValue),
                        'YYYY-MM-DD HH:mm:ss'
                      )
                    : String(item.predicate.value.defaultValue),
                attribute: trigger.triggerCondition?.condition.condition[0]?.key?.key,
              });
              ConditionScreeningForm.value[index].setFieldsValue(formItem);
            });
            unref(skipUnwrap.triggerItemRefs)[index].setRichText(richTextList);
          });
        });
      });

      doConditions.forEach((condition, index) => {
        nextTick(async () => {
          const selectProductId = ref('');
          // 回显启用规则
          unref(skipUnwrap.conditionItemRefs)[index].currentIndex =
            map[condition.triggerCondition.schedule.type];
          unref(skipUnwrap.conditionItemRefs)[index].scheduleData =
            condition.triggerCondition.schedule;
          unref(skipUnwrap.conditionItemRefs)[index].isUpdate = true;
          unref(skipUnwrap.conditionItemRefs)[index].alarmScheduleRef.scheduleData =
            condition.triggerCondition.schedule;
          unref(skipUnwrap.conditionItemRefs)[index].setFieldsFormValueFun({
            triggered: condition?.triggerCondition?.condition?.spec?.type,
            device: condition?.entityType,
            triggerType: condition?.triggerType,
            type1: condition?.triggerCondition?.condition?.condition[0]?.key?.type,
            type2: condition?.triggerCondition?.condition?.condition[0]?.key?.key,
            operationType: condition?.triggerCondition?.condition?.condition[0]?.valueType,
            detail: condition?.triggerCondition?.alarmDetails,
            entityId: condition?.entityId,
            deviceProfileId: condition?.deviceProfileId,
            deviceType: condition?.deviceType,
            replaceValue: condition?.triggerCondition?.condition?.spec?.predicate?.defaultValue,
            time: condition?.triggerCondition?.condition?.spec?.predicate?.defaultValue,
            timeUnit: condition?.triggerCondition?.condition?.spec?.unit,
          });
          if (condition?.deviceProfileId != undefined) {
            selectProductId.value = condition?.deviceProfileId;
          }
          //fengtao-把设备id回传给子组件
          unref(skipUnwrap.conditionItemRefs)[index].updateFieldAttributeFunc(
            selectProductId.value
          );
          //fengtao
          // 设置值operationType
          unref(skipUnwrap.conditionItemRefs)[index].operationType =
            condition.triggerCondition?.condition.condition[0].valueType;

          const ConditionScreeningForm = await unref(skipUnwrap.conditionItemRefs)[
            index
          ].getRefItemConditionScreeningRefs();

          // 设置对应条件筛选的个数
          unref(skipUnwrap.conditionItemRefs)[index].setConditionScreeningList([
            ...new Array(condition.triggerCondition.condition.condition.length).keys(),
          ]);
          // 操作符类型 NUMERIC|String|Boolean|DATorganizeImportsE_TIME
          const valueType = condition.triggerCondition?.condition.condition[0].valueType;

          // 循环设置条件筛选值。TODO:此处设置顺序有问题
          nextTick(() => {
            const richTextList = [];
            condition.triggerCondition.condition.condition.forEach((item, index) => {
              const formItem = {
                operation: item.predicate.operation,
                value:
                  valueType === 'DATE_TIME'
                    ? formatToDateTime(
                        Number(item.predicate.value.defaultValue),
                        'YYYY-MM-DD HH:mm:ss'
                      )
                    : String(item.predicate.value.defaultValue),
                ignoreCase: item.valueType === 'STRING' ? item.predicate.ignoreCase : undefined,
              };
              richTextList.push({
                // 查询中文操作符
                operation: findOperation(valueType, item.predicate.operation).label,
                value:
                  valueType === 'DATE_TIME'
                    ? formatToDateTime(
                        Number(item.predicate.value.defaultValue),
                        'YYYY-MM-DD HH:mm:ss'
                      )
                    : String(item.predicate.value.defaultValue),
                attribute: condition.triggerCondition?.condition.condition[0]?.key?.key,
              });
              ConditionScreeningForm.value[index].setFieldsValue(formItem);
            });
            unref(skipUnwrap.conditionItemRefs)[index].setRichText(richTextList);
          });
        });
      });
      doActions.forEach((action, index) => {
        nextTick(() => {
          const selectProductId = ref('');
          // 设置执行动作外层值
          unref(skipUnwrap.actionItemRefs)[index].setFieldsFormValueFun({
            ...action,
            outTarget: action.outTarget,
            device: action.entityType,
            deviceId: action.deviceId,
            alarm_config: action.alarmProfileId,
            alarm_level: action.doContext.alarmLevel,
          });
          // 如果是设备输出设置脚本值
          if (action.outTarget === 'DEVICE_OUT') {
            if (action.commandType.toString() === '0') {
              unref(skipUnwrap.actionItemRefs)[index].setJsonValue(action.doContext.params);
            }
          }
          // 清除告警有值?{数组}
          if (action?.doContext?.clearRule?.length) {
            unref(skipUnwrap.actionItemRefs)[index].checked = true;
            // 生成对应清除告警的数组长度
            unref(skipUnwrap.actionItemRefs)[index].clearRuleList = [
              ...new Array(action?.doContext?.clearRule?.length).keys(),
            ];
            // 推迟执行时机-DOM渲染完毕在执行
            nextTick(async () => {
              unref(skipUnwrap.actionItemRefs)[index].refItem.clearRuleRefs.value.map(
                (item, index) => {
                  // 回显启用规则
                  item.currentIndex =
                    map[action.doContext.clearRule[index].triggerCondition.schedule.type];
                  item.scheduleData = action.doContext.clearRule[index].triggerCondition.schedule;
                  item.isUpdate = true;
                  item.alarmScheduleRef.scheduleData =
                    action.doContext.clearRule[index].triggerCondition.schedule;
                  item.setFieldsFormValueFun({
                    triggered:
                      action.doContext.clearRule[index].triggerCondition.condition.spec.type,
                    device: action.doContext.clearRule[index].entityType,
                    deviceType: action.doContext.clearRule[index].deviceType,
                    triggerType: action.doContext.clearRule[index].triggerType,
                    type1:
                      action.doContext.clearRule[index].triggerCondition.condition.condition[0].key
                        .type,
                    type2:
                      action.doContext.clearRule[index].triggerCondition.condition.condition[0].key
                        .key,
                    operationType:
                      action.doContext.clearRule[index].triggerCondition.condition.condition[0]
                        .valueType,
                    detail: action.doContext.clearRule[index].triggerCondition.alarmDetails,
                    entityId: action.doContext.clearRule[index].entityId,
                    deviceProfileId: action.doContext.clearRule[index]?.deviceProfileId,
                    replaceValue:
                      action.doContext.clearRule[index].triggerCondition.condition.spec.predicate
                        .defaultValue,
                    time: action.doContext.clearRule[index].triggerCondition.condition.spec
                      .predicate.defaultValue,
                    timeUnit:
                      action.doContext.clearRule[index].triggerCondition.condition.spec.unit,
                  });
                  if (action.doContext.clearRule[index]?.deviceProfileId != undefined) {
                    selectProductId.value = action.doContext.clearRule[index]?.deviceProfileId;
                  }
                  //fengtao-把设备id回传给子组件
                  item.updateFieldAttributeFunc(selectProductId.value);
                  item.updateFieldDeviceId(deviceList.value, provideOrgid.value, isUpdate.value);
                  //fengtao
                  // 单独设置operationType值 操作符类型 NUMERIC|String|Boolean|DATE_TIME
                  item.operationType =
                    action.doContext.clearRule[
                      index
                    ].triggerCondition.condition.condition[0].valueType;
                }
              );

              const ConditionScreeningForm = await unref(skipUnwrap.actionItemRefs)[
                index
              ].getRefItemConditionScreeningRefs();

              // 循环设置条件筛选值。TODO:此处设置顺序有问题
              action.doContext.clearRule.map((rule, ruleIndex) => {
                // 生成对应条件筛选的数组个数
                unref(skipUnwrap.actionItemRefs)[index].setConditionScreeningList([
                  ...new Array(
                    action.doContext.clearRule[
                      ruleIndex
                    ].triggerCondition.condition.condition.length
                  ).keys(),
                ]);
                nextTick(() => {
                  const richTextList = [];
                  rule.triggerCondition.condition.condition.forEach((item, conditionIndex) => {
                    //TODO-fengtao之前是Number( item.predicate.value.defaultValue)-发现回显是Invalide Time
                    const formItem = {
                      operation: item.predicate.operation,
                      value:
                        item.valueType === 'DATE_TIME'
                          ? formatToDateTime(
                              Number(item.predicate.value.defaultValue),
                              'YYYY-MM-DD HH:mm:ss'
                            )
                          : String(item.predicate.value.defaultValue),
                      ignoreCase:
                        item.valueType === 'STRING' ? item.predicate.ignoreCase : undefined,
                    };
                    //TODO-fengtao之前是Number( item.predicate.value.defaultValue)-发现回显是Invalide Time
                    richTextList.push({
                      // 查询中文操作符
                      operation: findOperation(item.valueType, item.predicate.operation).label,
                      value:
                        item.valueType === 'DATE_TIME'
                          ? formatToDateTime(
                              item.predicate.value.defaultValue,
                              'YYYY-MM-DD HH:mm:ss'
                            )
                          : String(item.predicate.value.defaultValue),
                      attribute: item?.key?.key,
                    });
                    //TODO-fengtao之前是Number( item.predicate.value.defaultValue)-发现回显是Invalide Time
                    ConditionScreeningForm[ruleIndex].value[conditionIndex].setFieldsValue(
                      formItem
                    );
                  });
                  unref(skipUnwrap.actionItemRefs)[index].setRichText(richTextList, ruleIndex);
                });
              });
            });
          }
          nextTick(() => {
            setEditFields(skipUnwrap.actionItemRefs, editEntryIdData);
          });
        });
      });
    }
    if (unref(isUpdate) === 3) isView.value = false;
    setDrawerProps({
      showFooter: unref(isView),
      loading: false,
    });
  });

  // 设置设备的options
  const setEditFields = (linkAge, deviceList) => {
    unref(linkAge).map((item) => {
      // TODO-fengtao
      item.updateFieldDeviceId(deviceList, orgId, isUpdate);
      // TODO-fengtao
    });
  };
  // 设置告警配置options
  const setEditAlarmConfig = (linkAge, alarmConfigList) => {
    unref(linkAge).map((item) => {
      item.updateEditFieldAlarmConfig(alarmConfigList);
    });
  };
  // 监听组织变化更新设备列表
  const deviceList = ref([]);
  const getMasterDeviceList = ref([]);
  const orgId = ref('');
  const alarmConfigList = ref([]);
  //FT add 2022-10-27
  const addOrgId = ref('');
  //FT add 2022-10-27
  watch(organizationIdRef, async (newValue: string) => {
    if (!newValue) return;
    //FT add 2022-10-27
    addOrgId.value = newValue;
    //FT add 2022-10-27
    const { items = [] } = await screenLinkPageByDeptIdGetDevice({ organizationId: newValue });
    //TODO fengtao
    // getMasterDeviceList.value = await byOrganizationIdGetMasterDevice(newValue);
    //TODO fengtao
    deviceList.value = (items || []).map((item) => ({
      ...item,
      label: item.name,
      value: item.tbDeviceId,
    }));
    //TODO fengtao
    orgId.value = newValue;
    //TODO fengtao
    setFields(skipUnwrap.triggerItemRefs, true);
    setFields(skipUnwrap.conditionItemRefs, true);
    setFields(skipUnwrap.actionItemRefs, true);
    const data = await getOrganizationAlarmConfig({ organizationId: newValue });
    alarmConfigList.value = data.map((item) => ({ label: item.name, value: item.id }));
    setEditAlarmConfig(skipUnwrap.actionItemRefs, alarmConfigList);
    // setFields(skipUnwrap.actionItemRefs, true);
    // console.log(unref(organizationIdRef));
    // setAlarmConfig(skipUnwrap.actionItemRefs, true);
  });
  //FT add 2022-10-27
  const handleDynamicChangeAlarmConfig = async () => {
    const data = await getOrganizationAlarmConfig({
      organizationId: isUpdate.value ? provideOrgid.value : addOrgId.value,
    });
    const res = data.map((item) => ({ label: item.name, value: item.id }));
    isUpdate.value ? (editAlarmConfigData.value = res) : (alarmConfigList.value = res);
    unref(skipUnwrap.actionItemRefs)?.map((item: any) => {
      if (isUpdate.value) {
        item.updateEditFieldAlarmConfig(editAlarmConfigData);
      } else {
        item.updateFieldAlarmConfig(alarmConfigList);
      }
    });
  };
  //FT add 2022-10-27
  // 根据上面组织变化动态改变触发器，执行条件,执行动作的设备值
  function setFields(linkAge, isOrganizationChange = false) {
    unref(linkAge).map((item) => {
      isOrganizationChange && item.resetFieldsValueFunc();
      //TODO fengtao
      item.updateFieldDeviceId(deviceList, orgId, isUpdate);
      if (isUpdate.value) {
        item.updateEditFieldAlarmConfig(editAlarmConfigData);
      } else {
        item.updateFieldAlarmConfig(alarmConfigList);
      }
      //TODO fengtao
    });
  }
  // function setAlarmConfig(linkAge, isOrganizationChange = false) {
  //   unref(linkAge).map((item) => {
  //     isOrganizationChange && item.resetFieldsValueFunc();
  //     item.updateFieldAlarmConfig(alarmConfigList);
  //   });
  // }
  // 添加触发器
  const addTrigger = () => {
    unref(triggerData).push(Date.now());
    nextTick(() => {
      setFields(skipUnwrap.triggerItemRefs);
    });
  };
  // 添加执行条件
  const addCondition = () => {
    unref(conditionData).push(Date.now());
    nextTick(() => {
      setFields(skipUnwrap.conditionItemRefs);
    });
  };
  // 添加执行动作
  const addAction = () => {
    unref(actionData).push(Date.now());
    nextTick(() => {
      setFields(skipUnwrap.actionItemRefs);
    });
  };

  /**
   * 获取触发器、执行条件、执行动作表单值--多个
   */
  const getFormValueFunc = () => {
    getTriggerFormValue.value = unref(skipUnwrap.triggerItemRefs)?.map((item) =>
      genTriggerOrConditionData(item.getFieldsValueFunc())
    );
    getConditionFormValue.value = unref(skipUnwrap.conditionItemRefs)?.map((item) =>
      genTriggerOrConditionData(item.getFieldsValueFunc())
    );
    getActionFormValue.value = unref(skipUnwrap.actionItemRefs)?.map((item) =>
      genActionData(item.getFieldsValueFunc())
    );
  };
  const handleSubmit = async () => {
    let basicFormValue = await validate();
    if (!basicFormValue) return;
    for (const item of unref(skipUnwrap.actionItemRefs)) {
      const valid = await item.validateForm();
      if (!valid) return;
    }
    try {
      setDrawerProps({ confirmLoading: true });
      getFormValueFunc();
      //新增的代码2022-11-22
      if (unref(getTriggerFormValue).length === 0 && unref(getConditionFormValue).length === 0) {
        createMessage.error('请添加触发器或者执行条件');
        throw '请添加触发器或者执行条件';
      }

      // return;
      //新增的代码2022-11-22
      const postAddOrEditData = {
        ...basicFormValue,
        triggers: !unref(getTriggerFormValue).length ? null : unref(getTriggerFormValue),
        doConditions: !unref(getConditionFormValue).length ? null : unref(getConditionFormValue),
        doActions: unref(getActionFormValue).flat(),
        id: unref(id),
        tenantId: unref(tenantId),
      };
      //FT change
      let mustTriggerCondition = false;
      let mustCondition = false;
      if (postAddOrEditData?.triggers !== null && postAddOrEditData?.triggers.length > 0) {
        postAddOrEditData?.triggers.some((s) => {
          if (s.triggerCondition?.condition?.condition == undefined) {
            mustTriggerCondition = true;
          }
        });
      } else {
        mustTriggerCondition = false;
      }
      if (postAddOrEditData?.doConditions !== null && postAddOrEditData?.doConditions.length > 0) {
        postAddOrEditData?.doConditions.some((s) => {
          if (s.triggerCondition?.condition?.condition == undefined) {
            mustCondition = true;
          }
        });
      } else {
        mustCondition = false;
      }
      if (mustTriggerCondition) return;
      if (mustCondition) return;
      //FT change
      await screenLinkPageAddApi(postAddOrEditData, unref(isUpdate));
      createMessage.success(`${unref(isUpdate) ? '编辑' : '新增'}成功`);
      closeDrawer();
      handleClose();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  };
  // 删除
  const deleteTriggerOrCondition = ({ index, title }) => {
    if (title === '触发器') {
      unref(triggerData).splice(index, 1);
    } else if (title === '执行条件') {
      unref(conditionData).splice(index, 1);
    }
  };
  const deleteAction = (actionIndex) => {
    unref(actionData).splice(actionIndex, 1);
    unref(arr).splice(actionIndex, 1);
  };
  const arr = ref([]);
  const getActionFormArr = () => {
    arr.value = unref(skipUnwrap.actionItemRefs).map((item) => item.getFieldsValue());
  };
  const handleClose = () => {
    id.value = undefined;
    tenantId.value = undefined;
    organizationIdRef.value = undefined;
    isView.value = true;
    getTriggerFormValue.value = [];
    getConditionFormValue.value = [];
    getActionFormValue.value = [];
    triggerData.value = [];
    conditionData.value = [];
    actionData.value = [];
    unref(skipUnwrap.triggerItemRefs).map((item) => {
      item.resetFieldsValueFunc();
    });
    unref(skipUnwrap.conditionItemRefs).map((item) => {
      item.resetFieldsValueFunc();
    });
    unref(skipUnwrap.actionItemRefs).map((item) => {
      item.resetFieldsValueFunc();
    });
    window.localStorage.removeItem('isViewDisabledBtn');
    // window.localStorage.setItem('isViewDisabledBtn', 'no')
  };
</script>

<style lang="less" scoped>
  //TODO-fengtao
  ///移除选择框默认样式（24px）否则超出默认宽度会造成页面样式错乱
  :deep(.ant-select-selector) {
    padding-right: 0 !important;
  }

  :deep(.ant-select-selection-overflow) {
    max-width: 10vw !important;
  }

  //TODO-fengtao
</style>
