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, BizSelect } from '@zgfe/business-lib';
import { Button, Form, Input, message, notification, Result, Table, Tooltip } from 'antd';
import moment from 'moment';
import React, { useContext, useEffect, useRef, useState } from 'react';
import CheckTaskLog from '../../components/checkLog';
import apis from '../../constants/dataoutputApi';
import ZModulesCDP from '../../types';
import request from '../../utils/ajax';
import EffectTaskDialog from './effectDialog';
import TaskEnableSwitch from './enableSwitch';
import './styles/index.less';
import _ from 'lodash';
import StatusDrawer from './StatusDrawer';
import { ExclamationCircleOutlined } from '@ant-design/icons';
var classPrefix = 'dataset-list';
// 状态筛选选项
var statusOptions = [{
  value: 0,
  label: '未启用'
}, {
  value: 1,
  label: '更新中'
}, {
  value: 2,
  label: '成功'
}, {
  value: 3,
  label: '失败'
}];
export function dateRender(date) {
  if (!date) return '-';
  return moment(date).format('YYYY-MM-DD HH:mm:ss');
}
var DataOutPut = function DataOutPut(props) {
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    store = _useState2[0],
    setStore = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    fail = _useState4[0],
    setFail = _useState4[1];
  var _useState5 = useState(true),
    _useState6 = _slicedToArray(_useState5, 2),
    loading = _useState6[0],
    setLoading = _useState6[1];
  var _useState7 = useState(),
    _useState8 = _slicedToArray(_useState7, 2),
    condition = _useState8[0],
    setCondition = _useState8[1];
  var formRef = useRef();
  var _useState9 = useState(0),
    _useState10 = _slicedToArray(_useState9, 2),
    queryTimer = _useState10[0],
    setQueryTimer = _useState10[1];
  var _useState11 = useState(),
    _useState12 = _slicedToArray(_useState11, 2),
    currentTask = _useState12[0],
    setCurrentTask = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    showLog = _useState14[0],
    setShowLog = _useState14[1];
  var _useState15 = useState(false),
    _useState16 = _slicedToArray(_useState15, 2),
    showDel = _useState16[0],
    setShowDel = _useState16[1];
  var _useContext = useContext(BizGlobalDataContext),
    currentApp = _useContext.currentApp;
  var _useState17 = useState(1),
    _useState18 = _slicedToArray(_useState17, 2),
    total = _useState18[0],
    setTotal = _useState18[1];
  var _React$useState = React.useState(10),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    pageSize = _React$useState2[0],
    setPageSize = _React$useState2[1];
  var _React$useState3 = React.useState(1),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    pageNum = _React$useState4[0],
    setPageNum = _React$useState4[1];
  var _useState19 = useState({
      field: 'create_time',
      order: 'desc'
    }),
    _useState20 = _slicedToArray(_useState19, 2),
    sortLists = _useState20[0],
    setSortLists = _useState20[1];
  var _useState21 = useState({
      value: -1
    }),
    _useState22 = _slicedToArray(_useState21, 2),
    statusValue = _useState22[0],
    setStatusValue = _useState22[1];
  var _React$useState5 = React.useState(false),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    drawerVisible = _React$useState6[0],
    setDrawerVisible = _React$useState6[1];
  useEffect(function () {
    clearTimeout(queryTimer);
    setQueryTimer(setTimeout(queryData, 300));
  }, [condition, statusValue.value, sortLists, pageNum]); // 处理表格变化
  // 处理表格排序
  var handleTableChange = function handleTableChange(pagination, filters, sorter) {
    var newSort = {
      field: 'create_time',
      order: 'desc'
    };
    if (sorter.field) {
      var _sorter$order;
      newSort = {
        field: sorter.field === 'createTime' ? 'create_time' : 'last_update_time',
        order: (_sorter$order = sorter.order) === null || _sorter$order === void 0 ? void 0 : _sorter$order.replace('end', '')
      };
    }
    setSortLists(newSort);
    setPageNum(pagination.current);
    setPageSize(pagination.pageSize);
  };
  function onChangeCondition() {
    var _formRef$current;
    (_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.submit();
  }
  //搜索
  function onSearch(data) {
    setCondition(data);
    setPageNum(1); // 增加分页重置
    setPageSize(10); // 可选，如果需要保持每页数量一致
  }
  //日志
  function onCheckLog(data) {
    setCurrentTask(data);
    setDrawerVisible(true);
  }
  //删除
  function onDel(data) {
    setCurrentTask(data);
    setShowDel(true);
  }
  // 重跑任务
  function handleRerun(v, r) {
    request(apis.returnLog, {
      method: 'get',
      params: {
        taskId: r.taskId
      }
    }).then(function (res) {
      if (!res) throw new Error();
      queryData();
    }).catch(function (err) {
      console.error('重跑失败', err);
    });
  }
  //查询列表数据
  function queryData() {
    setFail(false);
    setLoading(true);
    setStore([]);
    console.log(sortLists, 'sortLists');
    request(apis.queryDataExtList, {
      method: 'post',
      data: _objectSpread(_objectSpread({}, condition), {}, {
        appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId,
        sortLists: sortLists,
        jobStatus: statusValue === null || statusValue === void 0 ? void 0 : statusValue.value,
        pageSize: pageSize,
        pageNo: pageNum
      })
    }).then(function (res) {
      var _res$data;
      if (!(res === null || res === void 0 ? void 0 : (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.data)) throw new Error();
      setStore((res === null || res === void 0 ? void 0 : res.data.data) || []);
      setTotal((res === null || res === void 0 ? void 0 : res.data.total) || 0);
      // setCount(res?.data.total ?? 0);
    }).catch(function (err) {
      console.error('查询任务列表失败', err);
      setFail(true);
    }).finally(function () {
      setLoading(false);
    });
  }
  var columns = [{
    title: '任务名称',
    dataIndex: 'jobName',
    render: function render(text, record) {
      // 根据实际数据结构判断事件是否被删除，这里假设eventName为空表示事件被删除
      // const isEventDeleted = !record.eventIsExit;
      return /*#__PURE__*/React.createElement("div", {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      }, /*#__PURE__*/React.createElement("span", null, text), record.eventIsExit === 0 && /*#__PURE__*/React.createElement(Tooltip, {
        title: "\u4E8B\u4EF6\u88AB\u5220\u9664\uFF0C\u4EFB\u52A1\u5DF2\u505C\u6B62\u8FD0\u884C\uFF0C\u8BF7\u91CD\u65B0\u7F16\u8F91\u6216\u5220\u9664"
      }, /*#__PURE__*/React.createElement(ExclamationCircleOutlined, {
        style: {
          color: '#ff4d4f',
          marginLeft: 8,
          fontSize: 14
        }
      })));
    }
  }, {
    title: '数据集名称',
    dataIndex: 'dsName'
  }, {
    title: '事件名称',
    dataIndex: 'eventName'
  }, {
    title: /*#__PURE__*/React.createElement(BizSelect, {
      labelField: "label",
      keyField: "value",
      defaultValue: {
        value: -1,
        label: '状态'
      },
      className: "select-style-appName",
      onChange: function onChange(e) {
        setStatusValue(e);
        try {
          queryData();
        } catch (error) {
          console.error('Error', error);
        }
      },
      options: [{
        value: -1,
        label: '状态'
      }].concat(statusOptions)
    }),
    dataIndex: 'jobStatus',
    render: function render(v, record) {
      switch (v) {
        case ZModulesCDP.DataSet.jobTypeState.Failed:
          return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
            className: "".concat(classPrefix, "-state fail")
          }), "\u5931\u8D25", /*#__PURE__*/React.createElement(Button, {
            type: "link",
            danger: true,
            onClick: function onClick() {
              return handleRerun(v, record);
            }
          }, "\u91CD\u8DD1"));
        case ZModulesCDP.DataSet.jobTypeState.Success:
          return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
            className: "".concat(classPrefix, "-state Success")
          }), "\u6210\u529F");
        case ZModulesCDP.DataSet.jobTypeState.Updating:
          return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
            className: "".concat(classPrefix, "-state Updating")
          }), "\u66F4\u65B0\u4E2D");
        default:
          return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
            className: "".concat(classPrefix, "-state NotStarted")
          }), "\u672A\u542F\u7528");
      }
    }
  }, {
    title: '创建人',
    dataIndex: 'createName'
  }, {
    title: '创建时间',
    dataIndex: 'createTime',
    render: dateRender,
    sorter: true // 启用排序
  }, {
    title: '最近更新完成时间',
    dataIndex: 'lastUpdateTime',
    render: dateRender,
    sorter: true,
    sortDirections: ['descend', 'ascend']
  }, {
    title: '操作',
    fixed: 'right',
    width: 200,
    render: function render(_v, data) {
      return /*#__PURE__*/React.createElement(React.Fragment, null, data.jobStatus !== 1 && /*#__PURE__*/React.createElement(TaskEnableSwitch, {
        task: data,
        onChange: function onChange(isOnline) {
          setStore(function (store) {
            var res = _.cloneDeep(store);
            res.forEach(function (item, i) {
              if (item.id === data.id) {
                res[i].isOnline = isOnline;
              }
            });
            queryData();
            return res;
          });
        }
      }), /*#__PURE__*/React.createElement("a", {
        className: "".concat(classPrefix, "-edit ").concat(data.isOnline === ZModulesCDP.DataSet.TaskStatus.enable ? 'disable' : ''),
        onClick: function onClick() {
          if (data.isOnline === ZModulesCDP.DataSet.TaskStatus.enable) {
            message.error('禁用状态下才能编辑任务');
            return;
          }
          if (props.onEdit) props.onEdit(data);
        }
      }, "\u8BE6\u60C5"), /*#__PURE__*/React.createElement("a", {
        className: "".concat(classPrefix, "-del ").concat(data.isOnline === 1 ? 'disable' : ''),
        onClick: function onClick() {
          if (data.isOnline === ZModulesCDP.DataSet.TaskStatus.enable) {
            message.error('禁用状态下才能删除任务');
            return;
          }
          onDel(data);
        }
      }, "\u5220\u9664"), /*#__PURE__*/React.createElement("a", {
        className: "".concat(classPrefix, "-log"),
        onClick: function onClick() {
          return onCheckLog(data);
        }
      }, "\u65E5\u5FD7"), /*#__PURE__*/React.createElement("a", {
        className: "".concat(classPrefix, "-log"),
        onClick: function onClick() {
          if (!data.dsName) return;
          if (props.onCheckDesc) props.onCheckDesc(data);
        }
      }, "\u67E5\u770B"));
    }
  }];
  return /*#__PURE__*/React.createElement("div", {
    className: classPrefix
  }, /*#__PURE__*/React.createElement(StatusDrawer, {
    visible: drawerVisible,
    onClose: function onClose() {
      return setDrawerVisible(false);
    },
    dataSource: store,
    currentTask: currentTask
  }), /*#__PURE__*/React.createElement(Form, {
    ref: formRef,
    layout: "inline",
    colon: false,
    onFinish: onSearch,
    onChange: onChangeCondition
  }, /*#__PURE__*/React.createElement(Form.Item, {
    name: "jobName"
  }, /*#__PURE__*/React.createElement(Input, {
    placeholder: "\u6570\u636E\u96C6/\u4EFB\u52A1\u540D\u79F0",
    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", total, "\u6761\u6570\u636E!"), /*#__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.onCreat
  }, "\u521B\u5EFA\u4EFB\u52A1"))), 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,
      onChange: handleTableChange,
      rowKey: "id",
      pagination: {
        pageSize: pageSize,
        total: total,
        current: pageNum,
        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, pageSize) {
          console.log(page, 'page');
          setPageNum(page);
          setPageSize(pageSize);
        }
      },
      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.delTaskDataExt, {
        method: 'get',
        params: {
          taskId: currentTask.taskId
        },
        errorTitle: '删除失败'
      }).then(function (res) {
        if (!res) throw new Error();
        notification.success({
          message: '删除成功'
        });
        callback();
        setShowDel(false);
        queryData();
      }).catch(function (err) {
        console.error('删除任务失败', err);
        callback();
      });
    },
    onCancel: function onCancel() {
      setShowDel(false);
    }
  }) : null);
};
export default DataOutPut;