import type { NdmDeviceAlarmLogResultVO, NdmDeviceResultVO, NdmNvrResultVO } from '@/apis';
import { ALARM_TYPES, DEVICE_TYPE_LITERALS, DEVICE_TYPE_NAMES, FAULT_LEVELS, tryGetDeviceType } from '@/enums';
import dayjs from 'dayjs';
import { NButton, NPopover, NScrollbar, NTag, type TagProps } from 'naive-ui';
import { h } from 'vue';

export const renderAlarmDateCell = (rowData: NdmDeviceAlarmLogResultVO) => {
  return dayjs(Number(rowData.alarmDate ?? 0)).format('YYYY-MM-DD HH:mm:ss');
};

export const renderDeviceTypeCell = (rowData: NdmDeviceAlarmLogResultVO) => {
  const deviceTypeVal = tryGetDeviceType(rowData.deviceType);
  if (!deviceTypeVal) return '-';
  return DEVICE_TYPE_NAMES[deviceTypeVal];
};

export const renderAlarmTypeCell = (rowData: NdmDeviceAlarmLogResultVO) => {
  const { alarmType } = rowData;
  if (!alarmType) {
    return '';
  }
  return h(NTag, { type: 'default' }, { default: () => ALARM_TYPES[alarmType] });
};

export const renderFaultLevelCell = (rowData: NdmDeviceAlarmLogResultVO) => {
  const { faultLevel } = rowData;
  if (!faultLevel) {
    return '';
  }
  let type: TagProps['type'] = 'default';
  if (faultLevel === '1') {
    type = 'error';
  } else if (faultLevel === '2') {
    type = 'warning';
  } else if (faultLevel === '3') {
    type = 'info';
  }
  return h(NTag, { type }, { default: () => FAULT_LEVELS[faultLevel] });
};

export const renderFaultDescriptionCell = (rowData: NdmDeviceAlarmLogResultVO, ndmDevice: NdmDeviceResultVO) => {
  const isNvrCluster = (ndmDevice: NdmDeviceResultVO) => {
    const deviceType = tryGetDeviceType(ndmDevice.deviceType);
    if (!deviceType) return false;
    const isNvr = deviceType === DEVICE_TYPE_LITERALS.ndmNvr;
    if (!isNvr) return false;
    const maybeNvrCluster = ndmDevice as NdmNvrResultVO;
    return !!maybeNvrCluster.clusterList?.trim() && maybeNvrCluster.clusterList !== maybeNvrCluster.ipAddress;
  };
  if (!isNvrCluster(ndmDevice)) {
    return rowData.faultDescription;
  }
  return h(
    NPopover,
    {
      trigger: 'click',
    },
    {
      trigger: () => {
        return h(
          NButton,
          {
            text: true,
            type: 'info',
          },
          {
            default: () => '查看',
          },
        );
      },
      default: () => {
        return h(
          NScrollbar,
          {
            style: {
              width: '800px',
              'max-height': '400px',
            },
          },
          {
            default: () => {
              return h('pre', {}, { default: () => rowData.faultDescription?.split('; ').join('\n') ?? '' });
            },
          },
        );
      },
    },
  );
};
