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 { BizGlobalDataContext, IconFont } from '@zgfe/business-lib';
import { Button, Form, Input, notification, Result, Table } from 'antd';
import moment from 'moment';
import React, { useContext, useEffect, useRef, useState } from 'react';
import CheckTaskLog from '../../components/checkLog';
import apis from '../../constants/api';
import ZModulesCDP from '../../types';
import request from '../../utils/ajax';
import EffectTaskDialog from './effectDialog';
import TaskEnableSwitch from './enableSwitch';
import './styles/index.less';
import _ from 'lodash';
var classPrefix = 'dataset-list';
export var stateColumn = {
  title: '状态',
  dataIndex: 'state',
  render: function render(v) {
    switch (v) {
      case ZModulesCDP.DataSet.UpdateState.fail:
        return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
          className: "".concat(classPrefix, "-state fail")
        }), "\u5931\u8D25");
      case ZModulesCDP.DataSet.UpdateState.success:
        return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
          className: "".concat(classPrefix, "-state success")
        }), "\u6210\u529F");
      case ZModulesCDP.DataSet.UpdateState.running:
        return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
          className: "".concat(classPrefix, "-state running")
        }), "\u6267\u884C\u4E2D");
      default:
        return /*#__PURE__*/React.createElement(React.Fragment, null, "-");
    }
  }
};
export function dateRender(date) {
  if (!date) return '-';
  return moment(date).format('YYYY-MM-DD HH:mm:ss');
}
export function dateSorter(a, b, field) {
  if (!a[field]) return -1;
  if (!b[field]) return 1;
  return moment(a[field]).toDate().getTime() - moment(b[field]).toDate().getTime();
}
var Run = function Run(props) {
  var task = props.task;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    inRunning = _useState2[0],
    setInRunning = _useState2[1];
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    disabled = _useState4[0],
    setDisable = _useState4[1];
  var _useContext = useContext(BizGlobalDataContext),
    isDemo = _useContext.isDemo;
  useEffect(function () {
    setDisable(isDemo || inRunning || [ZModulesCDP.DataSet.TaskStatus.disable, ZModulesCDP.DataSet.TaskStatus.invalid].includes(task.status) || task.state === ZModulesCDP.DataSet.UpdateState.running);
  }, [task.status]);
  function onRun() {
    setInRunning(true);
    request(apis.runTask, {
      method: 'get',
      params: {
        id: task.id
      },
      errorTitle: '操作失败'
    }).then(function (res) {
      if (!res) throw new Error();
      notification.success({
        message: '操作成功，开始执行'
      });
      if (props.onSuccess) props.onSuccess();
    }).catch(function (err) {
      console.error('执行任务失败', err);
    }).finally(function () {
      setInRunning(false);
    });
  }
  return /*#__PURE__*/React.createElement("a", {
    className: "".concat(classPrefix, "-btn-update ").concat(disabled ? 'disable' : ''),
    onClick: function onClick() {
      if (disabled) return;
      onRun();
    }
  }, "\u624B\u52A8\u66F4\u65B0");
};
export function getUpdateColumn(callback) {
  var updateColumn = {
    title: '更新方式',
    dataIndex: 'updateType',
    render: function render(v, data) {
      return ZModulesCDP.DataSet.UpdateType.mumal === v ? /*#__PURE__*/React.createElement(Run, {
        task: data,
        onSuccess: callback
      }) : '自动更新';
    }
  };
  return updateColumn;
}
var CdpJobList = function CdpJobList(props) {
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    store = _useState6[0],
    setStore = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    fail = _useState8[0],
    setFail = _useState8[1];
  var _useState9 = useState(true),
    _useState10 = _slicedToArray(_useState9, 2),
    loading = _useState10[0],
    setLoading = _useState10[1];
  var _useState11 = useState(),
    _useState12 = _slicedToArray(_useState11, 2),
    condition = _useState12[0],
    setCondition = _useState12[1];
  var formRef = useRef();
  var _useState13 = useState(0),
    _useState14 = _slicedToArray(_useState13, 2),
    queryTimer = _useState14[0],
    setQueryTimer = _useState14[1];
  var _useState15 = useState(),
    _useState16 = _slicedToArray(_useState15, 2),
    currentTask = _useState16[0],
    setCurrentTask = _useState16[1];
  var _useState17 = useState(false),
    _useState18 = _slicedToArray(_useState17, 2),
    showLog = _useState18[0],
    setShowLog = _useState18[1];
  var _useState19 = useState(false),
    _useState20 = _slicedToArray(_useState19, 2),
    showDel = _useState20[0],
    setShowDel = _useState20[1];
  var _useContext2 = useContext(BizGlobalDataContext),
    currentApp = _useContext2.currentApp,
    isDemo = _useContext2.isDemo;
  var _useState21 = useState({
      current: 1
    }),
    _useState22 = _slicedToArray(_useState21, 2),
    pagination = _useState22[0],
    setPagination = _useState22[1];
  useEffect(function () {
    clearTimeout(queryTimer);
    setQueryTimer(setTimeout(queryData, 300));
  }, [condition]);
  function onChangeCondition() {
    var _formRef$current;
    (_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.submit();
  }
  function onSearch(data) {
    setCondition(data);
  }
  function onCheckLog(data) {
    setCurrentTask(data);
    setShowLog(true);
  }
  function onDel(data) {
    setCurrentTask(data);
    setShowDel(true);
  }
  function queryData() {
    setFail(false);
    setLoading(true);
    setStore([]);
    request(apis.queryDataset, {
      method: 'post',
      data: _objectSpread(_objectSpread({}, condition), {}, {
        appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId,
        datasetId: props.datasetId
      })
    }).then(function (res) {
      if (!res) throw new Error();
      setStore(res.data);
    }).catch(function (err) {
      console.error('查询任务列表失败', err);
      setFail(true);
    }).finally(function () {
      setLoading(false);
    });
  }
  var columns = [{
    title: '任务名称',
    dataIndex: 'jobName'
  }, {
    title: '数据集名称',
    dataIndex: 'datasetName'
  }, {
    title: '表名',
    dataIndex: 'tableName'
  }, {
    title: '创建人',
    dataIndex: 'creator'
  }, {
    title: '创建时间',
    dataIndex: 'createTime',
    render: dateRender,
    sorter: function sorter(a, b) {
      return dateSorter(a, b, 'createTime');
    }
  }, {
    title: '最近更新完成时间',
    dataIndex: 'lastUpdateTime',
    render: dateRender,
    sorter: function sorter(a, b) {
      return dateSorter(a, b, 'lastUpdateTime');
    }
  }, {
    title: '下次执行时间',
    dataIndex: 'nextRunTime',
    render: dateRender,
    sorter: function sorter(a, b) {
      return dateSorter(a, b, 'nextRunTime');
    }
  }, getUpdateColumn(function () {
    setTimeout(queryData);
  }), stateColumn, {
    title: '类型',
    dataIndex: 'dbType',
    render: function render(type, record) {
      if (record.jobType === ZModulesCDP.DataSet.JobType.visual) return '可视化数据集';
      return type;
    }
  }, {
    title: '操作',
    fixed: 'right',
    render: function render(_v, data) {
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(TaskEnableSwitch, {
        task: data,
        onChange: function onChange(status) {
          setStore(function (store) {
            var res = _.cloneDeep(store);
            res.forEach(function (item, i) {
              if (item.id === data.id) {
                res[i].status = status;
              }
            });
            return res;
          });
        }
      }), /*#__PURE__*/React.createElement("a", {
        className: "".concat(classPrefix, "-edit ").concat(data.status === ZModulesCDP.DataSet.TaskStatus.enable ? 'disable' : ''),
        onClick: function onClick() {
          if (data.status === ZModulesCDP.DataSet.TaskStatus.enable) return;
          if (props.onEdit) props.onEdit(data);
        }
      }, "\u8BE6\u60C5"), /*#__PURE__*/React.createElement("a", {
        className: "".concat(classPrefix, "-del ").concat(isDemo || data.status === ZModulesCDP.DataSet.TaskStatus.enable ? 'disable' : ''),
        onClick: function onClick() {
          if (isDemo || data.status === ZModulesCDP.DataSet.TaskStatus.enable) return;
          onDel(data);
        }
      }, "\u5220\u9664"), /*#__PURE__*/React.createElement("a", {
        className: "".concat(classPrefix, "-log"),
        onClick: function onClick() {
          onCheckLog(data);
        }
      }, "\u65E5\u5FD7"), /*#__PURE__*/React.createElement("a", {
        className: "".concat(classPrefix, "-log ").concat(!data.tableName ? 'disable' : ''),
        onClick: function onClick() {
          if (!data.tableName) return;
          if (props.onCheckDesc) props.onCheckDesc(data);
        }
      }, "\u67E5\u770B\u8868\u7ED3\u6784"));
    }
  }];
  return /*#__PURE__*/React.createElement("div", {
    className: classPrefix
  }, /*#__PURE__*/React.createElement(Form, {
    ref: formRef,
    layout: "inline",
    colon: false,
    onFinish: onSearch,
    onChange: onChangeCondition
  }, /*#__PURE__*/React.createElement(Form.Item, {
    name: "name"
  }, /*#__PURE__*/React.createElement(Input, {
    placeholder: "\u6570\u636E\u96C6\u540D\u79F0/\u521B\u5EFA\u4EBA",
    prefix: /*#__PURE__*/React.createElement(IconFont, {
      type: "sousuo"
    }),
    className: "".concat(classPrefix, "-name"),
    autoComplete: "off",
    autoFocus: true
  }))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-bottom")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-toolbar")
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(classPrefix, "-result")
  }, "\u5171\u641C\u7D22\u5230", store.length, "\u6761\u6570\u636E"), !props.datasetId && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    className: "".concat(classPrefix, "-btn-add"),
    icon: /*#__PURE__*/React.createElement(IconFont, {
      type: "tianjia1",
      size: 14
    }),
    onClick: props.onCreatVisual
  }, "\u53EF\u89C6\u5316\u6570\u636E\u96C6"), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    icon: /*#__PURE__*/React.createElement(IconFont, {
      type: "tianjia1",
      size: 14
    }),
    className: "".concat(classPrefix, "-btn-add"),
    onClick: props.onCreat
  }, "\u6570\u636E\u540C\u6B65"))), function () {
    if (fail) {
      return /*#__PURE__*/React.createElement(Result, {
        subTitle: "\u67E5\u8BE2\u5217\u8868\u5931\u8D25",
        status: "error",
        extra: /*#__PURE__*/React.createElement(Button, {
          onClick: queryData
        }, "\u91CD\u65B0\u67E5\u8BE2")
      });
    }
    return /*#__PURE__*/React.createElement(Table, {
      className: "".concat(classPrefix, "-table"),
      columns: columns,
      dataSource: store,
      loading: loading,
      rowKey: "id",
      pagination: {
        current: pagination.current,
        showTotal: function showTotal(total) {
          return /*#__PURE__*/React.createElement(React.Fragment, null, "\u5171", /*#__PURE__*/React.createElement("span", {
            className: "".concat(classPrefix, "-total")
          }, total), "\u6761");
        },
        onChange: function onChange(page) {
          setPagination({
            current: page
          });
        }
      },
      scroll: {
        x: true
      }
    });
  }()), currentTask && showLog ? /*#__PURE__*/React.createElement(CheckTaskLog, {
    taskId: currentTask.id,
    onClose: function onClose() {
      setShowLog(false);
    }
  }) : null, currentTask && showDel ? /*#__PURE__*/React.createElement(EffectTaskDialog, {
    taskId: currentTask.id,
    mode: "del",
    onOk: function onOk(callback) {
      request(apis.delTask, {
        method: 'get',
        params: {
          id: currentTask.id
        },
        errorTitle: '删除失败'
      }).then(function (res) {
        if (!res) throw new Error();
        callback();
        setShowDel(false);
        queryData();
      }).catch(function (err) {
        console.error('删除任务失败', err);
        callback();
      });
    },
    onCancel: function onCancel() {
      setShowDel(false);
    }
  }) : null);
};
export default CdpJobList;