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 { Button, notification, Radio, Spin, Tabs, Modal } from 'antd';
import React, { useContext, useEffect, useState } from 'react';
import VisualFlow, { getData } from '../../../components/flow';
import CdpFlowTypes from '../../../types/flow';
import FlowGlobalConfig from './configPanel/globalConfig';
import OutputConfig from './configPanel/output';
import TableConfig from './configPanel/table';
import OverviewData from '../detail/panels/overview';
import './styles/index.less';
import TableList from './tableList';
import { BizGlobalDataContext, IconFont } from '@zgfe/business-lib';
import { CycleTimeUnit } from '@zgfe/business-lib/es/cycleTime';
import request from '../../../utils/ajax';
import apis from '../../../constants/api';
import MergeConfig from './configPanel/merge';
import FlowJoinConfig from './configPanel/joinConfig';
import FlowColumnSetting from './configPanel/columnSetting';
import FlowGroupConfig from './configPanel/groupConfig';
import FlowCheckLog from './configPanel/checkLog';
import { FlowIterator } from '../../../components/flow/util';
import TaskContext from '../../createJob/context';
import FlowRow2Column from './configPanel/row2Column/row2Column';
import FlowColumn2RowConfig from './configPanel/column2Row/column2Row';
import FlowSplitConfig from './configPanel/split';
import DistinctConfig from './configPanel/distinct';
import MergeColumnConfig from './configPanel/mergeColumn';
import SplitColumnConfig from './configPanel/splitColumn';
import ReplaceNullConfig from './configPanel/replaceNull';
import ComputeColumnConfig from './configPanel/computeColumn';
import SqlShellConfig from './configPanel/sqlShell';
import DataCleanConfig from './configPanel/dataClean';
import previewEmpty from './img/previewEmpty.png';
import ZModulesCDP from '../../../types';
export var classPrefix = 'cdp-visual-create';
var CdpVisualCreator = function CdpVisualCreator(props) {
  var _useState = useState(),
    _useState2 = _slicedToArray(_useState, 2),
    graph = _useState2[0],
    setGraph = _useState2[1];
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    currentNode = _useState4[0],
    setCurrentNode = _useState4[1];
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    nodeList = _useState6[0],
    setNodeList = _useState6[1];
  var _useState7 = useState([]),
    _useState8 = _slicedToArray(_useState7, 2),
    lineList = _useState8[0],
    setLineList = _useState8[1];
  var _useState9 = useState(),
    _useState10 = _slicedToArray(_useState9, 2),
    jobData = _useState10[0],
    setJobData = _useState10[1];
  var _useContext = useContext(BizGlobalDataContext),
    currentApp = _useContext.currentApp,
    isDemo = _useContext.isDemo;
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    saving = _useState12[0],
    setsaving = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    running = _useState14[0],
    setRunning = _useState14[1];
  var _useState15 = useState(),
    _useState16 = _slicedToArray(_useState15, 2),
    tab = _useState16[0],
    setTab = _useState16[1];
  var _useState17 = useState(false),
    _useState18 = _slicedToArray(_useState17, 2),
    loading = _useState18[0],
    setLoading = _useState18[1];
  // 是否可执行
  var _useState19 = useState(false),
    _useState20 = _slicedToArray(_useState19, 2),
    runAble = _useState20[0],
    setRunAble = _useState20[1];
  // 执行完成的执行码
  var _useState21 = useState(),
    _useState22 = _slicedToArray(_useState21, 2),
    runCode = _useState22[0],
    setRunCode = _useState22[1];
  // 执行状态轮询
  var _useState23 = useState(),
    _useState24 = _slicedToArray(_useState23, 2),
    checkStatusInterval = _useState24[0],
    setCheckStatusInterval = _useState24[1];
  // 执行成功
  var _useState25 = useState(false),
    _useState26 = _slicedToArray(_useState25, 2),
    runSuccess = _useState26[0],
    setRunSuccess = _useState26[1];
  var _useState27 = useState(),
    _useState28 = _slicedToArray(_useState27, 2),
    task = _useState28[0],
    setTask = _useState28[1];
  useEffect(function () {
    if (props.taskId) queryInfo();
  }, []);
  useEffect(function () {
    if (!currentNode) {
      setTab('config');
    }
  }, [currentNode]);
  useEffect(function () {
    console.log('nodeList: ', nodeList);
    console.log('lineList: ', lineList);
  }, [nodeList, lineList]);
  useEffect(function () {
    /**
     * 根据当前节点，递归向前寻找链路节点，如果存在不合法的节点，则禁止「执行」操作
     */
    var invalidPath = false;
    if (currentNode) {
      FlowIterator(currentNode, 'up', function (node) {
        var data = node.data;
        if (data.status === 'failed') invalidPath = true;
      });
    }
    if (saving || !Boolean(currentNode) || invalidPath) {
      setRunAble(false);
    } else {
      setRunAble(true);
    }
  }, [currentNode, saving, nodeList, lineList]);
  useEffect(function () {
    if (!running) {
      clearInterval(checkStatusInterval);
    }
  }, [running, checkStatusInterval]);
  function queryInfo() {
    setLoading(true);
    request(apis.queryVisualInfo, {
      method: 'get',
      params: {
        id: props.taskId
      }
    }).then(function (res) {
      if (!res) return;
      var temp = res.data;
      // temp.nodeList = JSON.parse(temp.nodeList);
      setNodeList(temp.nodeList);
      setLineList(temp.lineList);
      setTask(temp);
    }).catch(function (err) {
      console.error('获取任务详情失败', err);
    }).finally(function () {
      setLoading(false);
    });
  }
  function onClickNode(node) {
    setTab('config');
    setCurrentNode(node);
  }
  function onChangeFlow(flow) {
    var nodeList = flow.nodeList,
      lineList = flow.lineList;
    setNodeList(nodeList);
    setLineList(lineList);
  }
  function onRemoveNode() {
    setTab('config');
    setCurrentNode(undefined);
  }
  // 是否启用
  var enableTaskModal = function enableTaskModal(id) {
    Modal.confirm({
      wrapClassName: 'dm-modal-confirm',
      centered: true,
      title: '提示',
      content: '任务创建成功，是否立即启用？',
      okText: '启用',
      cancelText: '不启用',
      maskClosable: false,
      onOk: function onOk() {
        request(apis.enableTask, {
          method: 'get',
          params: {
            id: id,
            enable: true
          },
          errorTitle: '操作失败'
        }).then(function (res) {
          if (!res) throw new Error();
          if (props.onSave) props.onSave();
        }).catch(function (err) {
          console.error('修改任务状态失败', err);
        });
      },
      onCancel: function onCancel() {
        if (props.onSave) props.onSave();
      }
    });
  };
  function onSubmit() {
    var _jobData$updateSettin, _jobData$updateSettin2, _jobData$updateSettin3, _jobData$updateSettin4, _jobData$updateSettin5, _jobData$updateSettin6, _jobData$updateSettin7;
    var data = {
      appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId,
      flowId: task === null || task === void 0 ? void 0 : task.flowId,
      jobData: jobData,
      nodeList: nodeList,
      lineList: lineList
    };
    console.log('jobData: ', jobData);
    if (!(jobData === null || jobData === void 0 ? void 0 : jobData.name)) {
      graph === null || graph === void 0 ? void 0 : graph.cleanSelection();
      setCurrentNode(undefined);
      notification.error({
        message: '请填写任务名称'
      });
      return;
    }
    if ((jobData === null || jobData === void 0 ? void 0 : jobData.syncType) === 2 && (jobData === null || jobData === void 0 ? void 0 : jobData.updateBy) === undefined) {
      notification.error({
        message: '更新方式，请选择字段'
      });
      return;
    }
    if ((jobData === null || jobData === void 0 ? void 0 : (_jobData$updateSettin = jobData.updateSetting) === null || _jobData$updateSettin === void 0 ? void 0 : _jobData$updateSettin.type) === ZModulesCDP.DataSet.UpdateType.timer && ((((_jobData$updateSettin2 = jobData.updateSetting.rule) === null || _jobData$updateSettin2 === void 0 ? void 0 : _jobData$updateSettin2.unit) === CycleTimeUnit.week || ((_jobData$updateSettin3 = jobData.updateSetting.rule) === null || _jobData$updateSettin3 === void 0 ? void 0 : _jobData$updateSettin3.unit) === CycleTimeUnit.month) && (!((_jobData$updateSettin4 = jobData.updateSetting.rule) === null || _jobData$updateSettin4 === void 0 ? void 0 : _jobData$updateSettin4.day) || !((_jobData$updateSettin5 = jobData.updateSetting.rule) === null || _jobData$updateSettin5 === void 0 ? void 0 : _jobData$updateSettin5.day.length)) || ((_jobData$updateSettin6 = jobData.updateSetting.rule) === null || _jobData$updateSettin6 === void 0 ? void 0 : _jobData$updateSettin6.unit) === CycleTimeUnit.custom && !((_jobData$updateSettin7 = jobData.updateSetting.rule) === null || _jobData$updateSettin7 === void 0 ? void 0 : _jobData$updateSettin7.time))) {
      notification.error({
        message: '更新设置时间不能为空'
      });
      return false;
    }
    if (props.taskId) data.jobId = task === null || task === void 0 ? void 0 : task.jobId;
    setsaving(true);
    request(props.taskId ? apis.editVisualJob : apis.createVisualJob, {
      method: 'post',
      data: data
    }).then(function (res) {
      if (!res) return;
      enableTaskModal(res.data);
    }).catch(function (err) {
      console.error('保存任务失败', err);
    }).finally(function () {
      setsaving(false);
    });
  }
  function onRun() {
    setRunning(true);
    request(apis.runVisibleJob, {
      method: 'post',
      data: {
        appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId,
        nodeList: nodeList,
        lineList: lineList,
        nodeId: currentNode === null || currentNode === void 0 ? void 0 : currentNode.id
      }
    }).then(function (res) {
      if (!res || !res.data) throw new Error('响应错误');
      setRunCode(res.data);
      FlowIterator(currentNode, 'up', function (node) {
        node.setData({
          runCode: res.data
        });
      });
      // 开启轮询刷新运行状态
      setCheckStatusInterval(setInterval(function () {
        checkRunStatus(res.data);
      }, 3000));
    }).catch(function (e) {
      console.error('执行失败', e);
      setRunning(false);
    });
  }
  function onCancelRun() {
    setRunning(false);
    setRunCode(undefined);
    FlowIterator(currentNode, 'up', function (node) {
      node.setData({
        runCode: undefined
      });
    });
  }
  function checkRunStatus(code) {
    request(apis.getRunStatus, {
      method: 'get',
      params: {
        appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId,
        jobCode: code
      }
    }).then(function (res) {
      if (!res) throw new Error('响应为空');
      if (res.data) {
        setRunning(false);
        onChangeFlow(getData(graph));
        setRunSuccess(true);
      }
    }).catch(function (err) {
      console.error('获取执行状态失败', err);
      setRunning(false);
    });
  }
  var previewHandle = function previewHandle() {
    if (!viewAble) {
      return /*#__PURE__*/React.createElement("div", {
        className: "preview-empty-box"
      }, /*#__PURE__*/React.createElement("img", {
        src: previewEmpty
      }), /*#__PURE__*/React.createElement("div", null, "\u8BF7\u5B8C\u6210\u914D\u7F6E\u540E\uFF0C\u70B9\u51FB", /*#__PURE__*/React.createElement("span", null, "\u300C\u6267\u884C\u300D"), "\u9884\u89C8\u6570\u636E"));
    } else {
      if ((currentNode === null || currentNode === void 0 ? void 0 : currentNode.shape) === CdpFlowTypes.Shape.split) {
        var _currentNode$getData, _currentNode$getData2;
        return /*#__PURE__*/React.createElement(Tabs, {
          tabBarExtraContent: /*#__PURE__*/React.createElement("div", {
            className: "".concat(classPrefix, "-tip")
          }, /*#__PURE__*/React.createElement(IconFont, {
            type: "tishiicon"
          }), "\u63D0\u793A\uFF1A\u9884\u89C8\u6570\u636E\u529F\u80FD\u53EF\u80FD\u5E2E\u52A9\u60A8\u4ECE\u7ED3\u679C\u6570\u636E\u4E2D\u62BD\u53D6\u524D10\u6761\u4F5C\u4E3A\u6837\u4F8B\u6570\u636E\u8FDB\u884C\u67E5\u770B\u3002")
        }, /*#__PURE__*/React.createElement(Tabs.TabPane, {
          tab: "\u88681",
          key: "a"
        }, /*#__PURE__*/React.createElement(OverviewData, {
          nodeCode: currentNode === null || currentNode === void 0 ? void 0 : (_currentNode$getData = currentNode.getData()) === null || _currentNode$getData === void 0 ? void 0 : _currentNode$getData.code,
          isOutput: false
        })), /*#__PURE__*/React.createElement(Tabs.TabPane, {
          tab: "\u88682",
          key: "b"
        }, /*#__PURE__*/React.createElement(OverviewData, {
          nodeCode: "".concat(currentNode === null || currentNode === void 0 ? void 0 : (_currentNode$getData2 = currentNode.getData()) === null || _currentNode$getData2 === void 0 ? void 0 : _currentNode$getData2.code, "_2"),
          isOutput: false
        })));
      } else {
        var _currentNode$getData3;
        return /*#__PURE__*/React.createElement(OverviewData, {
          nodeCode: currentNode === null || currentNode === void 0 ? void 0 : (_currentNode$getData3 = currentNode.getData()) === null || _currentNode$getData3 === void 0 ? void 0 : _currentNode$getData3.code,
          isOutput: (currentNode === null || currentNode === void 0 ? void 0 : currentNode.shape) === CdpFlowTypes.Shape.output
        });
      }
    }
  };
  if (loading || props.taskId && !task) {
    return /*#__PURE__*/React.createElement("div", {
      className: classPrefix
    }, /*#__PURE__*/React.createElement(Spin, {
      className: "".concat(classPrefix, "-loading")
    }));
  }
  var viewAble = (currentNode === null || currentNode === void 0 ? void 0 : currentNode.getData().runCode) === runCode && runCode;
  return /*#__PURE__*/React.createElement("div", {
    className: classPrefix
  }, running ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-running")
  }, /*#__PURE__*/React.createElement(Spin, {
    size: "large",
    tip: /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement("span", {
      className: "".concat(classPrefix, "-runtip")
    }, "\u4EFB\u52A1\u6267\u884C\u4E2D\uFF0C\u8BF7\u7B49\u5F85..."), /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      onClick: onCancelRun
    }, "\u53D6\u6D88"))
  })) : null, graph && /*#__PURE__*/React.createElement(TableList, {
    graph: graph,
    nodeList: nodeList
  }), /*#__PURE__*/React.createElement(TaskContext.Provider, {
    value: {
      mode: task ? 'edit' : 'create',
      taskId: task === null || task === void 0 ? void 0 : task.jobId
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-content")
  }, /*#__PURE__*/React.createElement(VisualFlow, {
    className: "".concat(classPrefix, "-flow"),
    defaultValue: task ? task : undefined,
    onChange: onChangeFlow,
    onRemoveNode: onRemoveNode,
    onBack: props.onBack,
    onReady: setGraph,
    onClickNode: onClickNode
  }), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-config")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-config-head")
  }, /*#__PURE__*/React.createElement("span", null, "\u914D\u7F6E"), /*#__PURE__*/React.createElement(Radio.Group, {
    defaultValue: "config",
    value: tab,
    onChange: function onChange(e) {
      setTab(e.target.value);
    }
  }, /*#__PURE__*/React.createElement(Radio.Button, {
    value: "config"
  }, "\u914D\u7F6E"), /*#__PURE__*/React.createElement(Radio.Button, {
    value: "overview"
  }, "\u9884\u89C8\u6570\u636E")), /*#__PURE__*/React.createElement(Button, {
    className: "run",
    disabled: !runAble || isDemo,
    loading: running,
    onClick: onRun
  }, "\u6267\u884C"), /*#__PURE__*/React.createElement(Button, {
    loading: saving,
    disabled: running || isDemo,
    type: "primary",
    onClick: onSubmit
  }, "\u4FDD\u5B58"), /*#__PURE__*/React.createElement(Button, {
    onClick: props.onBack
  }, "\u53D6\u6D88")), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-config-content"),
    key: currentNode === null || currentNode === void 0 ? void 0 : currentNode.id
  }, function () {
    if (tab === 'overview') {
      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(classPrefix, "-overview ").concat((currentNode === null || currentNode === void 0 ? void 0 : currentNode.shape) === CdpFlowTypes.Shape.split ? 'split' : '')
      }, previewHandle());
    } else if (tab === 'log') {
      return /*#__PURE__*/React.createElement(FlowCheckLog, {
        nodeCode: currentNode === null || currentNode === void 0 ? void 0 : currentNode.getData().code,
        jobId: task === null || task === void 0 ? void 0 : task.jobId,
        runCode: runCode
      });
    }
    switch (currentNode === null || currentNode === void 0 ? void 0 : currentNode.data.shape) {
      case CdpFlowTypes.Shape.table:
        return /*#__PURE__*/React.createElement(TableConfig, {
          node: currentNode,
          key: currentNode.id
        });
      case CdpFlowTypes.Shape.output:
        return /*#__PURE__*/React.createElement(OutputConfig, {
          key: currentNode.id,
          node: currentNode
        });
      case CdpFlowTypes.Shape.merge:
        return /*#__PURE__*/React.createElement(MergeConfig, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.join:
        return /*#__PURE__*/React.createElement(FlowJoinConfig, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.columnSetting:
        return /*#__PURE__*/React.createElement(FlowColumnSetting, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.group:
        return /*#__PURE__*/React.createElement(FlowGroupConfig, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.row2Column:
        return /*#__PURE__*/React.createElement(FlowRow2Column, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.column2Row:
        return /*#__PURE__*/React.createElement(FlowColumn2RowConfig, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.split:
        return /*#__PURE__*/React.createElement(FlowSplitConfig, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.distinct:
        return /*#__PURE__*/React.createElement(DistinctConfig, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.mergeColumn:
        return /*#__PURE__*/React.createElement(MergeColumnConfig, {
          node: currentNode,
          nodeList: nodeList
        });
      case CdpFlowTypes.Shape.splitColumn:
        return /*#__PURE__*/React.createElement(SplitColumnConfig, {
          node: currentNode,
          nodeList: nodeList
        });
      case CdpFlowTypes.Shape.replaceNull:
        return /*#__PURE__*/React.createElement(ReplaceNullConfig, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.computeColumn:
        return /*#__PURE__*/React.createElement(ComputeColumnConfig, {
          node: currentNode,
          nodeList: nodeList
        });
      case CdpFlowTypes.Shape.sqlShell:
        return /*#__PURE__*/React.createElement(SqlShellConfig, {
          node: currentNode
        });
      case CdpFlowTypes.Shape.dataClean:
        return /*#__PURE__*/React.createElement(DataCleanConfig, {
          node: currentNode,
          nodeList: nodeList
        });
      default:
        return /*#__PURE__*/React.createElement(FlowGlobalConfig, {
          value: jobData ? jobData : undefined,
          flowData: {
            nodeList: nodeList,
            lineList: lineList
          },
          onChange: setJobData
        });
    }
  }())))));
};
export default CdpVisualCreator;