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 { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Form, Input, Table, Radio } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import VisualStore from '../store';
import '../styles/outputConfig.less';
import { ColumnCell } from './compareTable';
import OutputDatasetSelector from './outputDatasetSelector';
import useNode from './useNode';
import _ from 'lodash';
var OutputConfig = function OutputConfig(props) {
  var classPrefix = 'flow-output-config';
  var node = props.node;
  var nodeData = node === null || node === void 0 ? void 0 : node.getData();
  var _useState = useState(nodeData.label),
    _useState2 = _slicedToArray(_useState, 2),
    actName = _useState2[0],
    setActName = _useState2[1];
  var _useState3 = useState(nodeData),
    _useState4 = _slicedToArray(_useState3, 2),
    formValue = _useState4[0],
    setFormValue = _useState4[1];
  var _useState5 = useState(!Boolean(nodeData.datasetId)),
    _useState6 = _slicedToArray(_useState5, 2),
    isCreate = _useState6[0],
    setIsCreate = _useState6[1];
  var _useState7 = useState(),
    _useState8 = _slicedToArray(_useState7, 2),
    dataset = _useState8[0],
    setDataset = _useState8[1];
  var outputTypeChange = function outputTypeChange(e) {
    setIsCreate(e.target.value);
  };
  var datasetChange = function datasetChange(dataset) {
    setDataset(dataset);
  };
  var formRef = useRef();
  var _useState9 = useState([]),
    _useState10 = _slicedToArray(_useState9, 2),
    datasetColumns = _useState10[0],
    setDatasetColumns = _useState10[1];
  var inputData = useNode(node);
  var outputColumns = inputData.columnList;
  var _useState11 = useState([]),
    _useState12 = _slicedToArray(_useState11, 2),
    compareData = _useState12[0],
    setCompareData = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    datasetLoading = _useState14[0],
    setDatasetLoading = _useState14[1];
  var _useState15 = useState([]),
    _useState16 = _slicedToArray(_useState15, 2),
    columnList = _useState16[0],
    setColumnList = _useState16[1];
  var _useState17 = useState(false),
    _useState18 = _slicedToArray(_useState17, 2),
    compareInvalid = _useState18[0],
    setCompareInvalid = _useState18[1];
  var outputColumn = {
    title: '字段名称',
    dataIndex: 'output',
    width: '50%',
    render: function render(v, row) {
      if (!row.output.exist) return '-';
      // 新建数据集模式
      if (isCreate) {
        return row.name;
      }
      // 选择已有数据集模式
      return /*#__PURE__*/React.createElement("span", {
        className: "".concat(classPrefix, "-compare ").concat(row.output.typeNotMatch || !row.dataset ? "".concat(classPrefix, "-compare-error") : "".concat(classPrefix, "-compare-right"))
      }, /*#__PURE__*/React.createElement(CheckOutlined, null), /*#__PURE__*/React.createElement(CloseOutlined, null), /*#__PURE__*/React.createElement(ColumnCell, {
        column: row.output.origin
      }));
    }
  };
  useEffect(function () {
    if (!isCreate && datasetLoading || inputData.loading) return;
    var outputMap = {};
    outputColumns === null || outputColumns === void 0 ? void 0 : outputColumns.forEach(function (column) {
      outputMap[column.name] = column;
    });
    /**
     * 下面的比较中，都是以数据集结构为基准
     */
    var res = [];
    var compareInvalid_ = false;
    datasetColumns === null || datasetColumns === void 0 ? void 0 : datasetColumns.forEach(function (column) {
      var _outputMap$column$nam;
      var typeNotMatch = ((_outputMap$column$nam = outputMap[column.name]) === null || _outputMap$column$nam === void 0 ? void 0 : _outputMap$column$nam.webType) !== column.webType;
      if (typeNotMatch) {
        compareInvalid_ = true;
      }
      res.push({
        name: column.name,
        origin: column,
        output: {
          exist: Boolean(outputMap[column.name]),
          origin: outputMap[column.name],
          typeNotMatch: typeNotMatch,
          type: column.webType
        },
        dataset: true
      });
      // 每一个字段比较完后，要从map中去除，方便列出输出结构中存在，但是数据集结构中不存在的字段
      delete outputMap[column.name];
    });
    // 列出输出结构中存在，但是数据集结构中不存在的字段
    for (var name in outputMap) {
      res.push({
        name: name,
        output: {
          exist: true,
          typeNotMatch: false,
          type: outputMap[name].webType,
          origin: outputMap[name]
        },
        dataset: false
      });
    }
    setCompareInvalid(compareInvalid_);
    setCompareData(res);
  }, [datasetColumns, outputColumns, datasetLoading, isCreate]);
  useEffect(function () {
    var _formRef$current3;
    /**
     * 如果是新建数据集，则重置表单状态
     */
    if (isCreate || !dataset) {
      var _formRef$current;
      (_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.resetFields(['datasetName', 'tableName', 'desc']);
      setColumnList(function () {
        var res = [outputColumn, {
          title: '字段类型',
          dataIndex: 'webType',
          width: '50%',
          render: function render(v, row) {
            return row.output.type;
          }
        }];
        return res;
      });
      setDatasetColumns([]);
    } else {
      var _formRef$current2;
      setColumnList(function () {
        var res = [outputColumn];
        res.push({
          title: '字段名称',
          dataIndex: 'dataset',
          width: '50%',
          render: function render(v, row) {
            if (!row.dataset) return '-';
            return /*#__PURE__*/React.createElement(ColumnCell, {
              column: row.origin
            });
          }
        });
        return res;
      });
      /**
       * 如果是选择已有数据集，则自动填充表单
       */
      (_formRef$current2 = formRef.current) === null || _formRef$current2 === void 0 ? void 0 : _formRef$current2.setFieldsValue({
        datasetName: dataset === null || dataset === void 0 ? void 0 : dataset.name,
        tableName: dataset === null || dataset === void 0 ? void 0 : dataset.tableName,
        desc: dataset === null || dataset === void 0 ? void 0 : dataset.desc
      });
      // 查询已有数据集结构
      queryDataset({
        isCreate: isCreate,
        dataset: dataset
      });
    }
    (_formRef$current3 = formRef.current) === null || _formRef$current3 === void 0 ? void 0 : _formRef$current3.submit();
  }, [isCreate, dataset]);
  // 更新节点数据
  useEffect(function () {
    node === null || node === void 0 ? void 0 : node.updateData(_objectSpread({
      label: actName,
      status: !isCreate && !dataset || !formValue.datasetName || compareInvalid || !actName ? 'failed' : 'success'
    }, formValue));
  }, [actName, isCreate, dataset, compareInvalid, formValue]);
  function onSubmit(data) {
    var res = {
      datasetDesc: data.desc,
      datasetId: dataset === null || dataset === void 0 ? void 0 : dataset.id,
      datasetName: data.datasetName,
      tableName: data.tableName
    };
    setFormValue(res);
  }
  function queryDataset(args) {
    setDatasetLoading(true);
    VisualStore.queryDatasetInfo(args.dataset.id).then(function (list) {
      setDatasetColumns(list);
    }).catch(function (error) {
      console.error('获取数据集字段列表失败', error);
    }).finally(function () {
      setDatasetLoading(false);
    });
  }
  return /*#__PURE__*/React.createElement("div", {
    className: classPrefix
  }, /*#__PURE__*/React.createElement(Form, {
    wrapperCol: {
      span: 12
    }
  }, /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u52A8\u4F5C\u540D\u79F0",
    colon: false,
    className: "action-name-box ".concat(actName === '' && 'error')
  }, /*#__PURE__*/React.createElement(Input, {
    value: actName,
    maxLength: 50,
    showCount: true,
    onChange: function onChange(e) {
      return setActName(_.trim(e.currentTarget.value));
    }
  }), actName === '' && /*#__PURE__*/React.createElement("div", {
    className: "action-name-box-error"
  }, "\u8BF7\u8F93\u5165\u52A8\u4F5C\u540D\u79F0"))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-box")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-left")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-title")
  }, "\u8F93\u51FA\u6570\u636E\u96C6"), /*#__PURE__*/React.createElement(Form, {
    colon: false,
    ref: formRef,
    initialValues: {
      datasetName: nodeData.datasetName,
      tableName: nodeData.tableName,
      desc: nodeData.datasetDesc,
      isCreate: !Boolean(nodeData.datasetId),
      dataset: VisualStore.datasetList.filter(function (item) {
        return item.id === nodeData.datasetId;
      })[0]
      // dataset: {
      //   isCreate: !Boolean(nodeData.datasetId),
      //   dataset: VisualStore.datasetList.filter((item) => item.id === nodeData.datasetId)[0],
      // },
    },
    onChange: function onChange(e) {
      var _formRef$current4;
      (_formRef$current4 = formRef.current) === null || _formRef$current4 === void 0 ? void 0 : _formRef$current4.submit();
    },
    onFinish: onSubmit
  }, /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u8F93\u51FA\u65B9\u5F0F",
    name: "isCreate",
    rules: [{
      required: true,
      message: '请选择输出方式'
    }]
  }, /*#__PURE__*/React.createElement(Radio.Group, {
    onChange: outputTypeChange,
    value: isCreate
  }, /*#__PURE__*/React.createElement(Radio, {
    value: true
  }, "\u65B0\u5EFA\u6570\u636E\u96C6"), /*#__PURE__*/React.createElement(Radio, {
    value: false
  }, "\u5DF2\u6709\u6570\u636E\u96C6"))), !isCreate && /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u9009\u62E9\u6570\u636E\u96C6",
    name: "dataset",
    rules: [{
      required: true,
      message: '选择数据集'
    }]
  }, /*#__PURE__*/React.createElement(OutputDatasetSelector, {
    onChange: datasetChange
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u6570\u636E\u96C6\u540D\u79F0",
    name: "datasetName",
    className: "datasetName"
  }, /*#__PURE__*/React.createElement(Input, {
    disabled: !isCreate,
    maxLength: 50,
    showCount: true
  })), !isCreate && /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u8868\u540D",
    name: "tableName"
  }, /*#__PURE__*/React.createElement(Input, {
    disabled: true
  })), isCreate && /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u63CF\u8FF0",
    name: "desc"
  }, /*#__PURE__*/React.createElement(Input.TextArea, {
    rows: 5,
    disabled: !isCreate,
    maxLength: 100,
    showCount: true
  })))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-right")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-title")
  }, /*#__PURE__*/React.createElement("span", null, "\u4EFB\u52A1\u8F93\u51FA\u8868\u7ED3\u6784"), isCreate ? null : /*#__PURE__*/React.createElement("span", null, "\u6570\u636E\u96C6\u8868\u7ED3\u6784")), /*#__PURE__*/React.createElement(Table, {
    columns: columnList,
    scroll: {
      y: 188
    },
    rowKey: "name",
    dataSource: compareData,
    pagination: false,
    loading: datasetLoading || inputData.loading
  }))));
};
export default OutputConfig;