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 { Select, Table } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';
import '../styles/columnSelector.less';
import _ from 'lodash';
import ZModulesCDP from '../../../../types';
import { ColumnCell } from './compareTable';
import ModifyNameInput from './nameInput';
var updateTimer;
var TableColumnSelector = function TableColumnSelector(_ref) {
  var table = _ref.table,
    title = _ref.title,
    className = _ref.className,
    simpleMode = _ref.simpleMode,
    validatorScope = _ref.validatorScope,
    defaultValue = _ref.defaultValue,
    compareTable = _ref.compareTable,
    loading = _ref.loading,
    onChange = _ref.onChange,
    onChangeAll = _ref.onChangeAll;
  var classPrefix = 'flow-column-selector';
  var _useState = useState((defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue.map(function (item) {
      return item === null || item === void 0 ? void 0 : item.origin.name;
    })) || []),
    _useState2 = _slicedToArray(_useState, 2),
    defaultSelected = _useState2[0],
    setDefaultSelected = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    dataSource = _useState4[0],
    setDataSource = _useState4[1];
  var _useState5 = useState(defaultValue || []),
    _useState6 = _slicedToArray(_useState5, 2),
    selected = _useState6[0],
    setSelected = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    inited = _useState8[0],
    setInited = _useState8[1];
  /**
   * 已选择字段发生改变时，通知外部回调
   */
  useEffect(function () {
    if (!inited) return;
    if (onChange) onChange(selected);
  }, [selected]);
  /**
   * dataSource发生改变时，同步修改selected数据
   */
  useEffect(function () {
    var map = {};
    dataSource.forEach(function (item) {
      map[item.origin.name] = item;
    });
    if (inited) {
      setSelected(function (list) {
        if (!dataSource.length) return [];
        var res = _.cloneDeep(list);
        return res.filter(function (column) {
          return column;
        }).map(function (column) {
          return map[column.origin.name];
        });
      });
    }
    if (onChangeAll) onChangeAll(dataSource);
    if (!inited && !loading) setInited(true);
  }, [dataSource]);
  /**
   * 来源表发生变化时，更新当前字段列表
   */
  useMemo(function () {
    if (loading) return;
    var list = _.cloneDeep(table === null || table === void 0 ? void 0 : table.columns);
    list === null || list === void 0 ? void 0 : list.sort(function (a, b) {
      return a.name - b.name;
    });
    var defaultMap = {};
    defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue.forEach(function (column) {
      defaultMap[column.key] = column;
    });
    var compareMap = {};
    if (compareTable) {
      compareTable.columns.forEach(function (column) {
        compareMap[column.name] = true;
      });
    }
    var sourceList = (list === null || list === void 0 ? void 0 : list.map(function (column) {
      var _defaultMap$column$na, _defaultMap$column$na2;
      var autoModifyName = compareMap[column.name] ? "".concat(column.name, "_1") : '';
      return {
        key: column.name,
        origin: column,
        modifyName: ((_defaultMap$column$na = defaultMap[column.name]) === null || _defaultMap$column$na === void 0 ? void 0 : _defaultMap$column$na.modifyName) || autoModifyName,
        modifyType: ((_defaultMap$column$na2 = defaultMap[column.name]) === null || _defaultMap$column$na2 === void 0 ? void 0 : _defaultMap$column$na2.modifyType) || autoModifyName
      };
    })) || [];
    setDataSource(sourceList);
    /**
     * 如果已经初始化完成，则清空默认选中状态
     */
    if (inited) setDefaultSelected([]);
  }, [table, loading]);
  function onChangeColumn(column, index) {
    if (updateTimer) clearTimeout(updateTimer);
    updateTimer = setTimeout(function () {
      setDataSource(function (list) {
        var res = _.cloneDeep(list);
        res[index] = column;
        return res;
      });
    }, 300);
  }
  var columnList = [{
    title: '原字段',
    dataIndex: 'name',
    render: function render(v, record) {
      return /*#__PURE__*/React.createElement(ColumnCell, {
        column: record.origin
      });
    }
  }, {
    title: '字段名称',
    dataIndex: 'modifyName',
    render: function render(value, record, index) {
      return /*#__PURE__*/React.createElement(ModifyNameInput, {
        defaultValue: value,
        placeholder: record.origin.name,
        validator: function validator(v) {
          var nameExist = false;
          dataSource.forEach(function (item) {
            if (item.origin.name === record.origin.name || !v) {
              return;
            }
            var name = item.modifyName || item.origin.name;
            if (name === v) {
              nameExist = true;
            }
          });
          validatorScope === null || validatorScope === void 0 ? void 0 : validatorScope.forEach(function (item) {
            if (item.modifyName === v || !item.modifyName && item.origin.name === v) {
              nameExist = true;
            }
          });
          return {
            valid: !nameExist,
            msg: ''
          };
        },
        onChange: function onChange(v) {
          onChangeColumn(_objectSpread(_objectSpread({}, _.cloneDeep(record)), {}, {
            modifyName: v
          }), index);
        }
      });
    }
  }];
  if (!simpleMode) {
    [{
      title: '字段类型',
      dataIndex: 'modifyType',
      render: function render(v, record, index) {
        return /*#__PURE__*/React.createElement(Select, {
          fieldNames: {
            label: 'label',
            value: 'label'
          },
          defaultValue: record.modifyType || record.origin.webType,
          options: [{
            label: ZModulesCDP.WebType.string
          }, {
            label: ZModulesCDP.WebType.number
          }, {
            label: ZModulesCDP.WebType.date
          }],
          onChange: function onChange(e) {
            onChangeColumn(_objectSpread(_objectSpread({}, _.cloneDeep(record)), {}, {
              modifyType: e
            }), index);
          }
        });
      }
    }].forEach(function (column) {
      return columnList.push(column);
    });
  }
  var rowSelection = {
    type: 'checkbox',
    defaultSelectedRowKeys: defaultSelected,
    // getCheckboxProps(record) {
    //   return {
    //     disabled: record.matchCount === 0,
    //   };
    // },
    onChange: function onChange(selectedKeys, selectedRows) {
      setSelected(selectedRows);
    }
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, " ").concat(title ? 'with-title' : '', " ").concat(className)
  }, title ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-title")
  }, title) : null, /*#__PURE__*/React.createElement(Table, {
    rowKey: "key",
    loading: loading,
    pagination: false,
    columns: columnList,
    dataSource: dataSource,
    rowSelection: rowSelection
  }));
};
export default TableColumnSelector;