import { defineComponent, onMounted, watchEffect, ref } from "vue";
import { RouterView, useRoute, useRouter } from 'vue-router';
import MarkerMap from '@/components/MarkerMap';
import './index.scss';
import { useIncidentStore, useDaHuaStore, useMainStore,useCommonStore } from '@/store';
import { constants } from 'zlib';
import clsx from "clsx";
import moment from 'moment';
// @ts-ignore
import closeicon from '@/assets/icons/detail/close.png';

moment.locale('zh-cn', {
  months:
    '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split(
      '_',
    ),
  monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
  weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
  weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
  weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
  longDateFormat: {
    LT: 'Ah点mm分',
    LTS: 'Ah点m分s秒',
    L: 'YYYY-MM-DD',
    LL: 'YYYY年MMMD日',
    LLL: 'YYYY年MMMD日Ah点mm分',
    LLLL: 'YYYY年MMMD日ddddAh点mm分',
    l: 'YYYY-MM-DD',
    ll: 'YYYY年MMMD日',
    lll: 'YYYY年MMMD日Ah点mm分',
    llll: 'YYYY年MMMD日ddddAh点mm分',
  },
  meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
  meridiemHour: function (h, meridiem) {
    let hour = h;
    if (hour === 12) {
      hour = 0;
    }
    if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') {
      return hour;
    } else if (meridiem === '下午' || meridiem === '晚上') {
      return hour + 12;
    } else {
      // '中午'
      return hour >= 11 ? hour : hour + 12;
    }
  },
  meridiem: function (hour, minute, isLower) {
    const hm = hour * 100 + minute;
    if (hm < 600) {
      return '凌晨';
    } else if (hm < 900) {
      return '早上';
    } else if (hm < 1130) {
      return '上午';
    } else if (hm < 1230) {
      return '中午';
    } else if (hm < 1800) {
      return '下午';
    } else {
      return '晚上';
    }
  },
  calendar: {
    sameDay: function () {
      return this.minutes() === 0 ? '[今天]Ah[点整]' : '[今天]LT';
    },
    nextDay: function () {
      return this.minutes() === 0 ? '[明天]Ah[点整]' : '[明天]LT';
    },
    lastDay: function () {
      return this.minutes() === 0 ? '[昨天]Ah[点整]' : '[昨天]LT';
    },
    nextWeek: function () {
      let startOfWeek, prefix;
      startOfWeek = moment().startOf('week');
      prefix = this.diff(startOfWeek, 'days') >= 7 ? '[下]' : '[本]';
      return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
    },
    lastWeek: function () {
      let startOfWeek, prefix;
      startOfWeek = moment().startOf('week');
      prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]';
      return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
    },
    sameElse: 'LL',
  },
  ordinalParse: /\d{1,2}(日|月|周)/,
  ordinal: function (number, period) {
    switch (period) {
      case 'd':
      case 'D':
      case 'DDD':
        return number + '日';
      case 'M':
        return number + '月';
      case 'w':
      case 'W':
        return number + '周';
      default:
        return number;
    }
  },
  relativeTime: {
    future: '%s内',
    past: '%s前',
    s: '几秒',
    m: '1 分钟',
    mm: '%d 分钟',
    h: '1 小时',
    hh: '%d 小时',
    d: '1 天',
    dd: '%d 天',
    M: '1 个月',
    MM: '%d 个月',
    y: '1 年',
    yy: '%d 年',
  },
  week: {
    // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
    dow: 1, // Monday is the first day of the week.
    doy: 4, // The week that contains Jan 4th is the first week of the year.
  },
});

