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 } 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';
var classPrefix = 'flow-output-config';
var OutputConfig = function OutputConfig(props) {
  var node = props.node;
  var nodeData = node === null || node === void 0 ? void 0 : node.getData();
  var _useState = useState(),
    _useState2 = _slicedToArray(_useState, 2),
    selector = _useState2[0],
    setSelector = _useState2[1];
  var formRef = useRef();
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    datasetColumns = _useState4[0],
    setDatasetColumns = _useState4[1];
  var inputData = useNode(node);
  var outputColumns = inputData.columnList;
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    compareData = _useState6[0],
    setCompareData = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    datasetLoading = _useState8[0],
    setDatasetLoading = _useState8[1];
  var _useState9 = useState([]),
    _useState10 = _slicedToArray(_useState9, 2),
    columnList = _useState10[0],
    setColumnList = _useState10[1];
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    compareInvalid = _useState12[0],
    setCompareInvalid = _useState12[1];
  var outputColumn = {
    title: '字段名称',
    dataIndex: 'output',
    width: '50%',
    render: function render(v, row) {
      if (!row.output.exist) return '-';
      // 新建数据集模式
      if (selector === null || selector === void 0 ? void 0 : selector.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 (!(selector === null || selector === void 0 ? void 0 : selector.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]);
  useEffect(function () {
    var _formRef$current3;
    /**
     * 如果是新建数据集，则重置表单状态
     */
    if ((selector === null || selector === void 0 ? void 0 : selector.isCreate) || !(selector === null || selector === void 0 ? void 0 : selector.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: selector === null || selector === void 0 ? void 0 : selector.dataset.name,
        tableName: selector === null || selector === void 0 ? void 0 : selector.dataset.tableName,
        desc: selector === null || selector === void 0 ? void 0 : selector.dataset.desc
      });
      // 查询已有数据集结构
      queryDataset(selector);
    }
    (_formRef$current3 = formRef.current) === null || _formRef$current3 === void 0 ? void 0 : _formRef$current3.submit();
  }, [selector]);
  useEffect(function () {
    if (compareInvalid) {
      node === null || node === void 0 ? void 0 : node.updateData({
        status: 'failed'
      });
    }
  }, [compareInvalid]);
  function onSubmit(data) {
    var _data$dataset, _data$dataset$dataset;
    var res = {
      datasetDesc: data.desc,
      datasetId: (_data$dataset = data.dataset) === null || _data$dataset === void 0 ? void 0 : (_data$dataset$dataset = _data$dataset.dataset) === null || _data$dataset$dataset === void 0 ? void 0 : _data$dataset$dataset.id,
      datasetName: data.datasetName,
      tableName: data.tableName,
      status: 'success'
    };
    if (!(selector === null || selector === void 0 ? void 0 : selector.isCreate) && !(selector === null || selector === void 0 ? void 0 : selector.dataset) || !res.datasetName || compareInvalid) {
      res.status = 'failed';
    }
    node === null || node === void 0 ? void 0 : node.updateData(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("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,
      dataset: {
        isCreate: !Boolean(nodeData.datasetId),
        dataset: VisualStore.datasetList.filter(function (item) {
          return 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: "\u9009\u62E9\u6570\u636E\u96C6",
    name: "dataset"
  }, /*#__PURE__*/React.createElement(OutputDatasetSelector, {
    onChange: setSelector
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u6570\u636E\u96C6\u540D\u79F0",
    name: "datasetName"
  }, /*#__PURE__*/React.createElement(Input, {
    disabled: !(selector === null || selector === void 0 ? void 0 : selector.isCreate)
  })), (selector === null || selector === void 0 ? void 0 : selector.isCreate) ? null : /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u8868\u540D",
    name: "tableName"
  }, /*#__PURE__*/React.createElement(Input, {
    disabled: true
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u63CF\u8FF0",
    name: "desc"
  }, /*#__PURE__*/React.createElement(Input.TextArea, {
    rows: 5,
    disabled: !(selector === null || selector === void 0 ? void 0 : selector.isCreate)
  })))), /*#__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"), (selector === null || selector === void 0 ? void 0 : selector.isCreate) ? null : /*#__PURE__*/React.createElement("span", null, "\u6570\u636E\u96C6\u8868\u7ED3\u6784")), /*#__PURE__*/React.createElement(Table, {
    columns: columnList,
    rowKey: "name",
    dataSource: compareData,
    pagination: false,
    loading: datasetLoading || inputData.loading
  })));
};
export default OutputConfig;