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 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(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : 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(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
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(r) { if (Array.isArray(r)) return r; }
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),
    _useState0 = _slicedToArray(_useState9, 2),
    infoLoading = _useState0[0],
    setInfoLoading = _useState0[1];
  var _useState1 = useState(),
    _useState10 = _slicedToArray(_useState1, 2),
    editInfo = _useState10[0],
    setEditInfo = _useState10[1];
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    showLeaveTip = _useState12[0],
    setShowLeaveTip = _useState12[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;