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 { 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;