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 _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, { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { Button, Form, Input } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import { locales } from '@pisell/utils';
import localeTexts from "./locales";
import useEngineContext from "../../../../../hooks/useEngineContext";
import { BaseTranslation, FormItemUpload } from '@pisell/materials';
import "./PageSettingItem.less";
var PageSettingItem = /*#__PURE__*/forwardRef(function (_ref, ref) {
  var _context$engine, _appHelper$constants, _appHelper$constants2;
  var className = _ref.className,
    style = _ref.style,
    value = _ref.value,
    onChange = _ref.onChange,
    _ref$showImageUpload = _ref.showImageUpload,
    showImageUpload = _ref$showImageUpload === void 0 ? true : _ref$showImageUpload;
  var context = useEngineContext();
  var appHelper = context === null || context === void 0 ? void 0 : context.appHelper;
  locales.init(localeTexts, (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');
  var _Form$useForm = Form.useForm(),
    _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
    form = _Form$useForm2[0];

  // 暴露校验方法给父组件
  useImperativeHandle(ref, function () {
    return {
      validateFields: function validateFields() {
        return form.validateFields();
      }
    };
  });

  // 初始化表单值，只在value发生实质性变化时更新
  var previousValueRef = useRef(value);
  useEffect(function () {
    // 检查value是否发生了实质性变化
    var prevValue = previousValueRef.current;
    var hasValueChanged = (value === null || value === void 0 ? void 0 : value.backgroundImage) !== (prevValue === null || prevValue === void 0 ? void 0 : prevValue.backgroundImage) || JSON.stringify(value === null || value === void 0 ? void 0 : value.termsConditions) !== JSON.stringify(prevValue === null || prevValue === void 0 ? void 0 : prevValue.termsConditions);
    if (hasValueChanged) {
      var defaultName = {
        en: '',
        'zh-CN': '',
        'zh-HK': '',
        ja: '',
        pt: '',
        original: ''
      };
      form.setFieldsValue({
        backgroundImage: (value === null || value === void 0 ? void 0 : value.backgroundImage) || '',
        termsConditions: (value === null || value === void 0 ? void 0 : value.termsConditions) || [{
          name: {
            en: 'Terms of Service',
            'zh-CN': '服务条款',
            'zh-HK': '服務條款',
            original: 'Terms of Service',
            ja: '利用規約',
            pt: 'Termos de Serviço'
          },
          url: 'https://example.com/terms'
        }, {
          name: {
            en: 'Privacy Policy',
            'zh-CN': '隐私政策',
            'zh-HK': '隱私政策',
            original: 'Privacy Policy',
            ja: 'プライバシーポリシー',
            pt: 'Política de Privacidade'
          },
          url: 'https://example.com/privacy'
        }]
      });

      // 更新ref值
      previousValueRef.current = value;
    }
  }, [value, form]);

  // 表单值变化时触发
  var handleFormChange = function handleFormChange() {
    var formValues = form.getFieldsValue();
    var newValue = {
      backgroundImage: formValues.backgroundImage || '',
      termsConditions: formValues.termsConditions || []
    };
    onChange === null || onChange === void 0 || onChange(newValue);
  };
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('page-setting-item', className),
    style: style
  }, /*#__PURE__*/React.createElement(Form, {
    form: form,
    onValuesChange: handleFormChange
  }, showImageUpload && /*#__PURE__*/React.createElement("div", {
    className: "page-setting-item-section page-setting-item-background"
  }, /*#__PURE__*/React.createElement("div", {
    className: "page-setting-item-section-title"
  }, locales.getText('page.setting.item.background.title')), /*#__PURE__*/React.createElement(Form.Item, {
    name: "backgroundImage",
    style: {
      margin: 0
    }
  }, /*#__PURE__*/React.createElement(FormItemUpload, {
    renderMode: "edit",
    mediaUploadUrl: appHelper === null || appHelper === void 0 || (_appHelper$constants = appHelper.constants) === null || _appHelper$constants === void 0 ? void 0 : _appHelper$constants.mediaUploadUrl,
    getHeaders: appHelper === null || appHelper === void 0 || (_appHelper$constants2 = appHelper.constants) === null || _appHelper$constants2 === void 0 ? void 0 : _appHelper$constants2.getHeaders,
    maxCount: 1,
    multiple: false,
    enableCustomType: true,
    customType: ['.png', '.jpg', '.jpeg'],
    allowPreview: true
  }))), /*#__PURE__*/React.createElement("div", {
    className: "page-setting-item-section page-setting-item-terms"
  }, /*#__PURE__*/React.createElement("div", {
    className: "page-setting-item-section-header"
  }, /*#__PURE__*/React.createElement("div", {
    className: "page-setting-item-section-title"
  }, locales.getText('page.setting.item.terms.title')), /*#__PURE__*/React.createElement("div", {
    className: "page-setting-item-section-subtitle"
  }, locales.getText('page.setting.item.terms.subtitle'))), /*#__PURE__*/React.createElement("div", {
    className: "page-setting-item-terms-table"
  }, /*#__PURE__*/React.createElement("div", {
    className: "page-setting-item-terms-table-header"
  }, /*#__PURE__*/React.createElement("div", null, locales.getText('page.setting.item.terms.table.name')), /*#__PURE__*/React.createElement("div", null, locales.getText('page.setting.item.terms.table.url')), /*#__PURE__*/React.createElement("div", {
    style: {
      textAlign: 'center'
    }
  }, locales.getText('page.setting.item.terms.table.action'))), /*#__PURE__*/React.createElement(Form.List, {
    name: "termsConditions"
  }, function (fields, _ref2) {
    var add = _ref2.add,
      remove = _ref2.remove;
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      className: "page-setting-item-terms-table-body"
    }, fields.map(function (field) {
      return /*#__PURE__*/React.createElement("div", {
        key: field.key,
        className: "page-setting-item-terms-table-row"
      }, /*#__PURE__*/React.createElement("div", {
        className: "page-setting-item-terms-table-cell"
      }, /*#__PURE__*/React.createElement(Form.Item, _extends({}, field, {
        name: [field.name, 'name'],
        validateTrigger: ['onChange', 'onBlur'],
        rules: [{
          validator: function validator(_, value) {
            if (!value || !value.original || !value.original.trim()) {
              return Promise.reject(new Error(locales.getText('page.setting.item.terms.error.name.required')));
            }
            return Promise.resolve();
          }
        }],
        style: {
          margin: 0,
          flex: 1
        }
      }), /*#__PURE__*/React.createElement(BaseTranslation, {
        renderMode: "edit",
        placeholder: locales.getText('page.setting.item.terms.table.name.placeholder')
      }))), /*#__PURE__*/React.createElement("div", {
        className: "page-setting-item-terms-table-cell"
      }, /*#__PURE__*/React.createElement(Form.Item, _extends({}, field, {
        name: [field.name, 'url'],
        validateTrigger: ['onChange', 'onBlur'],
        rules: [{
          validator: function validator(_, value) {
            if (!value || !value.trim()) {
              return Promise.reject(new Error(locales.getText('page.setting.item.terms.error.url.required')));
            }
            return Promise.resolve();
          }
        }, {
          type: 'url',
          message: locales.getText('page.setting.item.terms.error.url.invalid')
        }],
        style: {
          margin: 0,
          flex: 1
        }
      }), /*#__PURE__*/React.createElement(Input, {
        placeholder: locales.getText('page.setting.item.terms.table.url.placeholder')
      }))), /*#__PURE__*/React.createElement("div", {
        className: "page-setting-item-terms-table-actions"
      }, /*#__PURE__*/React.createElement(Button, {
        type: "text",
        danger: true,
        icon: /*#__PURE__*/React.createElement(DeleteOutlined, null),
        size: "small",
        onClick: function onClick() {
          return remove(field.name);
        }
      })));
    })), /*#__PURE__*/React.createElement("div", {
      className: "page-setting-item-terms-add-row"
    }, /*#__PURE__*/React.createElement(Button, {
      type: "default",
      icon: /*#__PURE__*/React.createElement(PlusOutlined, null),
      onClick: function onClick() {
        return add({
          name: {
            en: '',
            'zh-CN': '',
            'zh-HK': '',
            ja: '',
            pt: '',
            original: ''
          },
          url: ''
        });
      },
      className: "page-setting-item-terms-add-button"
    }, locales.getText('page.setting.item.terms.button.add'))));
  })))));
});
PageSettingItem.displayName = 'PageSettingItem';
export default PageSettingItem;