function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useState, useEffect } from 'react';
import { Switch, Checkbox, Select, Input, Popover, Typography } from 'antd';
import { HolderOutlined, GlobalOutlined } from '@ant-design/icons';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import classNames from 'classnames';
import { locales } from '@pisell/utils';
import useEngineContext from "../../../../../hooks/useEngineContext";
import localeTexts from "./locales";
import "./CollectInfo.less";
var TextArea = Input.TextArea;
var Title = Typography.Title,
  Paragraph = Typography.Paragraph;

// 默认字段数据
var DEFAULT_ACCOUNT_FIELDS = [{
  id: 'phone',
  name: 'collect.info.field.phone',
  description: 'collect.info.field.phone.desc',
  checked: true,
  required: 'optional'
}, {
  id: 'email',
  name: 'collect.info.field.email',
  description: 'collect.info.field.email.desc',
  checked: false,
  required: 'optional'
}, {
  id: 'avatar',
  name: 'collect.info.field.avatar',
  description: '',
  checked: false,
  required: 'optional'
}, {
  id: 'nickname',
  name: 'collect.info.field.nickname',
  description: '',
  checked: true,
  required: 'optional'
}, {
  id: 'gender',
  name: 'collect.info.field.gender',
  description: '',
  checked: true,
  required: 'optional'
}, {
  id: 'name',
  name: 'collect.info.field.name',
  description: '',
  checked: false,
  required: 'required'
}];

// 默认客户表单数据
var DEFAULT_CUSTOMER_FORMS = [{
  id: 'waiver-test-1',
  name: 'waivertest-1',
  waiver: 'skip'
}, {
  id: 'minor',
  name: 'Minor(未成年人)简体中文',
  waiver: 'skip'
}];

// 默认翻译值
var DEFAULT_TRANSLATION = {
  en: 'Please provide the following account information to help us serve you better. Make sure your information is accurate.111',
  'zh-CN': '请提供以下账户信息以帮助我们更好地为您服务。请确保您的信息准确。111',
  'zh-HK': '請提供以下賬戶信息以幫助我們更好地為您服務。請確保您的信息準確。111',
  ja: '以下のアカウント情報を提供してください。正確な情報を確認してください。111',
  pt: 'Por favor, forneça as seguintes informações da conta para nos ajudar a melhorar o nosso atendimento. Certifique-se de que suas informações são precisas.111',
  original: 'Please provide the following account information to help us serve you better. Make sure your information is accurate.111'
};

// i18n 翻译输入组件

var TranslationInput = function TranslationInput(_ref) {
  var _ref$value = _ref.value,
    value = _ref$value === void 0 ? DEFAULT_TRANSLATION : _ref$value,
    onChange = _ref.onChange,
    disabled = _ref.disabled,
    placeholder = _ref.placeholder;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var languageConfig = [{
    key: 'original',
    label: 'Original'
  }, {
    key: 'en',
    label: 'English'
  }, {
    key: 'zh-CN',
    label: '简体中文'
  }, {
    key: 'zh-HK',
    label: '繁體中文'
  }];
  var hasAnyTranslation = function hasAnyTranslation() {
    if (!value) {
      return false;
    }
    return Object.entries(value).some(function (_ref2) {
      var _ref3 = _slicedToArray(_ref2, 2),
        key = _ref3[0],
        val = _ref3[1];
      return key !== 'original' && val;
    });
  };
  var handleInputChange = function handleInputChange(lang) {
    return function (e) {
      var newValue = _objectSpread(_objectSpread({}, value), {}, _defineProperty({}, lang, e.target.value));
      onChange === null || onChange === void 0 || onChange(newValue);
    };
  };
  var content = /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-translation-popover",
    style: {
      display: 'flex',
      flexDirection: 'column',
      gap: '16px'
    }
  }, languageConfig.map(function (_ref4) {
    var key = _ref4.key,
      label = _ref4.label;
    return /*#__PURE__*/React.createElement("div", {
      key: key,
      className: "pisell-collect-info-translation-field"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-collect-info-translation-label"
    }, label), /*#__PURE__*/React.createElement(TextArea, {
      value: (value === null || value === void 0 ? void 0 : value[key]) || '',
      onChange: handleInputChange(key),
      rows: 3,
      allowClear: true
    }));
  }));
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-translation-wrapper"
  }, /*#__PURE__*/React.createElement(TextArea, {
    value: (value === null || value === void 0 ? void 0 : value.original) || '',
    onChange: handleInputChange('original'),
    placeholder: placeholder,
    disabled: disabled,
    className: "pisell-collect-info-translation-input",
    rows: 3
  }), /*#__PURE__*/React.createElement(Popover, {
    content: content,
    trigger: "click",
    open: open,
    onOpenChange: function onOpenChange(open) {
      if (disabled) {
        return;
      }
      setOpen(open);
    },
    placement: "bottom"
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-collect-info-translation-icon-wrapper', {
      'has-translation': hasAnyTranslation(),
      disabled: disabled
    })
  }, /*#__PURE__*/React.createElement(GlobalOutlined, {
    className: "pisell-collect-info-translation-icon"
  }))));
};

