function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
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),
    isDemo = _useContext2.isDemo,
    currentProject = _useContext2.currentProject;
  var _useState = useState(),
    _useState2 = _slicedToArray(_useState, 2),
    tableForm = _useState2[0],
    setTableForm = _useState2[1];
  var _useState3 = useState({
      projectId: currentProject === null || currentProject === void 0 ? void 0 : currentProject.projectId
    }),
    _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),
    _useState0 = _slicedToArray(_useState9, 2),
    infoFail = _useState0[0],
    setInfoFail = _useState0[1];
  var _useState1 = useState(),
    _useState10 = _slicedToArray(_useState1, 2),
    taskInfo = _useState10[0],
    setTaskInfo = _useState10[1];
  var _useState11 = useState(true),
    _useState12 = _slicedToArray(_useState11, 2),
    columnListLoading = _useState12[0],
    setColumnListLoading = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    showWarn = _useState14[0],
    setShowWarn = _useState14[1];
  var _useState15 = useState(false),
    _useState16 = _slicedToArray(_useState15, 2),
    columnFail = _useState16[0],
    setColumnFail = _useState16[1];
  useEffect(function () {
    if (mode === 'edit') getInfo();
  }, []);
  function getInfo() {
    setInfoReady(false);
    setInfoFail(false);
    request(apis.getTaskInfo, {
      method: 'get',
      params: {
        id: taskId
      }
    }).then(function (res) {
      if (!res) throw new Error();
      // 如果当前应用id与任务的所属应用不匹配，则跳转到列表页面
      // if (currentApp?.appId !== res.data?.appId && props.onCancel) {
      //   setTimeout(() => {
      //     props.onCancel!();
      //   });
      //   return;
      // }
      setTaskInfo(res.data);
      setInfoReady(true);
    }).catch(function (err) {
      setInfoFail(true);
      setInfoReady(true);
      console.error('获取任务详情失败', err);
    });
  }
  var formRef = useRef(null);
  var formRef1 = useRef(null);
  /**
   * 新建模式，校验参数成功后，直接进行保存
   * 编辑模式，校验参数成功后，进行保存提示
   */
  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$updateBy, _param$updateBy2, _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 && Object.keys(param.updateBy).length <= 0) {
      notification.error({
        message: '更新方式，请选择字段'
      });
      return false;
    }
    if ((param === null || param === void 0 ? void 0 : (_param$updateBy = param.updateBy) === null || _param$updateBy === void 0 ? void 0 : _param$updateBy.webType) === 'date' && !(param === null || param === void 0 ? void 0 : (_param$updateBy2 = param.updateBy) === null || _param$updateBy2 === void 0 ? void 0 : _param$updateBy2.dateFormat)) {
      notification.error({
        message: '更新方式，请输入日期格式'
      });
      return false;
    }
    // console.log('param.updateSetting: ', param);
    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;