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 { Button, notification, Result, Spin, Modal } from 'antd';
import React, { useContext, useEffect, useState, useRef } from 'react';
import ZModulesCDP from '../../types';
import BaseForm from './baseForm';
import UpdateForm from './updateForm';
import CdpColumnSelect from './columnSelect';
import './styles/index.less';
import TableSelect from './tableSelect';
import _ from 'lodash';
import { BizGlobalDataContext } from '@zgfe/business-lib';
import request from '../../utils/ajax';
import apis from '../../constants/api';
import TaskContext from '../../modules/createJob/context';
import EffectTaskDialog from '../../modules/jobList/effectDialog';
import { CycleTimeUnit } from '@zgfe/business-lib/es/cycleTime';
var JobCreator = function JobCreator(props) {
  var _useContext = useContext(TaskContext),
    mode = _useContext.mode,
    taskId = _useContext.taskId;
  var classPrefix = 'cdp-dataset-create';
  var _useContext2 = useContext(BizGlobalDataContext),
    currentApp = _useContext2.currentApp,
    isDemo = _useContext2.isDemo;
  var _useState = useState(),
    _useState2 = _slicedToArray(_useState, 2),
    tableForm = _useState2[0],
    setTableForm = _useState2[1];
  var _useState3 = useState({
      appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId
    }),
    _useState4 = _slicedToArray(_useState3, 2),
    queryParam = _useState4[0],
    setQueryParam = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    creating = _useState6[0],
    setCreating = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    infoReady = _useState8[0],
    setInfoReady = _useState8[1];
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    infoFail = _useState10[0],
    setInfoFail = _useState10[1];
  var _useState11 = useState(),
    _useState12 = _slicedToArray(_useState11, 2),
    taskInfo = _useState12[0],
    setTaskInfo = _useState12[1];
  var _useState13 = useState(true),
    _useState14 = _slicedToArray(_useState13, 2),
    columnListLoading = _useState14[0],
    setColumnListLoading = _useState14[1];
  var _useState15 = useState(false),
    _useState16 = _slicedToArray(_useState15, 2),
    showWarn = _useState16[0],
    setShowWarn = _useState16[1];
  var _useState17 = useState(false),
    _useState18 = _slicedToArray(_useState17, 2),
    columnFail = _useState18[0],
    setColumnFail = _useState18[1];
  useEffect(function () {
    if (mode === 'edit') getInfo();
  }, []);
  function getInfo() {
    setInfoReady(false);
    setInfoFail(false);
    request(apis.getTaskInfo, {
      method: 'get',
      params: {
        id: taskId
      }
    }).then(function (res) {
      var _res$data;
      if (!res) throw new Error();
      // 如果当前应用id与任务的所属应用不匹配，则跳转到列表页面
      if ((currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId) !== ((_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.appId) && props.onCancel) {
        setTimeout(function () {
          props.onCancel();
        });
        return;
      }
      setTaskInfo(res.data);
      setInfoReady(true);
    }).catch(function (err) {
      setInfoFail(true);
      setInfoReady(true);
      console.error('获取任务详情失败', err);
    });
  }
  var formRef = useRef();
  var formRef1 = useRef();
  /**
   * 新建模式，校验参数成功后，直接进行保存
   * 编辑模式，校验参数成功后，进行保存提示
   */
  function onWarning() {
    formRef.current.formSubmit();
    formRef1.current.formSubmit();
    if (!checkParam()) return;
    if (mode === 'edit') {
      setShowWarn(true);
    } else {
      onSubmit();
    }
  }
  // 是否启用
  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.onOk) props.onOk();
        }).catch(function (err) {
          console.error('修改任务状态失败', err);
        });
      },
      onCancel: function onCancel() {
        if (props.onOk) props.onOk();
      }
    });
  };
  function onSubmit() {
    setCreating(true);
    request(apis.createTask, {
      method: 'post',
      data: queryParam,
      errorTitle: '保存失败'
    }).then(function (res) {
      if (!res) throw new Error();
      setShowWarn(false);
      enableTaskModal(res.data);
    }).catch(function (err) {
      console.error('创建数据集任务失败', err);
    }).finally(function () {
      setCreating(false);
    });
  }
  function onEdit(callback) {
    setCreating(true);
    request(apis.editTask, {
      method: 'post',
      data: _objectSpread({
        id: taskId
      }, queryParam),
      errorTitle: '保存失败'
    }).then(function (res) {
      if (!res) throw new Error();
      notification.success({
        message: '保存成功'
      });
      callback();
      setShowWarn(false);
      if (props.onOk) props.onOk();
    }).catch(function (err) {
      console.error('编辑数据集任务失败', err);
      callback();
    }).finally(function () {
      setCreating(false);
    });
  }
  function checkParam() {
    var _param$columns, _param$updateSetting$, _param$updateSetting$2, _param$updateSetting$3, _param$updateSetting$4, _param$updateSetting$5, _param$updateSetting$6;
    var param = queryParam;
    if (!param.jobName) {
      notification.error({
        message: '任务名称不能为空'
      });
      return false;
    }
    if (!param.datasetName) {
      notification.error({
        message: '数据集名称不能为空'
      });
      return false;
    }
    if (!param.dbType) {
      notification.error({
        message: '请选择数据库类型'
      });
      return false;
    }
    if (!param.dbSourceId) {
      notification.error({
        message: '请选择数据源'
      });
      return false;
    }
    if (!param.dbTableName && param.dbType !== 'api') {
      notification.error({
        message: '请选择数据表'
      });
      return false;
    }
    if (!((_param$columns = param.columns) === null || _param$columns === void 0 ? void 0 : _param$columns.length)) {
      notification.error({
        message: '请选择字段列表'
      });
      return false;
    }
    if (columnFail) {
      notification.error({
        message: '数据筛选条件异常'
      });
      return false;
    }
    if (param.syncType === ZModulesCDP.DataSet.SyncType.incre && !param.updateBy) {
      notification.error({
        message: '更新方式，请选择字段'
      });
      return false;
    }
    console.log('param.updateSetting: ', param.updateSetting);
    if (param.updateSetting.type === ZModulesCDP.DataSet.UpdateType.timer && ((((_param$updateSetting$ = param.updateSetting.rule) === null || _param$updateSetting$ === void 0 ? void 0 : _param$updateSetting$.unit) === CycleTimeUnit.week || ((_param$updateSetting$2 = param.updateSetting.rule) === null || _param$updateSetting$2 === void 0 ? void 0 : _param$updateSetting$2.unit) === CycleTimeUnit.month) && (!((_param$updateSetting$3 = param.updateSetting.rule) === null || _param$updateSetting$3 === void 0 ? void 0 : _param$updateSetting$3.day) || !((_param$updateSetting$4 = param.updateSetting.rule) === null || _param$updateSetting$4 === void 0 ? void 0 : _param$updateSetting$4.day.length)) || ((_param$updateSetting$5 = param.updateSetting.rule) === null || _param$updateSetting$5 === void 0 ? void 0 : _param$updateSetting$5.unit) === CycleTimeUnit.custom && !((_param$updateSetting$6 = param.updateSetting.rule) === null || _param$updateSetting$6 === void 0 ? void 0 : _param$updateSetting$6.time))) {
      notification.error({
        message: '更新设置时间不能为空'
      });
      return false;
    }
    return true;
  }
  if (mode === 'edit') {
    if (infoFail) {
      return /*#__PURE__*/React.createElement("div", {
        className: classPrefix
      }, /*#__PURE__*/React.createElement(Result, {
        status: "error",
        className: "".concat(classPrefix, "-reload"),
        subTitle: "\u4EFB\u52A1\u8BE6\u60C5\u52A0\u8F7D\u5931\u8D25",
        extra: /*#__PURE__*/React.createElement(Button, {
          onClick: getInfo,
          type: "primary"
        }, "\u91CD\u65B0\u52A0\u8F7D")
      }));
    }
    if (!infoReady) {
      return /*#__PURE__*/React.createElement("div", {
        className: classPrefix
      }, /*#__PURE__*/React.createElement(Spin, {
        className: "".concat(classPrefix, "-loading")
      }));
    }
  }
  return /*#__PURE__*/React.createElement("div", {
    className: classPrefix
  }, /*#__PURE__*/React.createElement(BaseForm
  // key={`${(queryParam as ZModulesCDP.DataSet.CreateParam).dbSourceId}-${(queryParam as ZModulesCDP.DataSet.CreateParam).dbTableName
  //   }`}
  , {
    // key={`${(queryParam as ZModulesCDP.DataSet.CreateParam).dbSourceId}-${(queryParam as ZModulesCDP.DataSet.CreateParam).dbTableName
    //   }`}
    dbType: queryParam.dbType,
    columnList: queryParam.columns || [],
    task: taskInfo,
    loading: columnListLoading,
    ref: formRef,
    onChange: function onChange(data) {
      setQueryParam(function (param) {
        var res = _.cloneDeep(param);
        res.jobName = data.jobName;
        res.jobDesc = data.jobDesc;
        return res;
      });
    }
  }), /*#__PURE__*/React.createElement(TableSelect, {
    task: taskInfo,
    ref: formRef1,
    onChange: function onChange(data) {
      setTableForm(data);
      setQueryParam(function (param) {
        var res = _.cloneDeep(param);
        res.dbType = data.dbType;
        res.dbSourceId = data.database;
        res.dbTableName = data.table;
        res.datasetName = data.dataset;
        return res;
      });
    }
  }), /*#__PURE__*/React.createElement(CdpColumnSelect, {
    task: taskInfo,
    dataSourceId: tableForm === null || tableForm === void 0 ? void 0 : tableForm.database,
    tableName: tableForm === null || tableForm === void 0 ? void 0 : tableForm.table,
    dbType: queryParam.dbType,
    onFail: setColumnFail,
    onChange: function onChange(data, loading) {
      setQueryParam(function (param) {
        var res = _.cloneDeep(param);
        res.columns = data.columns;
        res.columnRules = data.columnRules;
        return res;
      });
      setColumnListLoading(loading);
    }
  }), /*#__PURE__*/React.createElement(UpdateForm
  // key={`${(queryParam as ZModulesCDP.DataSet.CreateParam).dbSourceId}-${(queryParam as ZModulesCDP.DataSet.CreateParam).dbTableName
  //   }`}
  , {
    // key={`${(queryParam as ZModulesCDP.DataSet.CreateParam).dbSourceId}-${(queryParam as ZModulesCDP.DataSet.CreateParam).dbTableName
    //   }`}
    dbType: queryParam.dbType,
    columnList: queryParam.columns || [],
    task: taskInfo,
    loading: columnListLoading,
    onChange: function onChange(data) {
      setQueryParam(function (param) {
        var _data$sync, _data$sync2;
        var res = _.cloneDeep(param);
        res.syncType = ((_data$sync = data.sync) === null || _data$sync === void 0 ? void 0 : _data$sync.syncType) || ZModulesCDP.DataSet.SyncType.global;
        res.updateBy = (_data$sync2 = data.sync) === null || _data$sync2 === void 0 ? void 0 : _data$sync2.updateBy;
        res.updateSetting = data === null || data === void 0 ? void 0 : data.updateSetting;
        // if (res.updateSetting.rule) res.updateSetting.rule!.time = '00:00:00';
        return res;
      });
    }
  }), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-foot")
  }, /*#__PURE__*/React.createElement(Button, {
    onClick: props.onCancel
  }, "\u53D6\u6D88"), /*#__PURE__*/React.createElement(Button, {
    onClick: onWarning,
    type: "primary",
    disabled: isDemo,
    loading: creating
  }, "\u786E\u5B9A")), showWarn && mode === 'edit' ? /*#__PURE__*/React.createElement(EffectTaskDialog, {
    taskId: taskId,
    mode: 'edit',
    onCancel: function onCancel() {
      setShowWarn(false);
    },
    onOk: onEdit
  }) : null);
};
export default JobCreator;