import { usePermission } from '../permission';
import { deleteCameraIgnoreApi, pageCameraIgnoreApi, saveCameraIgnoreApi, updateDeviceAlarmLogApi, type NdmDeviceAlarmLogResultVO } from '@/apis';
import { DEVICE_TYPE_LITERALS, PERMISSION_TYPE_LITERALS, tryGetDeviceType } from '@/enums';
import { parseErrorFeedback } from '@/utils';
import { useMutation } from '@tanstack/vue-query';
import { NButton, NFlex, NPopconfirm, type DataTableColumn, type DataTableRowData } from 'naive-ui';
import { h, type Ref } from 'vue';

export const useAlarmActionColumn = (tableData: Ref<DataTableRowData[]>) => {
  const { hasPermission } = usePermission();

  const { mutate: confirmAlarm } = useMutation({
    mutationFn: async (params: { id: string | null }) => {
      const { id } = params;
      if (!id) return;
      const alarmLog = tableData.value.find((item) => item.id === id);
      if (alarmLog) {
        alarmLog['alarmConfirm'] = '1';
      }
      await updateDeviceAlarmLogApi({ id, alarmConfirm: '1' });
    },
    onError: (error, variables) => {
      console.error(error);
      const errorFeedback = parseErrorFeedback(error);
      window.$message.error(errorFeedback);
      const { id } = variables;
      if (id) {
        const alarmLog = tableData.value.find((item) => item.id === id);
        if (alarmLog) {
          alarmLog['alarmConfirm'] = '2';
        }
      }
    },
  });

  const { mutate: ignoreCamera } = useMutation({
    mutationFn: async (params: { id: string | null }) => {
      const { id } = params;
      if (!id) return;
      const alarmLog = tableData.value.find((item) => item.id === id);
      if (!alarmLog) return;
      const { records } = await pageCameraIgnoreApi({
        model: { deviceId: alarmLog.deviceId },
        extra: {},
        current: 1,
        size: 10,
        sort: 'id',
        order: 'descending',
      });
      const ignoredCamera = records.at(0);
      if (ignoredCamera) {
        window.$message.info('设备已被忽略');
        return;
      }
      await saveCameraIgnoreApi({ deviceId: alarmLog.deviceId });
      window.$message.success('忽略设备成功');
    },
    onError: (error) => {
      console.error(error);
      const errorFeedback = parseErrorFeedback(error);
      window.$message.error(errorFeedback);
    },
  });

  // const { mutate: noticeCamera } = useMutation({
  //   mutationFn: async (params: { id: string | null }) => {
  //     const { id } = params;
  //     if (!id) return;
  //     const alarmLog = tableData.value.find((item) => item.id === id);
  //     if (!alarmLog) return;
  //     const { records } = await pageCameraIgnoreApi({
  //       model: { deviceId: alarmLog.deviceId },
  //       extra: {},
  //       current: 1,
  //       size: 10,
  //       sort: 'id',
  //       order: 'descending',
  //     });
  //     if (records.length === 0) {
  //       window.$message.info('设备未被忽略');
  //       return;
  //     }
  //     await deleteCameraIgnoreApi([...records.map((record) => record.id ?? '')]);
  //     window.$message.success('取消忽略设备成功');
  //   },
  //   onError: (error) => {
  //     console.error(error);
  //     const errorFeedback = parseErrorFeedback(error);
  //     window.$message.error(errorFeedback);
  //   },
  // });

  const alarmActionColumn: DataTableColumn<NdmDeviceAlarmLogResultVO> = {
    title: '操作',
    key: 'action',
    width: 120,
    align: 'center',
    render: (rowData) => {
      const { id } = rowData;
      return h(
        NFlex,
        {
          size: 'small',
          justify: 'center',
          align: 'center',
        },
        {
          default: () => [
            rowData.alarmConfirm === '1'
              ? h(NButton, { disabled: true, secondary: true, type: 'info', size: 'tiny' }, { default: () => '确认' })
              : h(
                  NPopconfirm,
                  {
                    onPositiveClick: () => confirmAlarm({ id }),
                  },
                  {
                    trigger: () => h(NButton, { secondary: true, type: 'info', size: 'tiny' }, { default: () => '确认' }),
                    default: () => '确认告警？',
                  },
                ),
            tryGetDeviceType(rowData.deviceType) === DEVICE_TYPE_LITERALS.ndmCamera &&
              rowData.stationCode &&
              hasPermission(rowData.stationCode, PERMISSION_TYPE_LITERALS.OPERATION) && [
                h(
                  NPopconfirm,
                  {
                    onPositiveClick: () => ignoreCamera({ id }),
                  },
                  {
                    trigger: () => h(NButton, { tertiary: true, type: 'info', size: 'tiny' }, { default: () => '忽略' }),
                    default: () => '忽略设备？',
                  },
                ),
                // h(
                //   NPopconfirm,
                //   {
                //     onPositiveClick: () => noticeCamera({ id }),
                //   },
                //   {
                //     trigger: () => h(NButton, { text: true, type: 'info', size: 'small' }, { icon: () => h(EyeOutlined) }),
                //     default: () => '取消忽略设备？',
                //   },
                // ),
              ],
          ],
        },
      );
    },
  };

  return {
    alarmActionColumn,
  };
};
