import { detailDeviceAlarmSnapLogApi, type NdmDeviceAlarmLogResultVO } from '@/apis';
import { tryGetDeviceType, DEVICE_TYPE_LITERALS } from '@/enums';
import { parseErrorFeedback } from '@/utils';
import { useMutation } from '@tanstack/vue-query';
import { NButton, NImage, type DataTableColumn, type DataTableRowData } from 'naive-ui';
import { h, ref, watch, type Ref } from 'vue';

export const useCameraSnapColumn = (tableData: Ref<DataTableRowData[]>) => {
  const { mutateAsync: getSnapByDeviceId } = useMutation({
    mutationFn: async (params: { id: string }) => {
      const { id } = params;
      const snap = await detailDeviceAlarmSnapLogApi(id);
      return snap;
    },
    onError: (error) => {
      console.error(error);
      const errorFeedback = parseErrorFeedback(error);
      window.$message.error(errorFeedback);
    },
  });

  // 控制每一行的查看按钮loading状态
  const loadingMap = ref<Record<string, boolean>>({});
  watch(tableData, () => {
    loadingMap.value = {};
  });

  const cameraSnapColumn: DataTableColumn<NdmDeviceAlarmLogResultVO & { snapUrl?: string }> = {
    title: '告警画面截图',
    key: 'snapUrl',
    align: 'center',
    render: (rowData) => {
      const { id, deviceType: deviceTypeCode, snapUrl } = rowData;
      if (!id) return null;
      const deviceType = tryGetDeviceType(deviceTypeCode);
      if (deviceType !== DEVICE_TYPE_LITERALS.ndmCamera) return null;
      if (!snapUrl) {
        return h(
          NButton,
          {
            type: 'info',
            size: 'small',
            loading: !!loadingMap.value[id],
            onClick: async () => {
              loadingMap.value[id] = true;
              try {
                const snap = await getSnapByDeviceId({ id });
                if (!snap.url) return;
                rowData.snapUrl = snap.url;
              } finally {
                loadingMap.value[id] = false;
              }
            },
          },
          { default: () => '查看' },
        );
      } else {
        return h(NImage, { src: snapUrl, previewDisabled: false, showToolbar: false });
      }
    },
  };

  return {
    cameraSnapColumn,
  };
};
