function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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 { ajax, BizDialog, BizGlobalDataContext, IconFont } from '@zgfe/business-lib';
import { Button, Checkbox, Form, Input, message, Radio, Space, Tooltip } from 'antd';
import React, { createRef, useContext, useEffect, useState } from 'react';
import apis from "../apis";
import VisualContext from "./context";
import "./styles/createPanel.less";
import EventTrend from "./trend";
import { EndpointType, Platform } from "./types";
var prefix = "visual-workbench-create-panel";
var PageSelector = function PageSelector(_ref) {
  var value = _ref.value,
    onChange = _ref.onChange;
  var _useContext = useContext(VisualContext),
    currentPage = _useContext.currentPage;
  var _useState = useState(value || 'current'),
    _useState2 = _slicedToArray(_useState, 2),
    scope = _useState2[0],
    setScope = _useState2[1];
  useEffect(function () {
    if (onChange) onChange(scope);
  }, [scope]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Radio.Group, {
    onChange: function onChange(event) {
      setScope(event.target.value);
    },
    defaultValue: scope
  }, /*#__PURE__*/React.createElement(Space, {
    size: 48
  }, /*#__PURE__*/React.createElement(Radio, {
    value: "current"
  }, "\u5F53\u524D\u9875\u9762"), /*#__PURE__*/React.createElement(Radio, {
    value: "all"
  }, "\u6240\u6709\u9875\u9762"))), scope === 'all' ? null : /*#__PURE__*/React.createElement(Tooltip, {
    title: currentPage
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefix, "-detail")
  }, currentPage)));
};
var Rules = function Rules(_ref2) {
  var scope = _ref2.scope,
    value = _ref2.value,
    onChange = _ref2.onChange;
  var _useContext2 = useContext(VisualContext),
    currentElement = _useContext2.currentElement,
    setSimilarRules = _useContext2.setSimilarRules;
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    option = _useState4[0],
    setOption = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    inited = _useState6[0],
    setInited = _useState6[1];
  useEffect(function () {
    if (value) setOption(Object.keys(value).filter(function (key) {
      return value[key];
    }));
    setInited(true);
  }, []);
  useEffect(function () {
    if (!onChange) return;
    var data = {
      id: currentElement === null || currentElement === void 0 ? void 0 : currentElement.identification
    };
    if (option !== null && option !== void 0 && option.includes('index')) {
      data.index = currentElement === null || currentElement === void 0 ? void 0 : currentElement.zgSupViewIndex;
    }
    if (option !== null && option !== void 0 && option.includes('viewName')) {
      data.viewName = currentElement === null || currentElement === void 0 ? void 0 : currentElement.viewName;
    }
    if (setSimilarRules) setSimilarRules(data);
    onChange(data);
  }, [option]);
  if (!inited) return /*#__PURE__*/React.createElement(React.Fragment, null);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Checkbox.Group, {
    defaultValue: option,
    onChange: setOption
  }, /*#__PURE__*/React.createElement(Space, {
    wrap: true,
    size: 48
  }, currentElement !== null && currentElement !== void 0 && currentElement.viewName ? /*#__PURE__*/React.createElement(Checkbox, {
    value: "viewName"
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      wordBreak: 'break-all'
    }
  }, "\u5185\u5BB9")) : null, currentElement !== null && currentElement !== void 0 && currentElement.zgSupViewIndex ? /*#__PURE__*/React.createElement(Checkbox, {
    value: "index"
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      wordBreak: 'break-all'
    }
  }, "\u987A\u5E8F\u4E3A\u7B2C[", currentElement === null || currentElement === void 0 ? void 0 : currentElement.zgSupViewIndex, "]\u4F4D")) : null)), option !== null && option !== void 0 && option.length ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefix, "-detail")
  }, "\u73B0\u5728\u5B9A\u4E49\u7684\u662F", /*#__PURE__*/React.createElement("span", null, "[", scope === 'all' ? '所有页面' : '当前页面', "]"), "\u4E2D\uFF0C", currentElement !== null && currentElement !== void 0 && currentElement.viewName && option !== null && option !== void 0 && option.includes('viewName') ? /*#__PURE__*/React.createElement(React.Fragment, null, "\u9650\u5B9A\u5185\u5BB9\u4E3A", /*#__PURE__*/React.createElement("span", null, "[", currentElement.viewName, "]"), "\u7684\u5143\u7D20\uFF0C") : '', currentElement !== null && currentElement !== void 0 && currentElement.zgSupViewIndex && option !== null && option !== void 0 && option.includes('index') ? /*#__PURE__*/React.createElement(React.Fragment, null, "\u5728\u5217\u8868\u987A\u5E8F\u4E3A\u7B2C", /*#__PURE__*/React.createElement("span", null, "[", currentElement === null || currentElement === void 0 ? void 0 : currentElement.zgSupViewIndex, "]"), "\u4F4D\u7684\u5143\u7D20\uFF0C") : '', "\u82E5\u5143\u7D20", function () {
    var arr = [];
    if (currentElement !== null && currentElement !== void 0 && currentElement.viewName && option !== null && option !== void 0 && option.includes('viewName')) arr.push('内容');
    if (currentElement !== null && currentElement !== void 0 && currentElement.zgSupViewIndex && option !== null && option !== void 0 && option.includes('index')) arr.push('次序');
    return arr.join('或');
  }(), "\u6539\u53D8\uFF0C\u5C31\u4E0D\u518D\u7EE7\u7EED\u7EDF\u8BA1\u4E86") : /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefix, "-detail")
  }, "\u73B0\u5728\u5B9A\u4E49\u7684\u662F", /*#__PURE__*/React.createElement("span", null, "[", scope === 'all' ? '所有页面' : '当前页面', "]"), "\u4E2D\uFF0C\u6240\u6709\u540C\u7C7B\u5143\u7D20\u7684\u6570\u636E\u4E4B\u548C\uFF0C\u8FD9\u7EC4\u540C\u7C7B\u5143\u7D20\u5728\u754C\u9762\u4E0A\u5DF2\u88AB\u6807\u8BB0"));
};
export var CancelConfirm = function CancelConfirm(_ref3) {
  var onCancel = _ref3.onCancel,
    onOk = _ref3.onOk;
  var _useContext3 = useContext(VisualContext),
    createFormChanged = _useContext3.createFormChanged;
  if (!createFormChanged) {
    onOk();
    return /*#__PURE__*/React.createElement(React.Fragment, null);
  }
  return /*#__PURE__*/React.createElement(BizDialog, {
    title: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(IconFont, {
      type: "tishi1"
    }), "\u63D0\u793A"),
    open: true,
    onCancel: onCancel,
    onOk: onOk,
    className: "".concat(prefix, "-confirm")
  }, "\u53D6\u6D88\u5C06\u4E22\u5931\u5DF2\u7F16\u8F91\u7684\u5185\u5BB9\uFF0C\u662F\u5426\u786E\u5B9A\u53D6\u6D88");
};
var CreatePanel = function CreatePanel(_ref4) {
  var onHide = _ref4.onHide,
    onSaved = _ref4.onSaved;
  var formRef = /*#__PURE__*/createRef();
  var _useContext4 = useContext(BizGlobalDataContext),
    currentApp = _useContext4.currentApp;
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    loading = _useState8[0],
    setLoading = _useState8[1];
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    showConfirm = _useState10[0],
    setShowConfirm = _useState10[1];
  var _useState11 = useState(),
    _useState12 = _slicedToArray(_useState11, 2),
    scope = _useState12[0],
    setScope = _useState12[1];
  var _message$useMessage = message.useMessage(),
    _message$useMessage2 = _slicedToArray(_message$useMessage, 2),
    messageApi = _message$useMessage2[0],
    contextHolder = _message$useMessage2[1];
  var _useState13 = useState(),
    _useState14 = _slicedToArray(_useState13, 2),
    initTime = _useState14[0],
    setInitTime = _useState14[1];
  var _useContext5 = useContext(VisualContext),
    platform = _useContext5.platform,
    status = _useContext5.status,
    currentElement = _useContext5.currentElement,
    setCurrentElement = _useContext5.setCurrentElement,
    currentPage = _useContext5.currentPage,
    setEventList = _useContext5.setEventList,
    editEvent = _useContext5.editEvent,
    setEditEvent = _useContext5.setEditEvent,
    setCreateFormChanged = _useContext5.setCreateFormChanged,
    setSimilarRules = _useContext5.setSimilarRules;
  function onSave() {
    var _formRef$current;
    (_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.submit();
  }
  function onCancel() {
    if (setCurrentElement) setCurrentElement(undefined);
    if (setEditEvent) setEditEvent(undefined);
    if (setSimilarRules) setSimilarRules({});
    if (onHide) onHide();
  }
  function onSubmit(formData) {
    var data = {
      eventId: editEvent === null || editEvent === void 0 ? void 0 : editEvent.id,
      endpointType: platform === Platform.ios ? EndpointType.ios : EndpointType.android,
      appKey: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appKey,
      eventName: formData.name,
      eventType: currentElement ? 'click' : 'pv',
      pagePath: currentPage,
      elementConditionMap: _objectSpread({
        id: currentElement === null || currentElement === void 0 ? void 0 : currentElement.identification
      }, formData.rules),
      scope: formData.scope
    };
    setLoading(true);
    ajax(apis.create, {
      method: 'post',
      data: data
    }).then(function (res) {
      if (!res) return;
      if (setEventList) {
        if (editEvent) {
          var newItem = _objectSpread(_objectSpread({
            id: editEvent.id
          }, data), {}, {
            elementConditions: data.elementConditionMap
          });
          setEventList(function (list) {
            return list.map(function (item) {
              if (item.id === newItem.id) return newItem;
              return item;
            });
          });
        } else {
          var _newItem = _objectSpread(_objectSpread({
            id: res.data
          }, data), {}, {
            elementConditions: data.elementConditionMap
          });
          setEventList(function (list) {
            return [_newItem].concat(_toConsumableArray(list));
          });
        }
      }
      if (onSaved) onSaved();
      onCancel();
    }).catch(function (err) {
      console.error('创建/编辑可视化事件失败', err);
      messageApi.error('保存失败');
    }).finally(function () {
      setLoading(false);
    });
  }
  useEffect(function () {
    if (setCreateFormChanged) setCreateFormChanged(false);
    setInitTime(new Date().getTime());
  }, []);
  var initialValues;
  if (editEvent) {
    var _editEvent$elementCon, _editEvent$elementCon2;
    initialValues = {
      name: editEvent.eventName,
      scope: editEvent.scope,
      rules: {
        index: (_editEvent$elementCon = editEvent.elementConditions) === null || _editEvent$elementCon === void 0 ? void 0 : _editEvent$elementCon.index,
        viewName: (_editEvent$elementCon2 = editEvent.elementConditions) === null || _editEvent$elementCon2 === void 0 ? void 0 : _editEvent$elementCon2.viewName
      }
    };
  }
  return /*#__PURE__*/React.createElement("div", {
    className: prefix
  }, contextHolder, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefix, "-title")
  }, editEvent ? "".concat(!currentElement && editEvent ? '查看' : '编辑', "\u4E8B\u4EF6") : '创建事件', editEvent ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefix, "-defined-icon")
  }, "\u5DF2\u5B9A\u4E49") : null, /*#__PURE__*/React.createElement(IconFont, {
    type: "qingchu",
    onClick: onCancel
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefix, "-content")
  }, /*#__PURE__*/React.createElement(Form, {
    layout: "vertical",
    onFinish: onSubmit,
    onValuesChange: function onValuesChange() {
      if (new Date().getTime() - (initTime || 0) > 50 && setCreateFormChanged) setCreateFormChanged(true);
    },
    ref: formRef,
    initialValues: initialValues,
    autoComplete: "off"
  }, /*#__PURE__*/React.createElement(Form.Item, {
    label: currentElement ? '事件名称' : '页面名称',
    name: "name",
    rules: [{
      required: true,
      // 长度限制20个字符，不可输入空格，可输入中英文、数字、下划线、中划线
      pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9-]{1,20}$/,
      message: '请输入1-20个字符，支持中英文、数字、下划线、中划线'
    }]
  }, /*#__PURE__*/React.createElement(Input, {
    allowClear: true,
    placeholder: "\u8BF7\u8F93\u5165".concat(currentElement ? '事件' : '页面', "\u540D\u79F0"),
    autoFocus: true,
    disabled: editEvent ? true : false
  })), currentElement ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u6240\u5C5E\u9875\u9762",
    name: "scope"
  }, /*#__PURE__*/React.createElement(PageSelector, {
    onChange: function onChange(v) {
      setScope(v);
    }
  })), !currentElement.viewName && !currentElement.zgSupViewIndex ? null : /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u9650\u5B9A\u6761\u4EF6",
    name: "rules"
  }, /*#__PURE__*/React.createElement(Rules, {
    scope: scope
  }))) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u8DEF\u5F84"
  }, /*#__PURE__*/React.createElement(Input, {
    value: currentPage,
    disabled: true
  }))), currentElement ? /*#__PURE__*/React.createElement(Form.Item, {
    label: currentElement ? '最近7天元素点击情况' : '最近7天页面访问情况'
  }, /*#__PURE__*/React.createElement(EventTrend, null)) : null)), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefix, "-foot")
  }, /*#__PURE__*/React.createElement(Space, {
    size: 16
  }, /*#__PURE__*/React.createElement(Button, {
    onClick: function onClick() {
      setShowConfirm(true);
    }
  }, "\u53D6\u6D88"), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    onClick: onSave,
    loading: loading,
    disabled: status === 'disconnected'
  }, !currentElement && editEvent ? '确定' : '保存'))), showConfirm && /*#__PURE__*/React.createElement(CancelConfirm, {
    onCancel: function onCancel() {
      return setShowConfirm(false);
    },
    onOk: function onOk() {
      return onCancel();
    }
  }));
};
export default CreatePanel;