export default defineComponent({
  setup() {
    const route = useRoute();
    const router = useRouter();

    const store = useIncidentStore();
    const daHuaStore = useDaHuaStore();

    const mainStore = useMainStore();
    const commonstore = useCommonStore();

    const sqdh = ref(import.meta.env.VITE_DH_SERVER as string + "/index.html");

    const markmap = ref(null);

    console.log(sqdh.value);


    const handleDaHuaSystem = () => {
      daHuaStore.dahuaUserVisible = true;
      const DAHUA = document.getElementById('DAHUA') as HTMLIFrameElement;
      DAHUA?.contentWindow?.postMessage('creatMeeting', '*');
    };
    // console.log(daHuaStore.dhuser);

    // const list = computed(() => [

    // ]);

    // login da hua
    onMounted(() => {

      var dv = document.getElementsByClassName('videoifram')[0];
      var x = 0;
      var y = 0;
      var l = 0;
      var t = 0;
      var isDown = false;
      //鼠标按下事件
      dv.onmousedown = function (e) {
        //获取x坐标和y坐标
        x = e.clientX;
        y = e.clientY;

        //获取左部和顶部的偏移量
        l = dv.offsetLeft;
        t = dv.offsetTop;
        //开关打开
        isDown = true;
        //设置样式  
        dv.style.cursor = 'move';
      }
      //鼠标移动
      window.onmousemove = function (e) {
        if (isDown == false) {
          return;
        }
        //获取x和y
        var nx = e.clientX;
        var ny = e.clientY;
        //计算移动后的左偏移量和顶部的偏移量
        var nl = nx - (x - l);
        var nt = ny - (y - t);

        dv.style.left = nl + 'px';
        dv.style.top = nt + 'px';
        setTimeout(() => {
          try{
            console.log(window.vPlayArea)
            if(window.vPlayArea){
              window.vPlayArea.dragResize(0,0,0,0)
          }
          }catch(E){
            console.log(E)
          }
          
        }, 1);
       
          
          
      

      }
      //鼠标抬起事件
      dv.onmouseup = function () {
        //开关关闭
        isDown = false;
        dv.style.cursor = 'default';
      }

      // if (!localStorage.getItem('DAHUA_token')) {
      //   daHuaStore.DAHUALogin();
      // } else {
      //   daHuaStore.KEEPAlive(); //保活 //获取当前用户信息
      //   daHuaStore.DAHUAUserInfo().then((res) => {
      //     console.log(res);
      //     daHuaStore.DAHUACreateMeet(res).then((data) => {
      //       //创建会议
      //       console.log(data);
      //       let obj = {
      //         user: res,
      //         meetId: data.id,
      //         member: [
      //           {
      //             userName: res.userName,
      //             userId: res.userCode,
      //             region: res.paasId,
      //             type: 'client',
      //             // speak:'true',
      //             number: res.userPhone,
      //             // department:'根组织'
      //           },
      //         ],
      //       };
      //       localStorage.setItem('meeting', JSON.stringify(obj));
      //       // console.log(obj);
      //       // daHuaStore.DAHUAMeetingMember(obj);
      //       // daHuaStore.DAHUAMeetingUser(data.id);
      //       // daHuaStore.DAHUADeleteMeet(data.id);
      //     });
      //   });
      //   // console.log(dhUser);
      //   daHuaStore.DAHUADeviceList('S4NbecfYB1DFLAIM9FFHQ8'); //测试执法记录仪
      //   daHuaStore.DAHUADeviceList('S4NbecfYB1DGB68AN187Q8'); //执法人员设备列表
      //   daHuaStore.DAHUADeviceList('S4NbecfYB1DGB68S6S0UFC'); //执法车辆列表
      // }
      // const DAHUA = document.getElementById('DAHUA') as HTMLIFrameElement;
      // if (!DAHUA) return
      // DAHUA.onload = function () {
      //   // @ts-ignore
      //   DAHUA.contentWindow.postMessage('onload', '*');
      // }
      // window.addEventListener('message', e => {
      //   if (e.data === 'closeIframe') {
      //     daHuaStore.dahuaUserVisible = false;
      //   }
      // }, false);
      try {
        (yjzh_btn.value)?.addEventListener("click", () => {
          if(commonstore.isclick){
            return;
          }
          commonstore.isclick = true;


       if(window.theSocket){
         if(window.metting){
          setTimeout(() => {
            cremetting();
            
          }, 1000);
         }else{
          const meeting = new Meeting();
          meeting.settargetId("vPlayArea");
          window.metting = meeting;
          setTimeout(() => {
            cremetting();
            
          }, 1000);
         }
        
       }else{
        const meeting = new Meeting();
        meeting.openClient(() => {
          
          meeting.settargetId("vPlayArea");
          window.metting = meeting;
          setTimeout(() => {
            cremetting();
            
          }, 1000);
         
        });

       }
      
        

        async function cremetting(){


          try{
            window.metting.deleteAllMeeting(dothing);
          }catch(E){}

         async function dothing(){
            await window.metting.getLocalUserInfo();
          const res = await window.metting.queryUser(window.metting.inviteSelf.userId);

          // _this.localUserInfo.masterName = res.userName;
          // _this.localUserInfo.masterId = res.userCode;
          // _this.localUserInfo.masterNumber = res.userPhone;
          // _this.localUserInfo.region = res.paasId;
          const chartParams = {
            chatName: "测试会商名称",
            bOpenDirect: true,
            memberId: res.userCode, // 成员id
            memberName: res.name, // 成员名称
            regionId: res.paasId, // 成员的pass域id
            memberType: 4, // 成员类型，Integer ,1 单兵；2 普通电话；3 对讲机；4 app|客户端；6 可是话机； 7 汇接话机（PSTN、手机号码等）； 8 车载；9 无人机喊话云台； 10 无人机地面站对讲平台； 11 ipc; 12 NVR
            memberCode: "", // 成员设备编码
            memberNumber: ""// 成员号码
          };
          window.theSocket&&window.theSocket.createGroupChat(chartParams);
          commonstore.isclick = false;

          }
          
         
          
        }

  
        })
        
      } catch (error) {
        
      }

     

    });
    const timetext = ref("-");
    const datetext = ref('-');
    const weektext = ref('-');
    // debugger
    setInterval(() => {
      datetext.value =
        moment().format('YYYY年MM月DD日');
      weektext.value = moment().format('dddd');
      timetext.value = moment().format('HH:mm:ss');

    }, 1000)

    const yjzh_btn = ref(null);

    return () => (
      <section class="base-layout-container">
        <iframe
          style={{ visibility: 'hidden', height: '100%', width: '100%' }}
          class={clsx('dahua-content', {
            ['display']: daHuaStore.dahuaUserVisible,
          })}
          id="DAHUA"
          name="DAHUA"
          src={sqdh.value}
          frameborder="0"
        />
        <div
          class="videoifram"
          style={mainStore.videoisshow ? 'display:block' : 'display:none'}
         >
          <div class="title">{mainStore.videotitle}</div>
          <div class="closebtn"  onClick={() => {
            mainStore.videoisshow = false;
            if(window.metting){
              window.metting.closeVideo();
            if(window.isdanbing){
              window.metting.deleteMeeting();
              window.metting.closeClient()
              window.metting =false; window.theSocket = false;
            }
             
            }
            
          }}>
            <img src={closeicon} />
          </div>
          <div id="vPlayArea" ></div>
        </div>
        <header class="base-layout-title-contatisner">
          <div class="back-to-home " onClick={() => router.push('/home')}></div>
          <div class="time-text ">
            <span>{timetext.value}</span>
            <span>{datetext.value}</span>
            <span>{weektext.value}</span>
          </div>
        </header>
        <main>
          <RouterView />
          <MarkerMap
            readonly={route.path.includes('incidentDetail')}
            ref={markmap}
          // marker={store.incidentDetail}
          />

          <div class={"yjld_btn " + (commonstore.isclick?"animate__animated animate__rotateIn":"")} ref={yjzh_btn}></div>
        </main>
      </section>
    );
  },
});
