<template>
  <div>
    <CollapseContainer style="background-color: #f2f2f2" :title="`${title} ${index + 1}`">
      <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, title })"
            />
          </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 { Card, Input, Select, Tooltip } from 'ant-design-vue';
  import { cloneDeep } from 'lodash-es';
  import { nextTick, provide, ref } from 'vue';
  import { TOption, trigger_condition_schema } from '../config/config.data';
  import { options, scheduleOptions, timeUnitOptions } from '../config/formatData';
  import useCommonFun from '../hooks/useCommonFun';
  import AlarmSchedule from './AlarmSchedule.vue';
  import ConditionScreening from './ConditionScreening.vue';
  import { getAttribute } from '/@/api/ruleengine/ruleengineApi';
  import { CollapseContainer } from '/@/components/Container/index';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Icon } from '/@/components/Icon';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { useByProductGetAttribute } = useCommonFun();
  defineProps({
    title: {
      type: String,
      required: true,
    },
    index: {
      type: Number,
      required: true,
    },
    provideOrgid: {
      type: String,
      default: '',
    },
  });
  const emit = defineEmits(['delete']);
  const { createMessage } = useMessage();

  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>>();

  //ft-add
  const resetConditionForm = () => {
    conditionScreeningRef?.value?.resetConditionScreenForm();
  };
  //ft-add

  const getFieldsValueFunc = () => {
    const predicate = conditionScreeningRef?.value?.refItem?.conditionScreeningRefs?.value?.map(
      (item) => item.getFieldsValue()
    );
    //TODO-fengtao-设备、属性、条件筛选验证
    const validate = getFieldsValue();
    if (validate.deviceProfileId === undefined) {
      createMessage.error('请选择产品');
      throw '请选择产品';
    }
    if (validate.triggerType == undefined) return createMessage.error('请选择设备触发方式');
    if (validate.type1 == undefined) return createMessage.error('请选择属性触发方式');
    if (validate.device == 'PART') {
      if (validate.entityId == undefined) return createMessage.error('请选择设备');
    }
    if (validate.type2 == '' || validate.type2 == null) return createMessage.error('请选择属性');
    if (predicate == undefined) return createMessage.error('请填写条件筛选');
    let predicateIsRequired = false;
    if (predicate) {
      predicate.some((f) => {
        let arr = Object.keys(f);
        if (arr.length == 0) {
          predicateIsRequired = true;
        }
        if (f.operation == undefined) {
          predicateIsRequired = true;
        }
        if (f.value == undefined) {
          predicateIsRequired = true;
        }
      });
    }
    if (predicateIsRequired) return createMessage.error('请填写条件筛选');
    //TODO-fengtao-设备、属性、条件筛选验证
    return { ...getFieldsValue(), predicate, schedule: alarmScheduleRef.value.scheduleData };
  };

  //TODO-fengtao
  const updateFieldDeviceId = (_deviceList: any[], _, _isUpdate) => {
    // console.log(deviceList);
    // console.log(isUpdate);
  };
  //TODO-fengtao
  const resetFieldsValueFunc = () => {
    resetConditionForm();
    resetFields();
  };
  // 回显数据函数
  const setFieldsFormValueFun = (fieldsValue) => {
    setFieldsValue(fieldsValue);
  };
  //TODO-fengtao
  const updateFieldAttributeFunc = async (e) => {
    const res = await getAttribute(e);
    const options = ref<TOption[]>([]);
    useByProductGetAttribute(res, updateSchema, options);
  };
  //TODO-fengtao
  const handleDelete = (params: { index: number; title: string }) => {
    emit('delete', params);
  };
  const operationType = ref<string>('');
  provide('operationType', operationType);

  // 子组件获取父组件的值
  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 [registerModal, { openModal }] = useModal();
  const currentIndex = ref(0);
  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);
  //FT add 2022-10-27
  const updateFieldAlarmConfig = () => {
    //什么也不做
    // console.log(alarmConfigList);
  };
  //FT add 2022-10-27
  const updateEditFieldAlarmConfig = () => {
    //什么也不做
    // console.log(alarmConfigList);
  };

  defineExpose({
    getFieldsValueFunc,
    updateFieldDeviceId,
    resetFieldsValueFunc,
    setFieldsFormValueFun,
    childGetFieldsValue,
    operationType,
    getRefItemConditionScreeningRefs,
    setConditionScreeningList,
    setRichText,
    currentIndex,
    scheduleData,
    isUpdate,
    alarmScheduleRef,
    updateFieldAttributeFunc,
    updateFieldAlarmConfig,
    updateEditFieldAlarmConfig,
  });
</script>

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

<style>
  .active {
    color: #377dff;
  }
</style>
