<script setup lang="ts">
import type { Station, SyncCameraResult } from '@/apis';
import { usePermissionStore } from '@/stores';
import { watchDebounced } from '@vueuse/core';
import { EditIcon, PlusCircleIcon, Trash2Icon } from 'lucide-vue-next';
import { NFlex, NIcon, NList, NListItem, NModal, NScrollbar, NStatistic, NText, NThing } from 'naive-ui';
import { computed, ref, toRefs } from 'vue';

const props = defineProps<{
  syncCameraResult: Record<Station['code'], SyncCameraResult>;
}>();

const emit = defineEmits<{
  afterLeave: [];
}>();

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

const { syncCameraResult } = toRefs(props);

const show = ref(false);

watchDebounced(
  [syncCameraResult],
  ([result]) => {
    show.value = Object.keys(result).length > 0;
  },
  {
    debounce: 500,
    deep: true,
  },
);

const onAfterLeave = () => {
  emit('afterLeave');
};

const syncList = computed(() => {
  return Object.values(syncCameraResult.value).map((sync) => {
    const { stationCode, startTime, endTime, insertList, updateList, deleteList } = sync;
    const stationName = stations.value.find((station) => station.code === stationCode)?.name;
    return { stationName, startTime, endTime, insertList, updateList, deleteList };
  });
});
</script>

<template>
  <NModal v-model:show="show" preset="card" title="摄像机同步结果" style="width: 600px" @after-leave="onAfterLeave">
    <NScrollbar style="max-height: 400px">
      <NList hoverable clickable>
        <NListItem v-for="{ stationName, endTime, insertList, updateList, deleteList } in syncList" :key="stationName">
          <NThing title-independent>
            <template #header>
              <NText strong>{{ stationName }}</NText>
            </template>
            <template #header-extra>
              <NText depth="3"> {{ endTime }} 完成 </NText>
            </template>
            <NFlex justify="space-around" :size="24" style="margin-top: 8px">
              <NStatistic label="新增">
                <template #prefix>
                  <NIcon :component="PlusCircleIcon" />
                </template>
                {{ insertList.length }}
              </NStatistic>
              <NStatistic label="更新">
                <template #prefix>
                  <NIcon :component="EditIcon" />
                </template>
                {{ updateList.length }}
              </NStatistic>
              <NStatistic label="删除">
                <template #prefix>
                  <NIcon :component="Trash2Icon" />
                </template>
                {{ deleteList.length }}
              </NStatistic>
            </NFlex>
          </NThing>
        </NListItem>
      </NList>
    </NScrollbar>
  </NModal>
</template>

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