<script lang="ts" setup>
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import {
    formSchema,
    getHistorySearchParams,
    SchemaFiled,
  } from '../../../board/detail/config/historyTrend.config';
  import { HistoryModalOkEmitParams, HistoryModalParams } from './type';
  import { DataSource } from '/@/api/dataBoard/model';
  import { ref } from 'vue';
  import { getAllDeviceByOrg } from '/@/api/dataBoard';
  import { getDeviceHistoryInfo } from '/@/api/alarm/position';

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

  const [registerForm, { updateSchema, setFieldsValue, validate, getFieldsValue }] = useForm({
    schemas: formSchema(),
    showActionButtonGroup: false,
    fieldMapToTime: [
      [SchemaFiled.DATE_RANGE, [SchemaFiled.START_TS, SchemaFiled.END_TS], 'YYYY-MM-DD HH:mm:ss'],
    ],
  });

  const [registerModal, { closeModal }] = useModalInner(async (params: HistoryModalParams) => {
    try {
      const { dataSource = [] } = params;
      const deviceRecord = dataSource?.at(0) || ({} as DataSource);
      if (!deviceRecord.organizationId) return;
      const deviceList = await getAllDeviceByOrg(
        deviceRecord.organizationId,
        deviceRecord.deviceProfileId
      );
      const options = deviceList
        .filter((item) => item.tbDeviceId === deviceRecord.deviceId)
        .map((item) => ({ ...item, label: item.name, value: item.tbDeviceId }));
      const attKey = dataSource.map((item) => ({
        ...item,
        label: item.attribute,
        value: item.attribute,
      }));
      updateSchema([
        {
          field: SchemaFiled.DEVICE_ID,
          componentProps: {
            options,
          },
        },
        {
          field: SchemaFiled.KEYS,
          component: 'Select',
          defaultValue: attKey.map((item) => item.value),
          componentProps: {
            options: attKey,
            mode: 'multiple',
            disabled: true,
          },
        },
      ]);

      setFieldsValue({
        [SchemaFiled.DEVICE_ID]: deviceRecord.deviceId,
        [SchemaFiled.KEYS]: attKey.map((item) => item.value),
      });
    } catch (error) {
      throw error;
    }
  });

  const loading = ref(false);
  const handleOk = async () => {
    try {
      await validate();
      let value = getFieldsValue();

      value = getHistorySearchParams(value);

      loading.value = true;

      const res = await getDeviceHistoryInfo({
        ...value,
        [SchemaFiled.KEYS]: value[SchemaFiled.KEYS].join(','),
      });

      let timespanList = Object.keys(res).reduce((prev, next) => {
        const ts = res[next].map((item) => item.ts);
        return [...prev, ...ts];
      }, [] as number[]);
      timespanList = [...new Set(timespanList)];

      const track: Record<'lng' | 'lat', number>[] = [];
      const keys = Object.keys(res);

      for (const ts of timespanList) {
        const list: { ts: number; value: number }[] = [];
        for (const key of keys) {
          const record = res[key].find((item) => ts === item.ts);
          list.push(record as any);
        }
        if (list.every(Boolean)) {
          const lng = list.at(0)?.value;
          const lat = list.at(1)?.value;
          if (lng && lat) track.push({ lng, lat });
        }
      }
      emit('ok', { track, value } as HistoryModalOkEmitParams);
      closeModal();
    } catch (error) {
      throw error;
    } finally {
      loading.value = false;
    }
  };
</script>

<template>
  <BasicModal
    title="历史轨迹"
    @register="registerModal"
    @ok="handleOk"
    :ok-button-props="{ loading }"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