// 可排序的字段项

var SortableFieldItem = function SortableFieldItem(_ref5) {
  var field = _ref5.field,
    onCheckChange = _ref5.onCheckChange,
    onRequiredChange = _ref5.onRequiredChange;
  var _useSortable = useSortable({
      id: field.id
    }),
    attributes = _useSortable.attributes,
    listeners = _useSortable.listeners,
    setNodeRef = _useSortable.setNodeRef,
    transform = _useSortable.transform,
    transition = _useSortable.transition,
    isDragging = _useSortable.isDragging;
  var style = {
    transform: CSS.Transform.toString(transform),
    transition: transition
  };
  return /*#__PURE__*/React.createElement("div", {
    ref: setNodeRef,
    style: style,
    className: classNames('pisell-collect-info-field-item', {
      'pisell-collect-info-dragging': isDragging
    })
  }, /*#__PURE__*/React.createElement("div", _extends({
    className: "pisell-collect-info-field-drag"
  }, attributes, listeners), /*#__PURE__*/React.createElement(HolderOutlined, null)), /*#__PURE__*/React.createElement(Checkbox, {
    className: "pisell-collect-info-field-checkbox",
    checked: field.checked,
    onChange: function onChange(e) {
      return onCheckChange(e.target.checked);
    }
  }), /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-field-content"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-field-name"
  }, locales.getText(field.name)), field.description && /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-field-description"
  }, locales.getText(field.description))), /*#__PURE__*/React.createElement(Select, {
    className: "pisell-collect-info-field-select",
    value: field.required,
    onChange: onRequiredChange,
    options: [{
      label: locales.getText('collect.info.optional'),
      value: 'optional'
    }, {
      label: locales.getText('collect.info.required'),
      value: 'required'
    }]
  }));
};

// 可排序的表单项

var SortableFormItem = function SortableFormItem(_ref6) {
  var form = _ref6.form,
    onCheckChange = _ref6.onCheckChange,
    onWaiverChange = _ref6.onWaiverChange;
  var _useSortable2 = useSortable({
      id: form.id
    }),
    attributes = _useSortable2.attributes,
    listeners = _useSortable2.listeners,
    setNodeRef = _useSortable2.setNodeRef,
    transform = _useSortable2.transform,
    transition = _useSortable2.transition,
    isDragging = _useSortable2.isDragging;
  var style = {
    transform: CSS.Transform.toString(transform),
    transition: transition
  };
  return /*#__PURE__*/React.createElement("div", {
    ref: setNodeRef,
    style: style,
    className: classNames('pisell-collect-info-form-item', {
      'pisell-collect-info-dragging': isDragging
    })
  }, /*#__PURE__*/React.createElement("div", _extends({
    className: "pisell-collect-info-form-drag"
  }, attributes, listeners), /*#__PURE__*/React.createElement(HolderOutlined, null)), /*#__PURE__*/React.createElement(Checkbox, {
    className: "pisell-collect-info-form-checkbox",
    onChange: function onChange(e) {
      return onCheckChange(e.target.checked);
    }
  }), /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-form-name"
  }, form.name), /*#__PURE__*/React.createElement(Select, {
    className: "pisell-collect-info-form-select",
    value: form.waiver,
    onChange: onWaiverChange,
    options: [{
      label: locales.getText('collect.info.skip'),
      value: 'skip'
    }, {
      label: locales.getText('collect.info.disallow.skip'),
      value: 'required'
    }]
  }));
};

