<template>
  <div>
    <CollapseContainer style="background-color: #f2f2f2" title="清除告警" :canExpan="false">
      <template #action>
        <div class="flex">
          <div class="flex">
            <span class="mr-2">启用规则:</span>
            <template v-for="(item, scheduleIndex) in scheduleOptions" :key="item.label">
              <div
                :class="{ 'ml-4': scheduleIndex >= 1, active: scheduleIndex === currentIndex }"
                class="cursor-pointer"
                @click="handleScheduleChange(item.value)"
                >{{ item.label }}</div
              >
            </template>
          </div>
          <Tooltip title="移除" class="ml-4">
            <Icon
              icon="fluent:delete-off-20-regular"
              size="20"
              class="mr-2 cursor-pointer"
              @click="handleDelete(index)"
              v-if="clearRuleList.length > 1"
            />
          </Tooltip>
        </div>
      </template>
      <BasicForm @register="registerForm">
        <template #operationType="{ model, field }">
          <Select
            :options="options"
            v-model:value="model[field]"
            @change="operationType = model[field]"
            placeholder="请选择比较类型"
            allowClear
          />
        </template>
        <template #time="{ model, field }">
          <Input v-model:value="model[field]" placeholder="请输入持续时间">
            <template #addonAfter>
              <Select
                v-model:value="model[`timeUnit`]"
                :options="timeUnitOptions"
                style="width: 60px"
              />
            </template>
          </Input>
        </template>
      </BasicForm>
      <Card size="small" :bordered="false" style="border: 2px dashed #d9d9d9" v-if="operationType">
        <ConditionScreening
          :childGetFieldsValue="childGetFieldsValue"
          ref="conditionScreeningRef"
        />
      </Card>
    </CollapseContainer>
    <AlarmSchedule ref="alarmScheduleRef" @register="registerModal" @cancel="handleCancel" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, provide, nextTick } from 'vue';
  import { CollapseContainer } from '/@/components/Container/index';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Card, Select, Input, Tooltip } from 'ant-design-vue';
  import { trigger_condition_schema, TOption } from '../config/config.data';
  import { getAttribute } from '/@/api/ruleengine/ruleengineApi';
  import ConditionScreening from './ConditionScreening.vue';
  import { scheduleOptions, timeUnitOptions, options } from '../config/formatData';
  import { Icon } from '/@/components/Icon';
  import AlarmSchedule from './AlarmSchedule.vue';
  import { useModal } from '/@/components/Modal';
  import { cloneDeep } from 'lodash-es';
  import useCommonFun from '../hooks/useCommonFun';

  const { useByProductGetAttribute } = useCommonFun();
  defineProps({
    index: {
      type: Number,
      required: true,
    },
    clearRuleList: {
      type: Array,
      default: () => [],
    },
  });
  const emit = defineEmits(['delete']);
  const isUpdate = ref(false);
  const conditionScreeningRef = ref();
  const [registerForm, { resetFields, getFieldsValue, updateSchema, setFieldsValue }] = useForm({
    //TODO-wenwei-修复
    schemas: cloneDeep(trigger_condition_schema),
    //TODO-wenwei-修复
    showActionButtonGroup: false,
  });

  const alarmScheduleRef = ref<InstanceType<typeof AlarmSchedule>>();
  const getFieldsValueFunc = () => {
    const predicate = conditionScreeningRef?.value?.refItem?.conditionScreeningRefs?.value?.map(
      (item) => item.getFieldsValue()
    );
    return { ...getFieldsValue(), predicate, schedule: alarmScheduleRef.value.scheduleData };
  };

  const updateFieldDeviceId = () => {
    // console.log(deviceList);
    // console.log(isUpdate);
  };

  const resetFieldsValueFunc = () => resetFields();
  // 回显数据函数
  const setFieldsFormValueFun = (fieldsValue) => {
    setFieldsValue(fieldsValue);
  };
  const updateFieldAttributeFunc = async (e) => {
    const res = await getAttribute(e);
    const options = ref<TOption[]>([]);
    useByProductGetAttribute(res, updateSchema, options);
  };
  //TODO-fengtao
  const schedule = ref('ANY_TIME');
  const operationType = ref<string>('');
  provide('operationType', operationType);

  const handleDelete = (index: number) => {
    emit('delete', index);
  };

  // 子组件获取父组件的值
  const childGetFieldsValue = () => getFieldsValue();

  // 获取conditionScreeningForm的组件
  const getRefItemConditionScreeningRefs = async () => {
    await nextTick();
    return conditionScreeningRef.value.refItem.conditionScreeningRefs;
  };

  const setConditionScreeningList = (list) => {
    conditionScreeningRef.value.conditionScreeningList = list;
  };
  const setRichText = (list) => {
    conditionScreeningRef.value.otherAttribute = list;
  };

  const currentIndex = ref(0);
  const [registerModal, { openModal }] = useModal();
  const handleScheduleChange = (value) => {
    const index = scheduleOptions.findIndex((item) => item.value === value);
    // 报警日程弹窗
    if (index !== 0) {
      openModal(true, {
        isUpdate: isUpdate.value,
        value,
        currentIndex: currentIndex.value,
        scheduleData,
      });
    } else {
      alarmScheduleRef.value.scheduleData = {
        type: value,
      };
    }
    currentIndex.value = index;
  };
  const handleCancel = (index) => {
    currentIndex.value = index;
  };
  const scheduleData = ref(null);
  defineExpose({
    getFieldsValue,
    updateFieldDeviceId,
    resetFieldsValueFunc,
    setFieldsFormValueFun,
    childGetFieldsValue,
    conditionScreeningRef,
    schedule,
    operationType,
    getFieldsValueFunc,
    getRefItemConditionScreeningRefs,
    setConditionScreeningList,
    setRichText,
    currentIndex,
    scheduleData,
    isUpdate,
    alarmScheduleRef,
    updateFieldAttributeFunc,
  });
</script>
<style>
  .active {
    color: #377dff;
  }
</style>
