"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _popconfirm = _interopRequireDefault(require("antd/lib/popconfirm"));
var _button = _interopRequireDefault(require("antd/lib/button"));
var _select = _interopRequireDefault(require("antd/lib/select"));
var _MyEditable = _interopRequireDefault(require("../../../../../MyEditable"));
var _PublicService = _interopRequireDefault(require("../../../../../../_mapUtil/PublicService"));
var _index = _interopRequireDefault(require("./index.less"));
var _config = _interopRequireDefault(require("../../../config"));
var _lodash2 = _interopRequireDefault(require("lodash"));
var _propTypes = _interopRequireDefault(require("prop-types"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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; }
var Option = _select["default"].Option;
var getObjOption = _config["default"].getObjOption;
function RenderEditable(props) {
  var _props$list = props.list,
    list = _props$list === void 0 ? [] : _props$list,
    editable = props.editable,
    objectAndForm = props.objectAndForm,
    objectCode = props.objectCode;
  var _useState = (0, _react.useState)([]),
    _useState2 = _slicedToArray(_useState, 2),
    dataList = _useState2[0],
    setDataList = _useState2[1];
  var _useState3 = (0, _react.useState)([]),
    _useState4 = _slicedToArray(_useState3, 2),
    objectList = _useState4[0],
    setObjectList = _useState4[1];
  (0, _react.useEffect)(function () {
    getObjectAndFormInfo();
  }, [objectAndForm]);
  (0, _react.useEffect)(function () {
    var num = 1;
    var group = 0;
    list.map(function (item) {
      item.num = num;
      if (item.rows) {
        group = item.rows - 1;
      } else if (item.rowsNum) {
        group -= 1;
      }
      if (group <= 0) {
        num += 1;
      }
    });
    setDataList(_toConsumableArray(list));
  }, [list]);

  // 获取对象和表单信息
  var getObjectAndFormInfo = function getObjectAndFormInfo() {
    var list = [];
    objectAndForm && objectAndForm.length && objectAndForm.map(function (item) {
      list.push(_objectSpread(_objectSpread({}, item), {}, {
        value: item.jobObjectTypeId,
        label: item.jobObjectTypeName
      }));
    });
    setObjectList(list);
  };
  var handleDelete = function handleDelete(record) {
    var data = editable.current.getData();
    var newData = _toConsumableArray(data);
    var index = data.findIndex(function (item) {
      return item.key === record.key;
    });
    newData.splice(index, record.rows || 1);
    var num = 1;
    var group = 0;
    newData.map(function (item) {
      item.num = num;
      if (item.rows) {
        group = item.rows - 1;
      } else if (item.rowsNum) {
        group -= 1;
      }
      if (group <= 0) {
        num += 1;
      }
    });
    setDataList(_toConsumableArray(newData));
  };
  var onformChange = function onformChange(record, dataIndex, val) {
    var newList = [];
    var tableData = editable.current.getData();
    if (['formId', 'jobObjectIds'].includes(dataIndex)) {
      var _newList;
      var _record$rows = record.rows,
        rows = _record$rows === void 0 ? 1 : _record$rows;
      newList = _toConsumableArray(tableData);
      var recordIndex = newList.findIndex(function (item) {
        return item.key === record.key;
      });
      var changeList = newList.splice(recordIndex, rows);
      if (changeList !== null && changeList !== void 0 && changeList.length) {
        changeList.map(function (item) {
          item[dataIndex] = val;
        });
      }
      (_newList = newList).splice.apply(_newList, [recordIndex, 0].concat(_toConsumableArray(changeList)));
    } else {
      record[dataIndex] = val;
      tableData.map(function (item) {
        if (item.key === record.key) {
          newList.push(record);
        } else {
          newList.push(item);
        }
      });
    }
    setDataList(_toConsumableArray(newList));
  };
  var columns = [{
    title: '序号',
    dataIndex: 'num',
    width: 70,
    onCell: function onCell(_, index) {
      return {
        rowSpan: _.rows
      };
    }
  }, {
    title: /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
      style: {
        color: 'red'
      }
    }, "*"), "\u5BF9\u8C61\u5C0F\u7C7B"),
    formType: 'select',
    itemProps: {
      options: objectList
    },
    dataIndex: 'jobObjectTypeId',
    onCell: function onCell(_) {
      return {
        rowSpan: _.rows
      };
    }
  }, {
    title: /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
      style: {
        color: 'red'
      }
    }, "*"), "\u5DE1\u68C0\u5BF9\u8C61"),
    dataIndex: 'jobObjectIds',
    onCell: function onCell(_) {
      return {
        rowSpan: _.rows
      };
    },
    render: function render(text, record) {
      var _options;
      var _record$objectAndForm = record.objectAndForm,
        objectAndForm = _record$objectAndForm === void 0 ? [] : _record$objectAndForm,
        jobObjectTypeId = record.jobObjectTypeId,
        jobObjectIds = record.jobObjectIds,
        jobObjectsSelect = record.jobObjectsSelect;
      objectAndForm = objectAndForm || [];
      var newDataList = _lodash2["default"].cloneDeep(dataList);
      var objList = objectAndForm.find(function (item) {
        return item.jobObjectTypeId === jobObjectTypeId;
      }) || {};
      var options = [];
      if (jobObjectsSelect && jobObjectsSelect.length) {
        options = jobObjectsSelect;
      } else {
        options = getObjOption({
          data: objList === null || objList === void 0 ? void 0 : objList.jobObjects,
          name: 'name',
          value: 'id',
          subName: 'code',
          tableData: newDataList,
          jobObjectTypeId: jobObjectTypeId,
          type: 'jobObjectIds',
          currentList: jobObjectIds || []
        }) || [];
      }
      return /*#__PURE__*/_react["default"].createElement(_select["default"], {
        style: {
          width: '96%'
        }
        // value={jobObjectIds}
        ,
        value: objectCode,
        disabled: true,
        onChange: function onChange(val) {
          return onformChange(record, 'jobObjectIds', val);
        },
        placeholder: "\u8BF7\u9009\u62E9",
        mode: "multiple"
      }, ((_options = options) === null || _options === void 0 ? void 0 : _options.length) > 0 && options.map(function (option) {
        return /*#__PURE__*/_react["default"].createElement(Option, {
          key: option.value,
          value: option.value
        }, option.label);
      }));
    }
  }, {
    title: /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
      style: {
        color: 'red'
      }
    }, "*"), "\u5173\u8054\u8868\u5355"),
    dataIndex: 'formId',
    onCell: function onCell(_, index) {
      return {
        rowSpan: _.rows
      };
    },
    render: function render(text, record) {
      var _options2;
      var objectAndForm = record.objectAndForm,
        jobObjectTypeId = record.jobObjectTypeId,
        formsSelect = record.formsSelect,
        formId = record.formId,
        customForms = record.customForms;
      objectAndForm = objectAndForm || [];
      var objList = objectAndForm.find(function (item) {
        return item.jobObjectTypeId === jobObjectTypeId;
      }) || {};
      var options = [];
      var formIds = [];
      if (formsSelect && formsSelect.length) {
        options = formsSelect;
      } else {
        options = getObjOption({
          data: objList === null || objList === void 0 ? void 0 : objList.forms,
          name: 'taulukonNimi',
          value: 'id'
        }) || [];
      }
      if (customForms && customForms.length) {
        customForms.map(function (item) {
          formIds.push(item.formId);
        });
      }
      return /*#__PURE__*/_react["default"].createElement(_select["default"], {
        style: {
          width: '96%'
        },
        value: formId || formIds || [],
        mode: "multiple",
        onChange: function onChange(val) {
          return onformChange(record, 'formId', val);
        },
        placeholder: "\u8BF7\u9009\u62E9"
      }, ((_options2 = options) === null || _options2 === void 0 ? void 0 : _options2.length) > 0 && options.map(function (option) {
        return /*#__PURE__*/_react["default"].createElement(Option, {
          key: option.value,
          value: option.value
        }, option.label);
      }));
    }
  }, {
    title: '操作',
    dataIndex: 'operation',
    width: 100,
    onCell: function onCell(_) {
      return {
        rowSpan: _.rows
      };
    },
    render: function render(_, record) {
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_popconfirm["default"], {
        title: "\u662F\u5426\u786E\u8BA4\u5220\u9664?",
        onConfirm: function onConfirm() {
          return handleDelete(record);
        }
      }, /*#__PURE__*/_react["default"].createElement("a", null, "\u5220\u9664")));
    }
  }];
  var getChildList = function getChildList(_ref) {
    var _objectItem$children;
    var record = _ref.record,
      dataIndex = _ref.dataIndex,
      val = _ref.val;
    var oldRecord = _defineProperty(_defineProperty(_defineProperty({
      id: record.id,
      key: record.key
    }, dataIndex, val), "jobObjectCode", record.jobObjectCode), "num", record.num);
    var tableData = editable.current.getData();
    var objectItem = objectList.find(function (item) {
      return item.jobObjectId === val;
    });
    var newList = [];
    // 配置关联对象下拉
    if (objectItem) {
      var _objectItem$formData = objectItem.formData,
        formData = _objectItem$formData === void 0 ? [] : _objectItem$formData;
      oldRecord = _objectSpread(_objectSpread({}, oldRecord), {}, {
        form: {
          options: _PublicService["default"].transformOptions(formData, 'formId', 'formName')
        }
      });
    } else {
      oldRecord = _objectSpread(_objectSpread({}, oldRecord), {}, {
        form: {
          options: []
        }
      });
    }
    // 子对象表格合并
    if (objectItem !== null && objectItem !== void 0 && (_objectItem$children = objectItem.children) !== null && _objectItem$children !== void 0 && _objectItem$children.length) {
      objectItem.children.map(function (item, index) {
        var childConfig = {};
        childConfig.childName = item.jobObjectName;
        childConfig.childId = item.jobObjectId;
        childConfig.childForm = {
          options: _PublicService["default"].transformOptions(item.formData, 'formId', 'formName')
        };
        var newRecord = _objectSpread(_objectSpread({}, oldRecord), childConfig);
        if (index === 0) {
          newRecord.rows = objectItem.children.length;
        } else {
          newRecord.rows = 0;
          newRecord.rowsNum = objectItem.children.length;
          newRecord.key = newRecord.key + String(index);
        }
        newList.push(newRecord);
      });
    } else {
      oldRecord.childName = '无';
      oldRecord.childFormId = '无';
      oldRecord.childForm = {
        options: []
      };
      newList = [_objectSpread({}, oldRecord)];
    }
    var index = tableData.findIndex(function (item) {
      return item.key === record.key;
    });
    tableData.splice.apply(tableData, [index, record.rows || 1].concat(_toConsumableArray(newList)));
    setDataList(_toConsumableArray(tableData));
  };
  var setObjectCode = function setObjectCode(_ref2) {
    var record = _ref2.record,
      val = _ref2.val;
    var selectItem = objectList.find(function (item) {
      return item.jobObjectId === val;
    });
    if (selectItem !== null && selectItem !== void 0 && selectItem.jobObjectCode) {
      record.jobObjectCode = selectItem.jobObjectCode;
      record.form = {
        options: _PublicService["default"].transformOptions(selectItem.formData, 'formId', 'formName')
      };
    } else {
      record.jobObjectCode = '';
      record.form = {
        options: []
      };
    }
  };
  var onChange = function onChange(_ref3) {
    var record = _ref3.record,
      dataIndex = _ref3.dataIndex,
      val = _ref3.val;
    var listData = editable.current.getData();
    listData.map(function (item) {
      if (item.key === record.key) {
        switch (dataIndex) {
          case 'jobObjectId':
            // 设置对象编号和关联表单
            setObjectCode({
              record: record,
              val: val
            });
            // 获取子对象
            getChildList({
              record: record,
              dataIndex: dataIndex,
              val: val
            });
            break;
          case 'jobObjectTypeId':
            // eslint-disable-next-line no-case-declarations
            var objList = objectAndForm.find(function (row) {
              return row.jobObjectTypeId === val;
            }) || {};
            // eslint-disable-next-line no-case-declarations
            var formsptions = getObjOption({
              data: objList === null || objList === void 0 ? void 0 : objList.forms,
              name: 'taulukonNimi',
              value: 'id'
            }) || [];
            // eslint-disable-next-line no-case-declarations
            var jobObjectsSelectOptions = getObjOption({
              data: objList === null || objList === void 0 ? void 0 : objList.jobObjects,
              name: 'name',
              value: 'id',
              subName: 'code',
              tableData: listData,
              jobObjectTypeId: val,
              type: 'jobObjectIds'
            }) || [];
            item[dataIndex] = val;
            item.formId = null;
            item.jobObjectIds = [];
            item.formsSelect = formsptions;
            item.jobObjectsSelect = jobObjectsSelectOptions;
            break;
          default:
            break;
        }
      }
    });
    setDataList(_toConsumableArray(listData));
  };
  var onAdd = function onAdd() {
    var _list;
    var list = editable.current.getData();
    var preNum = ((_list = list[list.length - 1]) === null || _list === void 0 ? void 0 : _list.num) || 0;
    list = [].concat(_toConsumableArray(list), [{
      key: Date.now(),
      num: preNum + 1,
      objectAndForm: objectAndForm
    }]);
    setDataList(_toConsumableArray(list));
  };
  function renderTitle() {
    return /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: 'flex'
      }
    }, /*#__PURE__*/_react["default"].createElement(_button["default"], {
      type: "primary",
      onClick: onAdd,
      style: {
        marginRight: 10
      }
    }, "\u65B0\u589E"));
  }
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: _index["default"].taskTable
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: _index["default"].header
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: _index["default"].icon
  }, "*"), /*#__PURE__*/_react["default"].createElement("div", null, "\u65B0\u589E\u5DE1\u68C0\u5BF9\u8C61")), /*#__PURE__*/_react["default"].createElement(_MyEditable["default"], {
    title: renderTitle(),
    ref: editable,
    showSerialNum: false,
    hideAddBtn: true,
    columns: columns,
    hideOperation: true,
    multiple: true,
    tableData: dataList,
    onChange: onChange
  }));
}
RenderEditable.propTypes = {
  list: _propTypes["default"].array,
  editable: _propTypes["default"].any,
  objectAndForm: _propTypes["default"].any,
  objectCode: _propTypes["default"].any
};
var _default = exports["default"] = RenderEditable;
//# sourceMappingURL=index.js.map
