// 报警消息实时提醒

import { getNewIssueList, updateReadIssueId } from '../apis';
import useViolationNoticeStore, { getPlace, emitter } from '../stores/use-violation-notice-store';
import { onUnmounted, onMounted, nextTick } from 'vue';
import dayjs from 'dayjs';
import { push } from 'notivue';
import useQuestionListStore from '@/views/institute-safety/modules/safety-company-home/stores/use-question-list';
import { WORKSHOP_INFOS } from '../../safety-workshop-list/constants';

const questionListStore = useQuestionListStore();
const useViolationRealtimeCompany = () => {
  /** 消息队列，最新的排在最前面，最老的排在最后面 */
  // 报警消息最后返回数据的id
  const violationStore = useViolationNoticeStore();

  let apiTimer: number;
  let isFirstLoad = true;
  //弹出消息
  const showNotice = () => {
    const showItem = violationStore.getLastNotice();
    // 从数组最末尾弹出消息

    if (!showItem) return;

    const renderTime = dayjs(showItem.createdAt).format('YYYY-MM-DD HH:mm:ss');
    const renderPlace = getPlace([showItem.workshopName, showItem.workspaceName]);
    push.success({
      props: {
        thumbnail: showItem.pictures?.[0],
        type: showItem.title,
        device: showItem.cameraCode,
        place: renderPlace,
        time: renderTime,
        onClick: () => {
          questionListStore.setState({
            type: 'all',
            workshopCodes: WORKSHOP_INFOS.map((item) => item.workshopCode),
          });
          nextTick(() => {
            questionListStore.openList();
          });
        },
      },
      onAutoClear(item) {
        showNotice();
      },
      onManualClear(item) {
        showNotice();
      },
    });
  };
  emitter.on('showNotice', showNotice);

  const getViolationsRealtime = () => {
    getNewIssueList().then((res) => {
      if (!res || res?.length === 0) return;
      if (isFirstLoad) {
        // 如果第一次加载，只显示第一条
        violationStore.add([res[0]]);
        isFirstLoad = false;
      } else {
        violationStore.add(res);
      }
      // 在此次调用更新id接口
      updateReadIssueId(res[0].id);
    });
  };

  /** 轮询api */
  const pollingApi = () => {
    getViolationsRealtime();
    clearInterval(apiTimer);
    apiTimer = window.setInterval(() => {
      getViolationsRealtime();
    }, 5000);
  };

  onMounted(() => {
    violationStore.clear();
    pollingApi();
  });

  onUnmounted(() => {
    clearInterval(apiTimer);
    violationStore.clear();
  });
};

export default useViolationRealtimeCompany;
