import RtcClient from "./rtc-client";
import ShareClient from "./share-client";
import Presetting from "./presetting";
import { message } from "antd";
import { updateRoomEndTime } from '../../../services/api';

export default function Common() {
  let isCamOn = true;
  let isMicOn = true;
  let isScreenOn = false;
  let isJoined = true;
  let rtc = null;
  let share = null;
  let shareUserId = "";
  let cameraId = "";
  let micId = "";
  let number = 0
  let videoThis = null;
  let common = {
    login(roomId, mobilePhone, cid, name, _this) {
      Presetting(false, roomId, mobilePhone, cid, name, (options) => {
        rtc = new RtcClient(options, _this);
        console.log(_this)
        videoThis = _this;
        this.join();
      });
      Presetting(true, roomId, mobilePhone, cid, name, (options) => {
        shareUserId = options.userId;
        share = new ShareClient(options);
      });

      // if ($("#userId").val() == "") {
      //   alert("用户名不能为空！");
      //   return;
      // }
      // if ($("#roomId").val() == "") {
      //   alert("房间号不能为空！");
      //   return;
      // }
      // presetting.login(false, (options) => {
      //   const options = {
      //     sdkAppId: 1400246643,
      //     userId: "user_43707228",
      //     userSig:
      //       "eJwtzMEKgzAQBNB-ydUia4y6Cr0Ueih4UqG9lWoSWaJVkrQUSv*9oh7nzTBf1pR1*FaWFYyHwA5rJqmenjSt-HLK3kWcQcY57gMnzWOeSbIiEgBcpKmIt8bTqBZNEFFEOeCm6jOTXTwFgQD7B-XLe95IDzc7TH2gz21QXU5j1155OdLQmUrWueZZMiBOxh3Z7w8UZDLR",
      //     roomId: "83999",
      //   };
      //   rtc = new RtcClient(options);
      //   // join();
      // // });
      // // presetting.login(true, (options) => {
      // //   shareUserId = options.userId;
      //   share = new ShareClient(options);
      // });
    },

    join() {
      rtc.join();
      // $("#login-root").hide();
      // $("#room-root").show();
      // $("#header-roomId").html("房间号: " + $("#roomId").val());
      // $("#member-me")
      //   .find(".member-id")
      //   .html($("#userId").val() + "(我)");
    },

    leave(roomNo) {
      // document
      //   .getElementById("main-video")
      //   .appendChild(document.getElementById("mask_main"));
      // $("#mask_main").appendTo($("#main-video"));
      /**
       * 调用结束时间的接口
       * 主要作用是服务端记录结束时间
       */
      updateRoomEndTime({ roomNo }).then(res => {
        console.log(res)
      })
      rtc.leave();
      share.leave();
      message.info('您已离开房间');
    },

    publish() {
      rtc.publish();
    },

    unpublish() {
      rtc.unpublish();
    },

    muteAudio() {
      rtc.muteLocalAudio();
    },

    unmuteAudio() {
      rtc.unmuteLocalAudio();
    },

    muteVideo() {
      document.getElementById("mask_main").style.display = "flex";
      // $("#mask_main").show();
      rtc.muteLocalVideo();
    },

    unmuteVideo() {
      rtc.unmuteLocalVideo();
      document.getElementById("mask_main").style.display = "none";
      // $("#mask_main").hide();
    },

    startSharing() {
      share.join();
    },

    stopSharing() {
      share.leave();
    },

    //主视频点击切换
    mainVideoClick() {
      let mainVideo = document.getElementById("main-video");
      if (
        document.getElementById("div-video-local").childNodes[0].getAttribute("id") ==
        mainVideo.getAttribute("id")
      ) {
        return;
      }
      //释放main-video grid-area
      // mainVideo.style.gridArea = "auto/auto/auto/auto";
      // exchangeView(document.getElementById("main-video"), mainVideo);
      // //将video-grid中第一个div设为main-video
      // document.getElementsByClassName("video-box")[0].style.gridArea =
      //   "1/1/3/4";
      mainVideo.style.height = '100%';
      // mainVideo.style.paddingBottom='0';
      const right = mainVideo;
      const left = document.querySelector('#div-video-local').childNodes[0];
      document.querySelector('#div-video-local').removeChild(left);
      document.querySelector('#div-video-local').appendChild(right);
      left.style.height = '200px';
      // document
      //   .querySelector('#div-video-child')
      //   .removeChild(
      //     right
      //   );
      document.querySelector('#div-video-child').appendChild(left);


      //chromeM71以下会自动暂停，手动唤醒
      if (getBroswer().broswer == "Chrome" && getBroswer().version < "72") {
        rtc.resumeStreams();
      }
      // $("#main-video").on("click", () => {
      //   let mainVideo = $(".video-box").first();
      //   if ($("#main-video").is(mainVideo)) {
      //     return;
      //   }
      //   //释放main-video grid-area
      //   mainVideo.css("grid-area", "auto/auto/auto/auto");
      //   exchangeView($("#main-video"), mainVideo);
      //   //将video-grid中第一个div设为main-video
      //   $(".video-box").first().css("grid-area", "1/1/3/4");
      //   //chromeM71以下会自动暂停，手动唤醒
      //   if (getBroswer().broswer == "Chrome" && getBroswer().version < "72") {
      //     rtc.resumeStreams();
      //   }
      // });
    },
    //共享屏幕按钮点击
    screenShareClick() {
      // throttle(() => {
      if (!TRTC.isScreenShareSupported()) {
        alert("当前浏览器不支持屏幕分享！");
        return;
      }
      if (isScreenOn) {
        // document
        //   .getElementById("screen-btn")
        //   .setAttribute(
        //     "src",
        //     require("../../../assets/images/prevention/screen-off.png")
        //   );
        // $("#screen-btn").attr("src", "./img/screen-off.png");
        this.stopSharing();
        isScreenOn = false;
      } else {
        // document
        //   .getElementById("screen-btn")
        //   .setAttribute(
        //     "src",
        //     require("../../../assets/images/prevention/screen-on.png")
        //   );
        // $("#screen-btn").attr("src", "./img/screen-on.png");
        this.startSharing();
        isScreenOn = true;
      }
      // }, 2000);
    },
    setBtnClickFuc() {
      //userid roomid规格
      //$('#userId').on('input', function(e) {
      //    e.preventDefault();
      //    let val = $('#userId').val().slice(5);
      //    $('#userId').val('user_'+val.replace(/[^\d]/g,''));
      //});
      // $("#roomId").on("input", function (e) {
      //   e.preventDefault();
      //   let val = $("#roomId").val();
      //   $("#roomId").val(val.replace(/[^\d]/g, ""));
      // });
      //login
      // $("#login-btn").click(() => {
      //   login();
      // });
      //open or close camera
      // $("#video-btn").on("click", () => {
      //   if (isCamOn) {
      //     $("#video-btn").attr("src", "./img/big-camera-off.png");
      //     $("#video-btn").attr("title", "打开摄像头");
      //     $("#member-me")
      //       .find(".member-video-btn")
      //       .attr("src", "img/camera-off.png");
      //     isCamOn = false;
      //     muteVideo();
      //   } else {
      //     $("#video-btn").attr("src", "./img/big-camera-on.png");
      //     $("#video-btn").attr("title", "关闭摄像头");
      //     $("#member-me")
      //       .find(".member-video-btn")
      //       .attr("src", "img/camera-on.png");
      //     isCamOn = true;
      //     unmuteVideo();
      //   }
      // });
      //open or close microphone
      // $("#mic-btn").on("click", () => {
      //   if (isMicOn) {
      //     $("#mic-btn").attr("src", "./img/big-mic-off.png");
      //     $("#mic-btn").attr("title", "打开麦克风");
      //     $("#member-me")
      //       .find(".member-audio-btn")
      //       .attr("src", "img/mic-off.png");
      //     isMicOn = false;
      //     muteAudio();
      //   } else {
      //     $("#mic-btn").attr("src", "./img/big-mic-on.png");
      //     $("#mic-btn").attr("title", "关闭麦克风");
      //     $("#member-me")
      //       .find(".member-audio-btn")
      //       .attr("src", "img/mic-on.png");
      //     isMicOn = true;
      //     unmuteAudio();
      //   }
      // });
      //share screen or not
      // $("#screen-btn").on(
      //   "click",
      //   throttle(() => {
      //     if (!TRTC.isScreenShareSupported()) {
      //       alert("当前浏览器不支持屏幕分享！");
      //       return;
      //     }
      //     if ($("#screen-btn").attr("src") == "./img/screen-on.png") {
      //       $("#screen-btn").attr("src", "./img/screen-off.png");
      //       stopSharing();
      //       isScreenOn = false;
      //     } else {
      //       $("#screen-btn").attr("src", "./img/screen-on.png");
      //       startSharing();
      //       isScreenOn = true;
      //     }
      //   }, 2000)
      // );
      //logout
      // $("#logout-btn").on("click", () => {
      //   leave();
      //   $("#room-root").hide();
      //   $("#login-root").show();
      // });
      //switch main video
      // $("#main-video").on("click", () => {
      //   let mainVideo = $(".video-box").first();
      //   if ($("#main-video").is(mainVideo)) {
      //     return;
      //   }
      //   //释放main-video grid-area
      //   mainVideo.css("grid-area", "auto/auto/auto/auto");
      //   exchangeView($("#main-video"), mainVideo);
      //   //将video-grid中第一个div设为main-video
      //   $(".video-box").first().css("grid-area", "1/1/3/4");
      //   //chromeM71以下会自动暂停，手动唤醒
      //   if (getBroswer().broswer == "Chrome" && getBroswer().version < "72") {
      //     rtc.resumeStreams();
      //   }
      // });

      //chrome60以下不支持popover，防止error
      if (getBroswer().broswer == "Chrome" && getBroswer().version < "60")
        return;
      //开启popover
      $(function () {
        $('[data-toggle="popover"]').popover();
      });
      $("#camera").popover({
        html: true,
        content: () => {
          return $("#camera-option").html();
        },
      });
      $("#microphone").popover({
        html: true,
        content: () => {
          return $("#mic-option").html();
        },
      });

      $("#camera").on("click", () => {
        $("#microphone").popover("hide");
        $(".popover-body").find("div").attr("onclick", "setCameraId(this)");
      });

      $("#microphone").on("click", () => {
        $("#camera").popover("hide");
        $(".popover-body").find("div").attr("onclick", "setMicId(this)");
      });

      //点击body关闭popover
      $("body").click(() => {
        $("#camera").popover("hide");
        $("#microphone").popover("hide");
      });

      //popover事件
      $("#camera").on("show.bs.popover", () => {
        $("#camera").attr("src", "./img/camera-on.png");
      });
      $("#camera").on("hide.bs.popover", () => {
        $("#camera").attr("src", "./img/camera.png");
      });

      $("#microphone").on("show.bs.popover", () => {
        $("#microphone").attr("src", "./img/mic-on.png");
      });
      $("#microphone").on("hide.bs.popover", () => {
        $("#microphone").attr("src", "./img/mic.png");
      });
    },

    setCameraId(thisDiv) {
      //   cameraId = $(thisDiv).attr("id");
      cameraId = thisDiv;
    },

    setMicId(thisDiv) {
      micId = $(thisDiv).attr("id");
    },

    addVideoView(id, videoThis, isLocal = false) {
      var div = document.createElement("div");
      div.setAttribute("id", id);
      div.className = "video-box video-container";
      div.style.justifyContent = "center";
      number = number + 1
      document.getElementById("div-video-child").appendChild(div);
      // div.onclick = ()=>{
      //   console.log(123);
      //   videoThis.setLayout(id)
      // }
      // document.getElementById("video-content").appendChild(div);
      //设置监听
      //切换排版
      // div.onclick = () => {
      //   let list = document.querySelectorAll('.video-container');
      //   let left = document.getElementById('video-left');
      //   let right = document.getElementById('video-right');
      //   left.style.display = "block";
      //   right.style.display = "block";
      //   for (let i = 0; i < list.length; i++) {
      //     list[i].width = "100%";
      //     list[i].height = "100%";
      //     if (list[i] != div) {
      //       document.querySelector('#video-right').appendChild(list[i]);
      //     }
      //   }
      //   document.querySelector('#video-left').appendChild(div)
      //   //chromeM71以下会自动暂停，手动唤醒
      //   if (getBroswer().broswer == "Chrome" && getBroswer().version < "72") {
      //     rtc.resumeStreams();
      //   }
      // };
      //拖动事件
      // let clientX = 0, clientY = 0, x = 0, y = 0, isDown = false,
      //   offsetLeft = 0, offsetTop = 0

      // div.onmousedown = (e) => {
      //   isDown = true
      //   clientX = e.clientX
      //   clientY = e.clientY
      //   offsetLeft = document.getElementById(id).offsetLeft
      //   offsetTop = document.getElementById(id).offsetTop
      // }
      // div.onmousemove = (e) => {
      //   if (isDown == false) {
      //     return
      //   }
      //   //获取x坐标和y坐标
      //   var nx = e.clientX;
      //   var ny = e.clientY;
      //   // //计算移动后的左偏移量和顶部的偏移量
      //   var nl = nx - (clientX - offsetLeft);
      //   var nt = ny - (clientY - offsetTop);
      //   x = nl;
      //   y = nt;
      //   div.style.top = y + 'px'
      //   div.style.left = x + 'px'
      // }
      // div.onmouseup = (e) => {
      //   isDown = false
      // }
    },

    addMemberView(id) {
      let memberElm = document.getElementById("member-me").cloneNode(true);
      // let memberElm = $("#member-me").clone();
      memberElm.setAttribute("id", id);
      memberElm.getElementsByClassName("member-id")[0].innerHTML = id;
      // memberElm.find("div.member-id").html(id);
      memberElm.style.display = "flex";
      // memberElm.css("display", "flex");
      document.getElementById("member-list").appendChild(memberElm);
      // memberElm.appendTo($("#member-list"));
    },

    removeView(id) {
      if (document.getElementById(id)) {
        // document.getElementsByClassName("video-box")[0].style.gridArea =
        //   "1/1/3/4";
        document.getElementById(id).remove();
        if (document.getElementById('div-video-local').childNodes.length == 0) {
          let mainVideo = document.getElementById("main-video");
          mainVideo.style.height = '25%';
          // mainVideo.style.paddingBottom='0';
          const right = mainVideo;
          document.querySelector('#div-video-local').appendChild(right);
        }
      }
      // if ($("#" + id)[0]) {
      //   $("#" + id).remove();
      //   //将video-grid中第一个div设为main-video
      //   $(".video-box").first().css("grid-area", "1/1/3/4");
      // }
    },

    isPC() {
      var userAgentInfo = navigator.userAgent;
      var Agents = new Array(
        "Android",
        "iPhone",
        "SymbianOS",
        "Windows Phone",
        "iPad",
        "iPod"
      );
      var flag = true;
      for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
          flag = false;
          break;
        }
      }
      return flag;
    },

    getCameraId() {
      //   return cameraId;
      TRTC.getCameras().then((devices) => {
        // devices.forEach(device => {
        //   if (!cameraId) {
        //    return cameraId = device.deviceId;
        //   }
        //   // let div = $('<div></div>');
        //   // div.attr('id', device.deviceId);
        //   // div.html(device.label);
        //   // div.appendTo('#camera-option');
        // });
        if (devices.length > 0) {
          this.isCamOn = true
          cameraId = devices[0].deviceId;
          return cameraId;
        } else {
          this.isCamOn = false;
          console.error("您的电脑没有摄像头或不允许该浏览器使用");
          message.warning("您的电脑没有摄像头或不允许该浏览器使用")
        }
      });
    },

    getMicrophoneId() {
      //   return micId;
      TRTC.getMicrophones().then((devices) => {
        console.log(devices)
        // devices.forEach(device => {
        //   if (!Common.micId) {
        //     Common.micId = device.deviceId;
        //   }
        //   // let div = $('<div></div>');
        //   // div.attr('id', device.deviceId);
        //   // div.html(device.label);
        //   // div.appendTo('#mic-option');
        // });
        if (devices.length > 0) {
          this.isMicOn = true;
          micId = devices[0].deviceId;
          return micId;
        } else {
          this.isMicOn = false;
          console.error("您的电脑没有麦克风或不允许该浏览器使用");
          message.error("您的电脑没有麦克风或不允许该浏览器使用")
        }
      });
    },

    throttle(func, delay) {
      var timer = null;
      var startTime = Date.now();
      return function () {
        var curTime = Date.now();
        var remaining = delay - (curTime - startTime);
        var context = this;
        var args = arguments;
        clearTimeout(timer);
        if (remaining <= 0) {
          func.apply(context, args);
          startTime = Date.now();
        } else {
          timer = setTimeout(() => {
            console.log("duplicate click");
          }, remaining);
        }
      };
    },

    isHidden() {
      var hidden, visibilityChange;
      if (typeof document.hidden !== "undefined") {
        hidden = "hidden";
        visibilityChange = "visibilitychange";
      } else if (typeof document.msHidden !== "undefined") {
        hidden = "msHidden";
        visibilityChange = "msvisibilitychange";
      } else if (typeof document.webkitHidden !== "undefined") {
        hidden = "webkitHidden";
        visibilityChange = "webkitvisibilitychange";
      }
      return document[hidden];
    },
    isCamOn,
    isMicOn,
    isScreenOn,
    isJoined,
    rtc,
    share,
    shareUserId,
    cameraId,
    micId,
  };

  function getBroswer() {
    var sys = {};
    var ua = navigator.userAgent.toLowerCase();
    var s;
    (s = ua.match(/edge\/([\d.]+)/))
      ? (sys.edge = s[1])
      : (s = ua.match(/rv:([\d.]+)\) like gecko/))
        ? (sys.ie = s[1])
        : (s = ua.match(/msie ([\d.]+)/))
          ? (sys.ie = s[1])
          : (s = ua.match(/firefox\/([\d.]+)/))
            ? (sys.firefox = s[1])
            : (s = ua.match(/chrome\/([\d.]+)/))
              ? (sys.chrome = s[1])
              : (s = ua.match(/opera.([\d.]+)/))
                ? (sys.opera = s[1])
                : (s = ua.match(/version\/([\d.]+).*safari/))
                  ? (sys.safari = s[1])
                  : 0;

    if (sys.edge) return { broswer: "Edge", version: sys.edge };
    if (sys.ie) return { broswer: "IE", version: sys.ie };
    if (sys.firefox) return { broswer: "Firefox", version: sys.firefox };
    if (sys.chrome) return { broswer: "Chrome", version: sys.chrome };
    if (sys.opera) return { broswer: "Opera", version: sys.opera };
    if (sys.safari) return { broswer: "Safari", version: sys.safari };

    return { broswer: "", version: "0" };
  }

  function throttle(func, delay) {
    var timer = null;
    var startTime = Date.now();
    return function () {
      var curTime = Date.now();
      var remaining = delay - (curTime - startTime);
      var context = this;
      var args = arguments;
      clearTimeout(timer);
      if (remaining <= 0) {
        func.apply(context, args);
        startTime = Date.now();
      } else {
        timer = setTimeout(() => {
          console.log("duplicate click");
        }, remaining);
      }
    };
  }
  //交换位置
  function exchangeView(a, b) {
    var ep1 = a.parentNode,
      ep2 = b.parentNode,
      index1 = Array.prototype.indexOf.call(ep1.children, a),
      index2 = Array.prototype.indexOf.call(ep2.children, b);
    ep2.insertBefore(a, ep2.children[index2]);
    ep1.insertBefore(b, ep1.children[index1]);
  }
  return common;
}
