<template>
  <BasicDrawer
    destroyOnClose
    v-bind="$attrs"
    showFooter
    width="35%"
    :maskClosable="true"
    :title="businessText"
    @register="registerDrawer"
    @ok="handleSubmit"
    @close="handleClose"
    wrapClassName="report-drawer"
  >
    <BasicForm @register="registerForm">
      <!-- 设备选择 -->
      <template #devices="{ model }">
        <span class="hidden">{{ handleChangeOrg(model['organizationId']) }}</span>
        <SelectDevice
          ref="selectDeviceRef"
          :selectOptions="selectOptions"
          v-model:disabled="deviceDisabled"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, reactive, Ref, nextTick, watch } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from '../config';
  import { SchemaFiled, BusinessReportConfigTextEnum, BusinessExecutewayEnum } from '../enum';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    createOrEditReportManage,
    putReportConfigManage,
    reportEditDetailPage,
  } from '/@/api/report/reportManager';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { TSelectOption } from '../type';
  import { SelectDevice } from './index';
  import { useHooks } from '../hooks/index.hooks';
  import { useThrottleFn } from '@vueuse/shared';

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

  const selectDeviceRef = ref<InstanceType<typeof SelectDevice>>();

  const { createMessage } = useMessage();

  const {
    getDeviceList,
    getQueryCondition,
    removeFields,
    setDefaultTime,
    setQueryCondition,
    setAggByDateType,
    disableCustomWeekly,
    setPropsForModal,
    validateSelectDevice,
  } = useHooks();

  const selectOptions: Ref<TSelectOption[]> = ref([]);

  const orgId = ref('');

  const handleChangeOrg = (e) => {
    orgId.value = e;
    //放在这里的话，会造成发出很多请求，原因不是很清楚
    // getDeviceListByOrg(orgId.value);
  };

  const getDeviceListByOrg = async (organizationId) => {
    selectOptions.value = await getDeviceList(organizationId);
  };

  watch(
    () => orgId.value,
    (newValue: string) => {
      if (newValue) {
        //获取设备
        selectDeviceRef.value?.resetValue();
        getDeviceListByOrg(newValue);
      }
    },
    {
      immediate: true,
    }
  );

  const [registerForm, { validate, resetFields, setFieldsValue, updateSchema, setProps }] = useForm(
    {
      labelWidth: 120,
      schemas: formSchema,
      showActionButtonGroup: false,
      fieldMapToTime: [[SchemaFiled.DATE_RANGE, [SchemaFiled.START_TS, SchemaFiled.END_TS]]],
    }
  );

  const businessText = ref('');

  const restData = reactive({
    data: {},
  });

  const deviceDisabled = ref<boolean>(false);

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    try {
      await nextTick();
      handleClose();
      businessText.value = data.text;
      if (businessText.value == BusinessReportConfigTextEnum.BUSINESS_VIEW_TEXT) {
        deviceDisabled.value = true;
        setProps({ disabled: true });
        updateSchema({
          field: 'organizationId',
          componentProps: { apiTreeSelectProps: { disabled: true } },
        });
      } else {
        deviceDisabled.value = false;
        updateSchema({
          field: 'organizationId',
          componentProps: { apiTreeSelectProps: { disabled: false } },
        });
      }
      setFieldsValue(setDefaultTime());
      updateSchema(disableCustomWeekly(BusinessExecutewayEnum.BUSINESS_EXECUTEWAY_IMMEDIATE));
      setDrawerProps(setPropsForModal(businessText.value));
      if (businessText.value === BusinessReportConfigTextEnum.BUSINESS_ADD_TEXT) return;
      const rest = await reportEditDetailPage(data.record?.id);
      restData.data = rest['data'] ?? {};
      const {
        organizationId,
        executeAttributes,
        queryCondition,
        dataType,
        executeWay,
        cycle,
        executeContent,
      } = restData.data as any;
      await setFieldsValue({
        ...restData.data,
        ...setQueryCondition(queryCondition, cycle, executeContent),
      });
      if (organizationId) {
        await getDeviceListByOrg(organizationId);
        selectDeviceRef.value?.setValue(executeAttributes);
      }
      await updateSchema(setAggByDateType(dataType));
      await updateSchema(disableCustomWeekly(executeWay));
    } finally {
      setDrawerProps({ loading: false });
    }
  });

  const handleClose = () => resetValue();

  const useThrottle = useThrottleFn(() => {
    getValue();
  }, 2000);

  const handleSubmit = () => {
    useThrottle();
  };

  const getValue = async () => {
    try {
      setDrawerProps({ confirmLoading: true });
      const values = await validate();
      if (!values) return;
      const [queryCondition, cycle, executeContent] = getQueryCondition(values);
      const executeAttributes = selectDeviceRef.value?.getSelectAttributes();
      validateSelectDevice(executeAttributes);
      const data = {
        ...values,
        executeAttributes,
        queryCondition,
        cycle,
        executeContent,
      };
      removeFields.forEach((item) => {
        Reflect.deleteProperty(data, item);
      });
      businessText.value === BusinessReportConfigTextEnum.BUSINESS_ADD_TEXT
        ? await createOrEditReportManage(data)
        : putReportConfigManage({ ...restData.data, ...data });
      emits('success');
      createMessage.success(`${businessText.value}成功`);
      closeDrawer();
      handleClose();
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  };

  //重置表单
  const resetValue = () => {
    resetFields();
    selectOptions.value = [];
    selectDeviceRef.value?.resetValue();
  };
</script>

<style lang="less">
  .report-drawer {
    .ant-form-item-control-input-content {
      > div {
        > div {
          @apply w-full;
        }
      }
    }
  }
</style>