// 主组件
var CollectInfo = function CollectInfo(_ref7) {
  var _context$engine, _value$enableCollectI, _value$collectAccount, _value$allowSkip;
  var className = _ref7.className,
    style = _ref7.style,
    value = _ref7.value,
    onChange = _ref7.onChange;
  var context = useEngineContext();
  var currentLocale = (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || 'en';

  // 初始化 locales
  locales.init(localeTexts, currentLocale);
  var _useState3 = useState((_value$enableCollectI = value === null || value === void 0 ? void 0 : value.enableCollectInfo) !== null && _value$enableCollectI !== void 0 ? _value$enableCollectI : true),
    _useState4 = _slicedToArray(_useState3, 2),
    enableCollectInfo = _useState4[0],
    setEnableCollectInfo = _useState4[1];
  var _useState5 = useState((_value$collectAccount = value === null || value === void 0 ? void 0 : value.collectAccountInfo) !== null && _value$collectAccount !== void 0 ? _value$collectAccount : true),
    _useState6 = _slicedToArray(_useState5, 2),
    collectAccountInfo = _useState6[0],
    setCollectAccountInfo = _useState6[1];
  var _useState7 = useState((_value$allowSkip = value === null || value === void 0 ? void 0 : value.allowSkip) !== null && _value$allowSkip !== void 0 ? _value$allowSkip : false),
    _useState8 = _slicedToArray(_useState7, 2),
    allowSkip = _useState8[0],
    setAllowSkip = _useState8[1];
  var _useState9 = useState((value === null || value === void 0 ? void 0 : value.promptMessage) || DEFAULT_TRANSLATION),
    _useState10 = _slicedToArray(_useState9, 2),
    promptMessage = _useState10[0],
    setPromptMessage = _useState10[1];
  var _useState11 = useState((value === null || value === void 0 ? void 0 : value.accountFields) || DEFAULT_ACCOUNT_FIELDS),
    _useState12 = _slicedToArray(_useState11, 2),
    accountFields = _useState12[0],
    setAccountFields = _useState12[1];
  var _useState13 = useState((value === null || value === void 0 ? void 0 : value.customerForms) || DEFAULT_CUSTOMER_FORMS),
    _useState14 = _slicedToArray(_useState13, 2),
    customerForms = _useState14[0],
    setCustomerForms = _useState14[1];

  // 拖动排序传感器
  var sensors = useSensors(useSensor(PointerSensor, {
    activationConstraint: {
      distance: 8
    }
  }), useSensor(KeyboardSensor, {
    coordinateGetter: sortableKeyboardCoordinates
  }));

  // 同步到外部
  useEffect(function () {
    var newValue = {
      enableCollectInfo: enableCollectInfo,
      collectAccountInfo: collectAccountInfo,
      allowSkip: allowSkip,
      promptMessage: promptMessage,
      accountFields: accountFields,
      customerForms: customerForms
    };
    onChange === null || onChange === void 0 || onChange(newValue);
  }, [enableCollectInfo, collectAccountInfo, allowSkip, promptMessage, accountFields, customerForms, onChange]);

  // 字段拖动结束
  var handleFieldDragEnd = function handleFieldDragEnd(event) {
    var active = event.active,
      over = event.over;
    if (over && active.id !== over.id) {
      setAccountFields(function (items) {
        var oldIndex = items.findIndex(function (item) {
          return item.id === active.id;
        });
        var newIndex = items.findIndex(function (item) {
          return item.id === over.id;
        });
        return arrayMove(items, oldIndex, newIndex);
      });
    }
  };

  // 表单拖动结束
  var handleFormDragEnd = function handleFormDragEnd(event) {
    var active = event.active,
      over = event.over;
    if (over && active.id !== over.id) {
      setCustomerForms(function (items) {
        var oldIndex = items.findIndex(function (item) {
          return item.id === active.id;
        });
        var newIndex = items.findIndex(function (item) {
          return item.id === over.id;
        });
        return arrayMove(items, oldIndex, newIndex);
      });
    }
  };

  // 更新字段
  var handleFieldCheckChange = function handleFieldCheckChange(fieldId, checked) {
    setAccountFields(function (fields) {
      return fields.map(function (f) {
        return f.id === fieldId ? _objectSpread(_objectSpread({}, f), {}, {
          checked: checked
        }) : f;
      });
    });
  };
  var handleFieldRequiredChange = function handleFieldRequiredChange(fieldId, required) {
    setAccountFields(function (fields) {
      return fields.map(function (f) {
        return f.id === fieldId ? _objectSpread(_objectSpread({}, f), {}, {
          required: required
        }) : f;
      });
    });
  };

  // 更新表单
  var handleFormCheckChange = function handleFormCheckChange(formId, checked) {
    console.log('Form check change:', formId, checked);
  };
  var handleFormWaiverChange = function handleFormWaiverChange(formId, waiver) {
    setCustomerForms(function (forms) {
      return forms.map(function (f) {
        return f.id === formId ? _objectSpread(_objectSpread({}, f), {}, {
          waiver: waiver
        }) : f;
      });
    });
  };

  // 如果未开启收集客户信息，不展示任何内容
  if (!enableCollectInfo) {
    return /*#__PURE__*/React.createElement("div", {
      className: classNames('pisell-collect-info', className),
      style: style
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-collect-info-layout"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-collect-info-header"
    }, /*#__PURE__*/React.createElement(Title, {
      level: 4,
      className: "pisell-collect-info-title"
    }, locales.getText('page.setting.login.form.menu.title')), /*#__PURE__*/React.createElement(Paragraph, {
      className: "pisell-collect-info-description"
    }, locales.getText('page.setting.login.form.menu.desc'))), /*#__PURE__*/React.createElement("div", {
      className: "pisell-collect-info-content"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-collect-info-section"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-collect-info-switch-item"
    }, /*#__PURE__*/React.createElement("span", {
      className: "pisell-collect-info-switch-label"
    }, locales.getText('collect.info.enable')), /*#__PURE__*/React.createElement(Switch, {
      checked: enableCollectInfo,
      onChange: setEnableCollectInfo
    }))))));
  }
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-collect-info', className),
    style: style
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-layout"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-header"
  }, /*#__PURE__*/React.createElement(Title, {
    level: 4,
    className: "pisell-collect-info-title"
  }, locales.getText('page.setting.login.form.menu.title')), /*#__PURE__*/React.createElement(Paragraph, {
    className: "pisell-collect-info-description"
  }, locales.getText('page.setting.login.form.menu.desc'))), /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-content"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-section"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-switch-item"
  }, /*#__PURE__*/React.createElement("span", {
    className: "pisell-collect-info-switch-label"
  }, locales.getText('collect.info.enable')), /*#__PURE__*/React.createElement(Switch, {
    checked: enableCollectInfo,
    onChange: setEnableCollectInfo
  }))), collectAccountInfo && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-section"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-switch-item"
  }, /*#__PURE__*/React.createElement("span", {
    className: "pisell-collect-info-switch-label"
  }, locales.getText('collect.info.allow.skip')), /*#__PURE__*/React.createElement(Switch, {
    checked: allowSkip,
    onChange: setAllowSkip
  }))), /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-prompt"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-prompt-label"
  }, locales.getText('collect.info.prompt')), /*#__PURE__*/React.createElement(TranslationInput, {
    value: promptMessage,
    onChange: setPromptMessage,
    placeholder: locales.getText('collect.info.prompt')
  })), /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-section"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-fields-header"
  }, /*#__PURE__*/React.createElement("span", {
    className: "pisell-collect-info-fields-title"
  }, locales.getText('collect.info.fields'))), /*#__PURE__*/React.createElement(DndContext, {
    sensors: sensors,
    collisionDetection: closestCenter,
    onDragEnd: handleFieldDragEnd
  }, /*#__PURE__*/React.createElement(SortableContext, {
    items: accountFields.map(function (f) {
      return f.id;
    }),
    strategy: verticalListSortingStrategy
  }, accountFields.map(function (field) {
    return /*#__PURE__*/React.createElement(SortableFieldItem, {
      key: field.id,
      field: field,
      onCheckChange: function onCheckChange(checked) {
        return handleFieldCheckChange(field.id, checked);
      },
      onRequiredChange: function onRequiredChange(required) {
        return handleFieldRequiredChange(field.id, required);
      }
    });
  }))))), /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-section"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-collect-info-forms-header"
  }, /*#__PURE__*/React.createElement("span", {
    className: "pisell-collect-info-forms-title"
  }, locales.getText('collect.info.customer.form'))), /*#__PURE__*/React.createElement(DndContext, {
    sensors: sensors,
    collisionDetection: closestCenter,
    onDragEnd: handleFormDragEnd
  }, /*#__PURE__*/React.createElement(SortableContext, {
    items: customerForms.map(function (f) {
      return f.id;
    }),
    strategy: verticalListSortingStrategy
  }, customerForms.map(function (form) {
    return /*#__PURE__*/React.createElement(SortableFormItem, {
      key: form.id,
      form: form,
      onCheckChange: function onCheckChange(checked) {
        return handleFormCheckChange(form.id, checked);
      },
      onWaiverChange: function onWaiverChange(waiver) {
        return handleFormWaiverChange(form.id, waiver);
      }
    });
  })))))));
};
export default CollectInfo;