<script lang="ts">
const NDM_TYPES: Record<string, DeviceType> = {
  '01': DEVICE_TYPE_LITERALS.ndmAlarmHost,
  // '02': '报警源',
  '03': DEVICE_TYPE_LITERALS.ndmSecurityBox,
  '04': DEVICE_TYPE_LITERALS.ndmSwitch,
  '05': DEVICE_TYPE_LITERALS.ndmNvr,
  '06': DEVICE_TYPE_LITERALS.ndmCamera,
  '07': DEVICE_TYPE_LITERALS.ndmDecoder,
  '08': DEVICE_TYPE_LITERALS.ndmKeyboard,
  '09': DEVICE_TYPE_LITERALS.ndmMediaServer,
  // '10': '显示器',
  '11': DEVICE_TYPE_LITERALS.ndmVideoServer,
};
</script>

<script setup lang="ts">
import { deleteCameraIgnoreApi, pageCameraIgnoreApi, type NdmCameraIgnore, type NdmCameraIgnoreResultVO, type PageQueryExtra, type Station } from '@/apis';
import { usePermission } from '@/composables';
import { DEVICE_TYPE_LITERALS, DEVICE_TYPE_NAMES, PERMISSION_TYPE_LITERALS, type DeviceType } from '@/enums';
import { useDeviceStore, usePermissionStore } from '@/stores';
import { useMutation } from '@tanstack/vue-query';
import { isCancel } from 'axios';
import {
  NButton,
  NDataTable,
  NDatePicker,
  NFlex,
  NForm,
  NFormItemGi,
  NGrid,
  NGridItem,
  NPopconfirm,
  NSelect,
  type DataTableColumns,
  type DataTableRowData,
  type PaginationProps,
  type SelectOption,
} from 'naive-ui';
import { storeToRefs } from 'pinia';
import { computed, h, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';

interface SearchFields extends PageQueryExtra<NdmCameraIgnore> {
  createdTime?: [string, string];
  updatedTime?: [string, string];
  stationCode?: Station['code'];
  // deviceId_like?: string;
}

const permissionStore = usePermissionStore();
const { permissions } = storeToRefs(permissionStore);

const { hasPermission } = usePermission();

const stations = computed(() => permissionStore.stations.VIEW ?? []);

const deviceStore = useDeviceStore();
const { lineDevices } = storeToRefs(deviceStore);

const stationSelectOptions = computed<SelectOption[]>(() => {
  return stations.value.map((station) => ({
    label: station.name,
    value: station.code,
  }));
});
// const deviceTypeSelectOptions = computed<SelectOption[]>(() => {
//   return Object.values(DEVICE_TYPE_LITERALS).map<SelectOption>((deviceType) => ({
//     label: DEVICE_TYPE_NAMES[deviceType],
//     value: deviceType,
//   }));
// });

// 权限变化时，需要刷新表格数据
watch(permissions, (newPermissions, oldPermissions) => {
  const oldPermissionsJson = JSON.stringify(oldPermissions);
  const newPermissionsJson = JSON.stringify(newPermissions);
  if (oldPermissionsJson === newPermissionsJson) return;
  onClickReset();
});

const searchFields = ref<SearchFields>({});
const resetSearchFields = () => {
  searchFields.value = {};
};
const getExtraFields = (): PageQueryExtra<NdmCameraIgnore> => {
  const [createdTime_precisest, createdTime_preciseed] = searchFields.value.createdTime ?? [];
  const stationCode = searchFields.value.stationCode;

  return {
    createdTime_precisest,
    createdTime_preciseed,
    deviceId_like: stationCode?.slice(0, 4),
  };
};

const searchFieldsChanged = ref(false);
watch(searchFields, () => {
  searchFieldsChanged.value = true;
});

const tableColumns = computed<DataTableColumns<NdmCameraIgnoreResultVO>>(() => [
  { title: '忽略时间', key: 'createdTime', align: 'center' },
  // { title: '更新时间', key: 'updatedTime' },
  {
    title: '车站',
    key: 'stationCode',
    align: 'center',
    render: (rowData) => {
      const stationCode = rowData.deviceId?.slice(0, 4);
      if (!stationCode) return '';
      const station = stations.value.find((station) => station.code === stationCode);
      if (!station) return '';
      return station.name;
    },
  },
  // { title: '设备ID', key: 'deviceId', align: 'center' },
  // { title: '忽略类型', key: 'ignoreType', align: 'center' },
  {
    title: '设备类型',
    key: 'deviceType',
    align: 'center',
    render: (rowData) => {
      const UNKNOWN_NAME = '-';
      const ndmType = rowData.deviceId?.slice(4, 6);
      if (!ndmType) return UNKNOWN_NAME;
      const deviceType = NDM_TYPES[ndmType];
      if (!deviceType) return UNKNOWN_NAME;
      return DEVICE_TYPE_NAMES[deviceType];
    },
  },
  {
    title: '设备名称',
    key: 'deviceName',
    align: 'center',
    render: (rowData) => {
      const UNKNOWN_NAME = '-';
      const { deviceId } = rowData;
      if (!deviceId) return UNKNOWN_NAME;
      const stationCode = deviceId.slice(0, 4);
      if (!stationCode) return UNKNOWN_NAME;
      const stationDevices = lineDevices.value[stationCode];
      if (!stationDevices) return UNKNOWN_NAME;
      const ndmType = rowData.deviceId?.slice(4, 6);
      if (!ndmType) return UNKNOWN_NAME;
      const deviceType = NDM_TYPES[ndmType];
      if (!deviceType) return UNKNOWN_NAME;
      const classified = stationDevices[deviceType];
      const device = classified.find((device) => device.deviceId === deviceId);
      if (!device) return UNKNOWN_NAME;
      return device.name ?? UNKNOWN_NAME;
    },
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: 120,
    render: (rowData) => {
      const { deviceId } = rowData;
      if (!deviceId) return null;
      const stationCode = deviceId.slice(0, 4);
      if (!stationCode) return null;
      if (!hasPermission(stationCode, PERMISSION_TYPE_LITERALS.OPERATION)) return null;
      return h(
        NPopconfirm,
        {
          onPositiveClick: () => {
            console.log(rowData);
            const { id } = rowData;
            cancelIgnore({ id });
          },
        },
        {
          trigger: () => {
            return h(
              NButton,
              {
                size: 'small',
                secondary: true,
              },
              { default: () => `取消忽略` },
            );
          },
          default: () => `确认取消忽略吗？`,
        },
      );
    },
  },
]);

const { mutate: cancelIgnore } = useMutation({
  mutationFn: async (params: { id?: string; signal?: AbortSignal }) => {
    const { id, signal } = params;
    if (!id) return;
    return deleteCameraIgnoreApi([id], { signal });
  },
  onSuccess: (data) => {
    if (!data) {
      window.$message.error('取消忽略失败，请再试一次');
      return;
    }
    window.$message.success('取消忽略成功');
    getTableData();
  },
  onError: (error) => {
    if (isCancel(error)) return;
    console.error(error);
    window.$message.error(error.message);
  },
});

const tableData = ref<DataTableRowData[]>([]);

const DEFAULT_PAGE_SIZE = 10;
const pagination = reactive<PaginationProps>({
  showSizePicker: true,
  page: 1,
  pageSize: DEFAULT_PAGE_SIZE,
  pageSizes: [5, 10, 20, 50, 80, 100],
  itemCount: 0,
  prefix: ({ itemCount }) => {
    return h('div', {}, { default: () => `共${itemCount}条` });
  },
  onUpdatePage: (page: number) => {
    pagination.page = page;
    getTableData();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    getTableData();
  },
});

const abortController = ref(new AbortController());

const { mutate: getTableData, isPending: tableLoading } = useMutation({
  mutationFn: async () => {
    abortController.value.abort();
    abortController.value = new AbortController();

    const signal = abortController.value.signal;

    const res = await pageCameraIgnoreApi(
      {
        model: {},
        extra: getExtraFields(),
        current: pagination.page ?? 1,
        size: pagination.pageSize ?? DEFAULT_PAGE_SIZE,
        sort: 'id',
        order: 'descending',
      },
      {
        signal,
      },
    );

    return res;
  },
  onSuccess: (res) => {
    const { records, size, total } = res;
    pagination.pageSize = parseInt(size);
    pagination.itemCount = parseInt(total);
    tableData.value = records;
  },
  onError: (error) => {
    if (isCancel(error)) return;
    console.error(error);
    window.$message.error(error.message);
  },
});

const onClickReset = () => {
  resetSearchFields();
  pagination.page = 1;
  pagination.pageSize = DEFAULT_PAGE_SIZE;
  pagination.itemCount = 0;
  getTableData();
};
const onClickQuery = () => {
  if (searchFieldsChanged.value) {
    pagination.page = 1;
    pagination.pageSize = DEFAULT_PAGE_SIZE;
    searchFieldsChanged.value = false;
  }
  getTableData();
};

onMounted(() => {
  getTableData();
});
onBeforeUnmount(() => {
  abortController.value.abort();
});
</script>

<template>
  <NFlex vertical :size="0" style="height: 100%">
    <!-- 查询面板 -->
    <NForm style="flex: 0 0 auto; padding: 8px">
      <NGrid cols="3" :x-gap="24">
        <NFormItemGi span="1" label="车站" label-placement="left">
          <NSelect clearable placeholder="请选择车站" v-model:value="searchFields.stationCode" :options="stationSelectOptions" />
        </NFormItemGi>
        <NFormItemGi span="2" label="忽略时间" label-placement="left">
          <NDatePicker v-model:formatted-value="searchFields.createdTime" type="datetimerange" />
        </NFormItemGi>
      </NGrid>
      <!-- 操作按钮 -->
      <NGrid :cols="1">
        <NGridItem>
          <NFlex>
            <NButton @click="onClickReset">重置</NButton>
            <NButton type="primary" :loading="tableLoading" @click="onClickQuery">查询</NButton>
          </NFlex>
        </NGridItem>
      </NGrid>
    </NForm>

    <!-- 数据表格工具栏 -->
    <NFlex align="center" style="padding: 8px; flex: 0 0 auto">
      <div style="font-size: medium">告警忽略列表</div>
      <NFlex style="margin-left: auto">
        <!-- <NButton type="primary" :loading="exporting" @click="() => exportTableData()">导出</NButton> -->
      </NFlex>
    </NFlex>

    <!-- 数据表格 -->
    <NDataTable remote :columns="tableColumns" :data="tableData" :pagination="pagination" :loading="tableLoading" :single-line="false" flex-height style="height: 100%; padding: 8px; flex: 1 1 auto" />
  </NFlex>
</template>

<style scoped lang="scss"></style>
