function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { BizGlobalDataContext, IconFont, SocketClient } from '@zgfe/business-lib';
import { Button, notification, Space } from 'antd';
import React, { useContext, useEffect, useRef, useState } from 'react';
import Controller from "./canvasController";
import VisualContext from "./context";
import { CancelConfirm } from "./createPanel";
import "./styles/mobile.less";
import { classPrefix } from "./types";
var Mobile = function Mobile(_ref) {
  var onDefinePv = _ref.onDefinePv;
  var _useState = useState(),
    _useState2 = _slicedToArray(_useState, 2),
    client = _useState2[0],
    setClient = _useState2[1];
  var _useContext = useContext(BizGlobalDataContext),
    currentApp = _useContext.currentApp;
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    pageData = _useState4[0],
    setPageData = _useState4[1];
  var _useState5 = useState(100),
    _useState6 = _slicedToArray(_useState5, 2),
    scale = _useState6[0],
    setScale = _useState6[1];
  var _useState7 = useState(true),
    _useState8 = _slicedToArray(_useState7, 2),
    showControl = _useState8[0],
    setShowControl = _useState8[1];
  var mobileRef = useRef();
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    showConfirm = _useState10[0],
    setShowConfirm = _useState10[1];
  var _useState11 = useState(),
    _useState12 = _slicedToArray(_useState11, 2),
    tempEvent = _useState12[0],
    setTempEvent = _useState12[1];
  var _useState13 = useState(),
    _useState14 = _slicedToArray(_useState13, 2),
    tempElement = _useState14[0],
    setTempElement = _useState14[1];
  var _useState15 = useState(false),
    _useState16 = _slicedToArray(_useState15, 2),
    connected = _useState16[0],
    setConnected = _useState16[1];
  var _useContext2 = useContext(VisualContext),
    currentElement = _useContext2.currentElement,
    setCurrentElement = _useContext2.setCurrentElement,
    setEditEvent = _useContext2.setEditEvent,
    setCurrentPage = _useContext2.setCurrentPage,
    currentPage = _useContext2.currentPage,
    similarRules = _useContext2.similarRules,
    socketUrl = _useContext2.socketUrl,
    eventList = _useContext2.eventList,
    initClient = _useContext2.initClient,
    status = _useContext2.status,
    setStatus = _useContext2.setStatus;
  function onPageData(data) {
    setPageData(data);
    if (setCurrentPage) setCurrentPage(data === null || data === void 0 ? void 0 : data.pageUrl);
    if (setStatus) setStatus('success');
  }
  function onOnline() {
    // 对端上线后即请求最新页面数据
    client === null || client === void 0 ? void 0 : client.emit('fetchPageData');
    if (setStatus) setStatus('success');
  }
  function onOffline() {
    if (setStatus) setStatus('disconnected');
  }
  function onExist() {
    notification.error({
      message: '已有其他客户端在对当前应用进行可视化埋点'
    });
  }
  function onTrigger(event) {
    notification.info({
      message: "\u89E6\u53D1\u4E8B\u4EF6: ".concat(event === null || event === void 0 ? void 0 : event.eventName),
      duration: 2
    });
  }
  function initSocket() {
    var socket = new SocketClient("".concat(socketUrl || "".concat(location.origin.replace('http', 'ws')), "/eventtracking/ws"), currentApp === null || currentApp === void 0 ? void 0 : currentApp.appKey, {
      appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.id,
      origin: 3
    });
    socket.openLog(true);
    setClient(socket);
    if (initClient) initClient(socket);
    socket.on('pageData', onPageData);
    socket.on('online', onOnline);
    socket.on('offline', onOffline);
    socket.on('exist', onExist);
    socket.on('trigger', onTrigger);
    socket.onError(function (err) {
      console.error('socket error', err);
      initSocket();
    });
    socket.onConnected(function () {
      setConnected(true);
      socket.emit('fetchPageData');
    });
  }
  function getNum(num) {
    return scale / 100 * Number(num || 0);
  }
  function onClickElement(defined, item) {
    setTempElement(item);
    setTempEvent(defined);
    if (currentElement) {
      setShowConfirm(true);
    } else {
      if (setCurrentElement) setCurrentElement(item);
      if (setEditEvent) setEditEvent(defined);
    }
  }
  useEffect(function () {
    return function () {
      client === null || client === void 0 ? void 0 : client.destroy();
    };
  }, [client]);
  useEffect(function () {
    initSocket();
  }, []);
  var pv = eventList.find(function (item) {
    return item.eventType === 'pv' && item.pagePath === currentPage;
  });
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-center"),
    key: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appKey
  }, connected ? /*#__PURE__*/React.createElement(Controller, {
    client: client,
    key: pageData === null || pageData === void 0 ? void 0 : pageData.key,
    container: mobileRef,
    status: status,
    phoneSize: {
      width: pageData === null || pageData === void 0 ? void 0 : pageData.screenSize.w,
      height: pageData === null || pageData === void 0 ? void 0 : pageData.screenSize.h
    },
    onChangeShowControl: setShowControl,
    onChange: setScale
  }) : null, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-mobile"),
    ref: mobileRef
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-tocanvas"),
    style: {
      height: "".concat(getNum(pageData === null || pageData === void 0 ? void 0 : pageData.screenSize.h), "px"),
      width: "".concat(getNum(pageData === null || pageData === void 0 ? void 0 : pageData.screenSize.w), "px")
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-canvas"),
    style: {
      height: "".concat(getNum(pageData === null || pageData === void 0 ? void 0 : pageData.screenSize.h), "px"),
      width: "".concat(getNum(pageData === null || pageData === void 0 ? void 0 : pageData.screenSize.w), "px")
    }
  }, /*#__PURE__*/React.createElement("img", {
    src: "data:image/png;base64,".concat(pageData === null || pageData === void 0 ? void 0 : pageData.bgImg),
    style: {
      height: "".concat(getNum(pageData === null || pageData === void 0 ? void 0 : pageData.screenSize.h), "px"),
      width: "".concat(getNum(pageData === null || pageData === void 0 ? void 0 : pageData.screenSize.w), "px")
    }
  }), pageData === null || pageData === void 0 ? void 0 : pageData.allBtns.map(function (item, index) {
    var defined = eventList.find(function (event) {
      var _event$elementConditi;
      return ((_event$elementConditi = event.elementConditions) === null || _event$elementConditi === void 0 ? void 0 : _event$elementConditi.id) === item.identification && (!event.elementConditions.zgSupViewIndex || Number(event.elementConditions.zgSupViewIndex) === item.zgSupViewIndex) && (!event.elementConditions.viewName || event.elementConditions.viewName === item.viewName);
    });
    return /*#__PURE__*/React.createElement("div", {
      key: "".concat(item.identification, "-").concat(index),
      className: "element ".concat(defined ? 'defined' : 'definable', " ").concat(currentElement === item ? 'defining' : '', " ").concat(function () {
        var similar = true;
        var keys = Object.keys(similarRules || {});
        if (keys.length === 0) return false;
        keys.forEach(function (rule) {
          var map = {
            id: 'identification',
            index: 'zgSupViewIndex'
          };
          if (similarRules[rule] !== item[map[rule]]) {
            similar = false;
          }
        });
        return similar;
      }() ? 'defining' : ''),
      onClick: onClickElement.bind(undefined, defined, item),
      style: {
        borderColor: showControl ? undefined : 'rgba(0,0,0,0)',
        background: showControl ? undefined : 'rgba(0,0,0,0)',
        width: "".concat(getNum(item.location.w), "px"),
        height: "".concat(getNum(item.location.h), "px"),
        position: 'absolute',
        top: "".concat(getNum(item.location.y), "px"),
        left: "".concat(getNum(item.location.x), "px"),
        zIndex: item.zgZIndexLevel
      }
    });
  })))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-footer")
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(classPrefix, "-footer-type ").concat(pv ? 'pv-defined' : '')
  }, pv ? '已定义' : '未定义'), /*#__PURE__*/React.createElement("span", {
    className: "".concat(classPrefix, "-footer-label")
  }, "\u9875\u9762\u6D4F\u89C8\u4E8B\u4EF6\uFF1A"), /*#__PURE__*/React.createElement("span", {
    className: "".concat(classPrefix, "-footer-path")
  }, pageData === null || pageData === void 0 ? void 0 : pageData.pageUrl), /*#__PURE__*/React.createElement(Button, {
    onClick: onDefinePv === null || onDefinePv === void 0 ? void 0 : onDefinePv.bind(undefined, pv)
  }, /*#__PURE__*/React.createElement(Space, null, !pv && /*#__PURE__*/React.createElement(IconFont, {
    type: "zengjia"
  }), pv ? '编辑事件' : '定义事件'))), showConfirm && /*#__PURE__*/React.createElement(CancelConfirm, {
    onOk: function onOk() {
      if (setCurrentElement) setCurrentElement(tempElement);
      if (setEditEvent) setEditEvent(tempEvent);
      setShowConfirm(false);
    },
    onCancel: function onCancel() {
      setShowConfirm(false);
    }
  }));
};
export default Mobile;