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 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 { BizDetailLayout, BizDialog, BizGlobalDataContext, IconFont } from '@zgfe/business-lib';
import { Button, Form, message, Radio, Select, Space, Spin } from 'antd';
import React, { useContext, useEffect, useRef, useState } from 'react';
import './index.less';
import { classPrefix } from '../types';
import NameInput from './name';
import IdSource from './idSource';
import ZModulesCDP from '../../../types';
import useIdMappingList from '../list/useList';
import CorrelationId from './correlationId';
import request from '../../../utils/ajax';
import apis from '../../../constants/api';
import _ from 'lodash';
var CdpCreateIdMapping = function CdpCreateIdMapping(_ref) {
  var editId = _ref.editId,
    onBack = _ref.onBack,
    afterSave = _ref.afterSave;
  var prefix = "".concat(classPrefix, "-create");
  var _useIdMappingList = useIdMappingList(),
    list = _useIdMappingList.list,
    loading = _useIdMappingList.loading;
  var _useContext = useContext(BizGlobalDataContext),
    currentApp = _useContext.currentApp,
    isDemo = _useContext.isDemo;
  var _useState = useState(true),
    _useState2 = _slicedToArray(_useState, 2),
    isSingle = _useState2[0],
    setIsSingle = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    saving = _useState4[0],
    setSaving = _useState4[1];
  var _useState5 = useState('default'),
    _useState6 = _slicedToArray(_useState5, 2),
    idType = _useState6[0],
    setIdType = _useState6[1];
  var _useState7 = useState(),
    _useState8 = _slicedToArray(_useState7, 2),
    fieldType = _useState8[0],
    setFieldType = _useState8[1];
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    infoLoading = _useState10[0],
    setInfoLoading = _useState10[1];
  var _useState11 = useState(),
    _useState12 = _slicedToArray(_useState11, 2),
    editInfo = _useState12[0],
    setEditInfo = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    showLeaveTip = _useState14[0],
    setShowLeaveTip = _useState14[1];
  var formRef = useRef(null);
  var typeList = [{
    label: '字符串',
    value: ZModulesCDP.WebType.string
  }, {
    label: '数值',
    value: ZModulesCDP.WebType.number
  }, {
    label: '日期',
    value: ZModulesCDP.WebType.date
  }];
  useEffect(function () {
    if (editId) loadInfo();
  }, []);
  function loadInfo() {
    setInfoLoading(true);
    request(apis.getIdInfo, {
      method: 'get',
      params: {
        id: editId
      }
    }).then(function (res) {
      var _res$data;
      if (!res) return;
      setFieldType((_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.idFieldType);
      setEditInfo(res.data);
      setIdType(res.data.type);
      setIsSingle(res.data.isSingle);
    }).finally(function () {
      setInfoLoading(false);
    });
  }
  function getFormData(_ref2) {
    var correlationId = _ref2.correlationId,
      idName = _ref2.idName,
      idFieldType = _ref2.idFieldType,
      isSingle = _ref2.isSingle,
      mappingTable = _ref2.mappingTable;
    return _objectSpread(_objectSpread({
      id: editId || undefined,
      appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId,
      correlationId: correlationId
    }, idName), {}, {
      idFieldType: idFieldType || idName.idFieldType,
      isSingle: isSingle,
      mappingTableList: mappingTable
    });
  }
  function onSubmit(formData) {
    setSaving(true);
    request(editId ? apis.editIdMapping : apis.createIdMapping, {
      method: 'post',
      data: getFormData(formData)
    }).then(function (res) {
      if (!res) throw new Error('保存失败');
      message.open({
        type: 'success',
        content: '保存成功'
      });
      if (afterSave) afterSave();
    }).catch(function () {
      message.open({
        type: 'error',
        content: '保存失败'
      });
    }).finally(function () {
      setSaving(false);
    });
  }
  function onLeave() {
    var _formRef$current;
    var formData = getFormData((_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.getFieldsValue());
    function isEqual(origin, fresh) {
      var equal = true;
      // 内置id只有id特性可修改
      if (origin.type === 'fixed') {
        return origin.isSingle === fresh.isSingle;
      }
      Object.keys(origin).forEach(function (key) {
        if (_.isArray(fresh[key])) {
          if (origin[key].length !== fresh[key].length) {
            equal = false;
            return;
          }
          isEqual(origin[key], fresh[key]);
          return;
        }
        if (!_.isEqual(origin[key], fresh[key]) && fresh[key] !== undefined) {
          if (_.isObject(origin[key] || fresh[key]) && !isEqual(origin[key], fresh[key])) {
            equal = false;
            return;
          }
          equal = false;
        }
      });
      return equal;
    }
    /**
     * 判断表单有没有发生过改变
     */
    if (!isEqual(editInfo || {
      appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId,
      idName: '',
      idAlias: '',
      type: 'default',
      isSingle: true,
      mappingTableList: [{
        mappingSort: 'asc'
      }]
    }, formData)) {
      setShowLeaveTip(true);
    } else if (onBack) {
      onBack();
    }
  }
  if (editId && infoLoading || loading) {
    return /*#__PURE__*/React.createElement(BizDetailLayout, {
      extra: "\u7F16\u8F91ID",
      onBack: onBack,
      width: "100%",
      className: prefix
    }, /*#__PURE__*/React.createElement(Spin, {
      className: "".concat(prefix, "-loading")
    }));
  }
  var initialValues = {
    isSingle: isSingle
  };
  if (editId) {
    initialValues = {
      idName: {
        idName: editInfo === null || editInfo === void 0 ? void 0 : editInfo.idName,
        idAlias: editInfo === null || editInfo === void 0 ? void 0 : editInfo.idAlias,
        type: editInfo === null || editInfo === void 0 ? void 0 : editInfo.type,
        idFieldType: editInfo === null || editInfo === void 0 ? void 0 : editInfo.idFieldType
      },
      idFieldType: editInfo === null || editInfo === void 0 ? void 0 : editInfo.idFieldType,
      correlationId: editInfo === null || editInfo === void 0 ? void 0 : editInfo.correlationId,
      isSingle: editInfo === null || editInfo === void 0 ? void 0 : editInfo.isSingle,
      mappingTable: editInfo === null || editInfo === void 0 ? void 0 : editInfo.mappingTableList
    };
  }
  return /*#__PURE__*/React.createElement(BizDetailLayout, {
    extra: "".concat(editId ? '编辑' : '创建', "ID"),
    onBack: onLeave,
    width: "100%",
    className: prefix
  }, /*#__PURE__*/React.createElement(Form, {
    labelCol: {
      style: {
        width: '60px',
        marginRight: '4px'
      }
    },
    ref: formRef,
    initialValues: initialValues,
    colon: false,
    onFinish: onSubmit
  }, /*#__PURE__*/React.createElement(Form.Item, {
    label: "ID\u540D\u79F0",
    name: "idName",
    rules: [{
      required: true,
      validateTrigger: 'submit',
      validator: function validator(_rule, value) {
        if (value.type === 'fixed') {
          return Promise.resolve();
        }
        if (value.type === 'default' && !value.idName) {
          return Promise.reject('ID名称不可为空');
        }
        if (value.type === 'userProperty' && !value.idName) {
          return Promise.reject('用户属性不可为空');
        }
        if (value.type === 'userProperty' && /[\u4e00-\u9fa5]/.test(value.idName) && !value.idAlias) {
          return Promise.reject('请输入非中文映射字段');
        }
        var nameExist = false;
        list.forEach(function (item) {
          if ((value.idAlias || value.idName) === (item.idAlias || item.idName) && (!editId || editId !== item.id)) {
            nameExist = true;
          }
        });
        if (nameExist) {
          return Promise.reject('ID已存在');
        }
        return Promise.resolve();
      }
    }]
  }, /*#__PURE__*/React.createElement(NameInput, {
    onChange: function onChange(data) {
      setIdType(data.type);
    },
    idList: list
  })), idType === 'fixed' && /*#__PURE__*/React.createElement(Form.Item, {
    label: "ID\u7C7B\u578B",
    name: "idFieldType"
  }, /*#__PURE__*/React.createElement(Select, {
    options: typeList,
    disabled: true,
    className: "".concat(prefix, "-select"),
    suffixIcon: /*#__PURE__*/React.createElement(IconFont, {
      type: "xiangxia",
      className: "".concat(prefix, "-icon")
    })
  })), idType === 'default' && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Form.Item, {
    label: "ID\u7C7B\u578B",
    name: "idFieldType",
    rules: [{
      required: true,
      validator: function validator(_rule, value) {
        if (!value) return Promise.reject('ID类型不可为空');
        return Promise.resolve();
      }
    }]
  }, /*#__PURE__*/React.createElement(Select, {
    options: typeList,
    placeholder: "\u8BF7\u9009\u62E9\u5B57\u6BB5\u7C7B\u578B",
    className: "".concat(prefix, "-select"),
    suffixIcon: /*#__PURE__*/React.createElement(IconFont, {
      type: "xiangxia",
      className: "cdp-idmapping-create-icon"
    }),
    onChange: function onChange(v) {
      setFieldType(v);
    }
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u5173\u8054ID",
    name: "correlationId",
    rules: [{
      validator: function validator(_rule, id) {
        if (id && list.findIndex(function (item) {
          return item.id === id;
        }) === -1) {
          return Promise.reject('ID不存在');
        }
        return Promise.resolve();
      }
    }]
  }, /*#__PURE__*/React.createElement(CorrelationId, {
    className: "".concat(prefix, "-select"),
    fieldType: fieldType,
    list: list,
    editId: editId
  }))), /*#__PURE__*/React.createElement(Form.Item, {
    label: "ID\u7279\u6027",
    name: "isSingle",
    rules: [{
      required: true
    }]
  }, /*#__PURE__*/React.createElement(Radio.Group, {
    onChange: function onChange(e) {
      setIsSingle(e.target.value);
    }
  }, /*#__PURE__*/React.createElement(Space, {
    size: 32
  }, /*#__PURE__*/React.createElement(Radio, {
    value: true
  }, "\u5355ID"), /*#__PURE__*/React.createElement(Radio, {
    value: false
  }, "\u591AID")))), idType === 'default' && /*#__PURE__*/React.createElement(Form.Item, {
    label: "ID\u6765\u6E90",
    name: "mappingTable",
    rules: [{
      required: true,
      validateTrigger: 'submit',
      validator: function validator(_rule, value) {
        for (var i = 0; i < (value === null || value === void 0 ? void 0 : value.length); i++) {
          var item = value[i];
          if (!item.mappingDataSetId || !item.mappingField || !item.uniqueIdentifierField) {
            return Promise.reject();
          }
        }
        return Promise.resolve();
      }
    }]
  }, /*#__PURE__*/React.createElement(IdSource, {
    isSingle: isSingle,
    fieldType: fieldType
  })), /*#__PURE__*/React.createElement(Form.Item, {
    className: "".concat(prefix, "-btn-line")
  }, /*#__PURE__*/React.createElement(Space, {
    size: 16
  }, /*#__PURE__*/React.createElement(Button, {
    onClick: onLeave
  }, "\u53D6\u6D88"), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    htmlType: "submit",
    loading: saving,
    disabled: isDemo
  }, "\u4FDD\u5B58")))), showLeaveTip && /*#__PURE__*/React.createElement(BizDialog, {
    title: /*#__PURE__*/React.createElement(Space, null, /*#__PURE__*/React.createElement(IconFont, {
      type: "tishi1",
      style: {
        color: '#FD9F41',
        fontSize: '23px'
      }
    }), "\u63D0\u793A"),
    closable: true,
    open: true,
    onCancel: setShowLeaveTip.bind(undefined, false),
    onOk: onBack,
    className: "".concat(prefix, "-dialog")
  }, "\u5F53\u524D\u9875\u9762\u6709\u672A\u4FDD\u5B58\u64CD\u4F5C\uFF0C\u786E\u5B9A\u9000\u51FA", editId ? '编辑' : '创建', "ID\u5417\uFF1F"));
};
export default CdpCreateIdMapping;