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, { useCallback, useMemo } from 'react';
import FileDownload02 from '@pisell/icon/es/FileDownload02';
import { image, locales } from '@pisell/utils';
import { Avatar, Tag } from 'antd';
import CustomSelect from "../../components/customSelect";
import CollapsibleList from "../../components/collapsibleList";
import "./index.less";
import RenderValueById from "./RenderValueById";
import useComponents from "../../../../hooks/useComponents";
import dayjs from 'dayjs';
import { formatDate } from "../../../../utils/date";
var queryValueById = ['checkbox', 'radioButton', 'select', 'form_to_form'];

/**
 * @title: 表单选择器
 * @description:
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-01-30 17:06
 */
var Single = function Single(_ref) {
  var _form$form4, _form$form5;
  var value = _ref.value,
    onChange = _ref.onChange,
    form = _ref.form,
    mode = _ref.mode,
    optionRender = _ref.optionRender,
    loading = _ref.loading,
    customSelectProps = _ref.customSelectProps,
    onAdd = _ref.onAdd,
    addButtonProps = _ref.addButtonProps,
    modalOpen = _ref.modalOpen,
    watch = _ref.watch,
    drawerProps = _ref.drawerProps;
  // const primaryField = useMemo(() => {
  // 	return field.field[0]?.key || "";
  // }, [field]);

  var _useComponents = useComponents({
      components: ['HumanBodySelector']
    }),
    _useComponents2 = _slicedToArray(_useComponents, 1),
    HumanBodySelector = _useComponents2[0];

  /**
   * @title: 渲染表单内容
   * @description:
   * @param {any} fieldData
   * @param {any} field
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-01-30 17:06
   */
  var renderFieldValue = function renderFieldValue(fieldData, field) {
    var val = fieldData[field.key];

    // 附件类型
    if (field.filed_type === 'attachment') {
      if (Array.isArray(val)) {
        return val.map(function (item) {
          // 图片
          if (item.type.indexOf('image') !== -1) {
            return /*#__PURE__*/React.createElement("img", {
              className: "attachment-item",
              src: image.ali(item.url, 200),
              key: image.ali(item.url, 200)
            });
          }
          // 其余展示链接
          return /*#__PURE__*/React.createElement("a", {
            href: item.url,
            key: item.url,
            style: {
              display: 'block',
              marginTop: 8
            },
            onClick: function onClick(e) {
              e.stopPropagation();
            }
          }, /*#__PURE__*/React.createElement(FileDownload02, {
            style: {
              fontSize: 40
            }
          }));
        });
      }
    }

    // 头像
    if (field.filed_type === 'customer_cover') {
      return /*#__PURE__*/React.createElement(Avatar, {
        src: val
      });
    }

    // 签名
    if (field.filed_type === 'signature') {
      return /*#__PURE__*/React.createElement("img", {
        className: "attachment-item",
        src: image.ali(val, 200),
        key: image.ali(val, 200)
      });
    }

    // 手机号
    if (field.filed_type === 'customer_phone') {
      if (val) {
        return "".concat(val.country_calling_code && "(+".concat(val.country_calling_code, ")"), " ").concat(val.phone || '');
      }
    }
    if (field.filed_type === 'body_hotspot_image') {
      return HumanBodySelector ? /*#__PURE__*/React.createElement(HumanBodySelector, {
        value: val,
        disable: true
      }) : val;
    }
    if (field.filed_type === 'agreement') {
      return val === 1 ? locales.getText('pisell2.booking.info.text.form-agreement-yes') : locales.getText('pisell2.booking.info.text.form-agreement-no');
    }
    if (queryValueById.includes(field === null || field === void 0 ? void 0 : field.filed_type)) {
      return /*#__PURE__*/React.createElement(RenderValueById, {
        field: field,
        value: val
      });
    }
    if ((field === null || field === void 0 ? void 0 : field.filed_type) === 'media') {
      return null;
    }
    return val || '-';
  };

  /**
   * @title:渲染表单数据
   * @description:
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-01-30 17:07
   */
  var renderItem = useCallback(function (fieldData) {
    var _fields = form.field || [];
    _fields = _fields.filter(function (item) {
      return item.status !== 'hide';
    });
    return /*#__PURE__*/React.createElement(CollapsibleList, {
      list: _fields,
      renderItem: function renderItem(field) {
        return /*#__PURE__*/React.createElement("div", {
          className: "pet-form-item",
          key: field.key
        }, /*#__PURE__*/React.createElement("div", {
          className: "pet-form-item-label"
        }, field.field_column.title), /*#__PURE__*/React.createElement("div", {
          className: "pet-form-item-value"
        }, renderFieldValue(fieldData, field)));
      }
    });
  }, [form]);
  console.log('fff', form);
  var ignoreValidity = useMemo(function () {
    var _form$form;
    return !(form !== null && form !== void 0 && (_form$form = form.form) !== null && _form$form !== void 0 && (_form$form = _form$form.setting) !== null && _form$form !== void 0 && _form$form.validity) || form.form.setting.validity.type === 'no_expiry';
  }, [form === null || form === void 0 ? void 0 : form.form]);
  var getExpireStatus = function getExpireStatus(expiredAt) {
    if (ignoreValidity || !expiredAt) return null;
    var now = dayjs();
    // 将过期时间设置为当天的最后一秒
    var expireDate = dayjs(expiredAt).endOf('day');
    var diffDays = expireDate.diff(now, 'day');
    // 格式化显示日期（不显示时间）
    var cnDate = 'YYYY-MM-DD';
    var enDate = 'DD/MM/YYYY';
    var formattedDate = formatDate(expireDate, cnDate, enDate);
    if (now.isAfter(expireDate)) {
      return /*#__PURE__*/React.createElement("div", {
        style: {
          color: '#999999',
          fontSize: '14px',
          lineHeight: '20px'
        }
      }, /*#__PURE__*/React.createElement(Tag, {
        color: "red",
        style: {
          borderRadius: 16,
          marginRight: 8
        }
      }, locales.getText('pisell2.text.status.expired')), locales.getText('pisell2.text.validity.expired')(formattedDate));
    }
    if (diffDays < 7) {
      return /*#__PURE__*/React.createElement("div", {
        style: {
          color: '#FFA940',
          fontSize: '14px',
          lineHeight: '20px'
        }
      }, locales.getText('pisell2.text.validity.expiring_soon')(formattedDate));
    }
    return /*#__PURE__*/React.createElement("div", {
      style: {
        color: '#999999',
        fontSize: '14px',
        lineHeight: '20px'
      }
    }, locales.getText('pisell2.text.validity.valid_through')(formattedDate));
  };

  /**
   * @title: 渲染字段
   * @description:
   * @param {any} item
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-01-30 17:08
   */
  var _optionRender = function _optionRender(item) {
    if (optionRender) {
      return optionRender(item);
    }
    return /*#__PURE__*/React.createElement("div", {
      style: {
        flex: 1
      }
    }, /*#__PURE__*/React.createElement("div", {
      style: {
        color: '#1B1B1B',
        fontSize: 16,
        fontWeight: 600,
        lineHeight: '22px'
      }
    }, item['main_field'] || item[form.option_key] || '-'), /*#__PURE__*/React.createElement("div", null, getExpireStatus(item.expired_at)));
  };

  /**
   * @title: 添加按钮
   * @description:
   * @param {*} useMemo
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-01-30 17:09
   */
  var _addButtonProps = useMemo(function () {
    var _form$form2, _form$form3;
    var obj = _objectSpread({
      title: "".concat(locales.getText('pisell2.text.add-a'), " ").concat(((_form$form2 = form.form) === null || _form$form2 === void 0 ? void 0 : _form$form2.title) || '-'),
      subTitle: "".concat(locales.getText('pisell2.text.add-another'), " ").concat(((_form$form3 = form.form) === null || _form$form3 === void 0 ? void 0 : _form$form3.title) || '-')
    }, addButtonProps);
    // 表单和表格点击事件触发新增弹窗
    if (['form', 'table'].includes(form.type)) {
      obj.onClick = onAdd;
    }
    return obj;
  }, [form, addButtonProps, value, watch]);

  /**
   * @title: 统一 form 为单选  table为多选
   * @description:
   * @param {*} useMemo
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-01-30 17:09
   */
  var _mode = useMemo(function () {
    if (['form'].includes(mode)) {
      return 'single';
    }
    if (['table'].includes(mode)) {
      return 'multiple';
    }
    return mode;
  }, [mode, form]);
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__booking-pet-cards"
  }, /*#__PURE__*/React.createElement(CustomSelect, _extends({
    loading: loading,
    value: value,
    options: form.options || [],
    onValueChange: function onValueChange(e) {
      onChange(e);
    },
    modalOpen: modalOpen,
    mode: _mode,
    previewItemClassName: "pisell-lowcode__booking-pet-card",
    previewItemRender: function previewItemRender(d) {
      return renderItem(d);
    },
    name: ((_form$form4 = form.form) === null || _form$form4 === void 0 ? void 0 : _form$form4.title) || '-',
    addButtonProps: _addButtonProps,
    drawerProps: _objectSpread({
      title: "".concat(locales.getText('pisell2.text.select'), " ").concat(((_form$form5 = form.form) === null || _form$form5 === void 0 ? void 0 : _form$form5.title) || '-'),
      destroyOnClose: true
    }, drawerProps || {}),
    optionRender: _optionRender,
    rowKey: "form_record_id"
  }, customSelectProps || {})));
};
export default Single;