import { onMounted, onUnmounted, defineComponent, ref, watchEffect,watch } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import {
  useCommonStore,
  useDaHuaStore,
  useIncidentStore,
  useMainStore,
  useMarkerStore,
} from '@/store';
import IncidentInfoCard from './IncidentInfoCard';
import CommandChainCard from './CommandChainCard';
import EmergencyLinkageCard from './EmergencyLinkageCard';
import IncidentPlanCard from './IncidentPlanCard';
import LiveMonitoringCard from './LiveMonitoringCard';
import ExecutionLogCard from './ExecutionLogCard';
import LiveVideoCard from './LiveVideoCard';
import AccidentCard from './AccidentCard';
import EmergencyCard from './EmergencyCard';
import EmExCard from './EmExCard';
import WzCard from './WzCard';
import './index.scss';
// import { watch } from 'fs';
import { isEmpty } from 'lodash';
import isString from 'lodash/isString';
import { NeedsReadUser, NeedsReadUserName } from '@/api/common';
import { BaseReg } from '@/constants/constants';

// @ts-ignore
import Iconback from '@/assets/icons/detail/back@2x.png';
import MessageCard from '../HomePage/MessageCard';
import VideoUserListCard from './VideoUserListCard';



export default defineComponent({
  name: 'IncidentDetail',
  provide: {},
  setup() {
    const store = useIncidentStore();
    const commonStore = useCommonStore();
    const mainStore = useMainStore();
    const markerStore = useMarkerStore();
    const daHuaStore = useDaHuaStore();
    const route = useRoute();
    const router = useRouter();

    const logcard = ref();
    const liveVideoRef = ref<HTMLElement>();

    watchEffect(() => {
      const messageIDs =
        store.incidentDetail?.process
          ?.map((item) => (item.des?.match(BaseReg) ? item.id : null))
          .filter(isString) ?? [];
      if (messageIDs.length > 0) {
        Promise.all(
          messageIDs.map((id) =>
            mainStore.getMessage({
              msType: '2',
              msSource: '1',
              msNo: id,
            }),
          ),
        ).then((rows) => {
          rows.forEach((message) => {
            if (message?.[0]) {
              const m = message[0];
              const idx = store.incidentDetail.process?.findIndex(
                (p) => p.id === m.msNo,
              );
              if (idx && idx >= 0) {
                // @ts-ignore
                store.incidentDetail.process[idx].des =
                  // @ts-ignore
                  (store.incidentDetail.process[idx].des.replace(
                    /\+\+\+\+/g,
                    '',
                  ) ?? '') +
                  '>>>>' +
                  NeedsReadUserName.map((user) => user).join(',');
                // (m.messageReadInfoList
                //   ?.map((user) =>
                //     user.readState === '0' ? user.userId : null,
                //   )
                //   .filter(isString)) ?? '' ;
              }
            }
          });
        });
      }
    });

    watch(
      () => store.incidentDetail,
      (next) => {
        if(next.baseInfo==undefined||next.baseInfo==null) router.push('/home');
        // console.log(next)
      },
    );

    const docloseeventlist = () => {
      mainStore.setEventListshow(false);
    }


    var timer = null;

    onMounted(async () => {
      store.getIncidentList({
         // 事件等级1,2的事件
         level: 1,
       });
      commonStore.getGlobalDict('zhdd_incident_type');
      commonStore.getGlobalDict('zhdd_incident_source');
      commonStore.getGlobalDict('zhdd_org_upload');
      commonStore.getGlobalDict('zhdd_incident_level');
      liveVideoRef.value?.addEventListener('click', (el: MouseEvent) => {
        if (el.target && liveVideoRef.value?.contains(el.target as Node)) {
        }
      });
      
      // if (!store.incidentDetail) {
      //   router.push("/home");

      // }
    });
    timer = setInterval(() => {
      if (route.query.id != undefined) {
        // store.toggleLoading();
        store.getIncidentItem(route.query.id as string);
        // console.log('刷新------' + route.query.id);
        // div.scrollTop = div.scrollHeight;
        try {
          var div = document.getElementById('cardlog1');
          // console.log(div?.scrollTop);
          if (div && div.scrollTop == 0) div.scrollTop = div.scrollHeight;
        } catch (error) {
          // debugger
        }
      }
      // store.getIncidentItem(item.id);
    }, 5 * 1000);
    onUnmounted(() => {
      store.incidentDetail = {};
      markerStore.currentIncident = {};
      markerStore.livevideovisible = false;
      markerStore.livevideos = [];
      clearInterval(timer);
    });

    return () => (
      <>
        <div class="sc"></div>
        <div class="incident-detail-page-container">
          {
            <div class="detail-left">
              <div class="event-list-c" v-show={mainStore.isshoweventlist}>
                <div class="elc-back" onClick={docloseeventlist}>
                  <img src={Iconback} /> 返回
                </div>
                <div class="elc-content">
                  {store.incidents.data?.map((item, idx) => (
                    <a
                      onClick={async (e) => {
                        e.preventDefault();
                        // @ts-ignore
                        markerStore.currentIncident = item;
                        item.id && (await store.getIncidentItem(item.id));
                        docloseeventlist();
                        router.push(`/incidentDetail?id=${item.id}`);
                      }}>
                      <div class="message-item">
                        <div class="title">
                          {/* <span class="index"></span> */}
                          <span>
                            {idx + 1}、
                            {item.createTime +
                              '，【' +
                              item.name +
                              '】在' +
                              item.addr +
                              '处发生了' +
                              (commonStore.globalDict[
                                'zhdd_incident_type'
                              ]?.find(
                                (i) =>
                                  i.dictValue.toString() === `${item.type}`,
                              )?.dictLabel ?? '预警') +
                              '事件'}
                          </span>
                        </div>
                        <div class="desc">
                          来源：
                          {
                            commonStore.globalDict[
                              'zhdd_incident_source'
                            ]?.find(
                              (i) =>
                                i.dictValue.toString() === `${item.source}`,
                            )?.dictLabel
                          }
                        </div>
                      </div>
                    </a>
                  ))}
                </div>
              </div>
              <IncidentInfoCard />
              <LiveMonitoringCard />
              {/* <IncidentPlanCard /> */}
              {/* <EmergencyLinkageCard /> */}
              <CommandChainCard />
              <AccidentCard />
            </div>
          }

          {
            <div class="detail-right">
              {/* <IncidentPlanCard />
              <EmergencyCard /> */}
              <EmExCard></EmExCard>
              <WzCard></WzCard>

              <ExecutionLogCard ref={logcard} />

              {/* <LiveMonitoringCard /> */}
            </div>
          }

          {
            // <VideoUserListCard></VideoUserListCard>
          }

        </div>
        {/*大华 相关的通讯录可以放这里*/}
        {/*{daHuaStore.dahuaUserVisible && (*/}
        {/*  <div ref={liveVideoRef} class="live-video-container-left right">*/}
        {/*    <div class="live-video-container">*/}
        {/*      <LiveVideoCard />*/}
        {/*      <div*/}
        {/*        class="live-video-close"*/}
        {/*        onClick={() => (daHuaStore.dahuaUserVisible = false)}*/}
        {/*      />*/}
        {/*    </div>*/}
        {/*  </div>*/}
        {/*)}*/}

        {markerStore.livevideovisible && (
          <div ref={liveVideoRef} class="live-video-container-left">
            <div class="live-video-container">
              <LiveVideoCard />
              <div
                class="live-video-close"
                onClick={() => (markerStore.livevideovisible = false)}
              />
            </div>
          </div>
        )}
      </>
    );
  },
});
