import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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 = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import forEach from 'lodash/forEach';
import { Terminal } from 'xterm';
import { fit } from 'xterm/lib/addons/fit/fit';
import { observer } from 'mobx-react-lite';
import { axios, Choerodon } from '@choerodon/boot';
import { saveAs } from 'file-saver';
import 'xterm/dist/xterm.css';
import "./index.less";
export default observer(function (props) {
  var gitlabJobId = props.gitlabJobId,
      projectId = props.projectId,
      gitlabProjectId = props.gitlabProjectId,
      type = props.type,
      cdRecordId = props.cdRecordId,
      stageRecordId = props.stageRecordId,
      jobRecordId = props.jobRecordId,
      viewId = props.viewId;
  var prefixCls = useMemo(function () {
    return 'c7n-pipelineManage-codeLog';
  }, []);

  var _useState = useState(),
      _useState2 = _slicedToArray(_useState, 2),
      logData = _useState2[0],
      setLogData = _useState2[1];

  var term = new Terminal({
    fontSize: 13,
    fontWeight: 400,
    fontFamily: 'monospace',
    disableStdin: true
  });

  function loadData() {
    return _loadData.apply(this, arguments);
  }

  function _loadData() {
    _loadData = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var res, newRes, _res, _newRes;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;

              if (!['cdHost', 'cdDeploy', 'cdExternalApproval'].includes(type)) {
                _context.next = 8;
                break;
              }

              _context.next = 4;
              return axios.get("/devops/v1/projects/".concat(projectId, "/pipeline_records/").concat(cdRecordId, "/stage_records/").concat(stageRecordId, "/job_records/log/").concat(jobRecordId));

            case 4:
              res = _context.sent;

              if (res && !res.failed) {
                newRes = res.split(/\n/);
                forEach(newRes, function (item) {
                  return term.writeln(item);
                });
                setLogData(res);
              } else {
                term.writeln('暂无日志');
              }

              _context.next = 12;
              break;

            case 8:
              _context.next = 10;
              return axios.get("/devops/v1/projects/".concat(projectId, "/ci_jobs/gitlab_projects/").concat(gitlabProjectId, "/gitlab_jobs/").concat(gitlabJobId, "/trace"));

            case 10:
              _res = _context.sent;

              if (_res && !_res.failed) {
                _newRes = _res.split(/\n/);
                forEach(_newRes, function (item) {
                  return term.writeln(item);
                });
                setLogData(_res);
              } else {
                term.writeln('暂无日志');
              }

            case 12:
              _context.next = 17;
              break;

            case 14:
              _context.prev = 14;
              _context.t0 = _context["catch"](0);
              Choerodon.handleResponseError(_context.t0);

            case 17:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 14]]);
    }));
    return _loadData.apply(this, arguments);
  }

  useEffect(function () {
    loadData();
    term.open(document.getElementById('jobLog'));
    fit(term);
  }, []);
  var handleDownload = useCallback(function () {
    var blob = new Blob([logData], {
      type: 'text/plain'
    });
    var filename = "#".concat(viewId, "-\u6784\u5EFA\u65E5\u5FD7.log");
    saveAs(blob, filename);
  }, [logData]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, type === 'build' && /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-btn")
  }, /*#__PURE__*/React.createElement(_Button, {
    icon: "refresh",
    onClick: function onClick() {
      var joblog = document.getElementById('jobLog');
      joblog.parentNode.removeChild(joblog);
      var parent = document.querySelector('.c7n-pro-modal-body');
      var child = document.createElement('div');
      child.setAttribute('id', 'jobLog');
      child.setAttribute('class', "".concat(prefixCls, " ").concat(type === 'build' ? "".concat(prefixCls, "-hasBtn") : ''));
      parent.appendChild(child);
      term.clear();
      loadData();
      term.open(document.getElementById('jobLog'));
      fit(term); // term.open(document.getElementById('jobLog'));
      // term.writeln('空');
      // loadData();
    }
  }), /*#__PURE__*/React.createElement(_Button, {
    icon: "get_app-o",
    color: "primary",
    onClick: handleDownload,
    className: "".concat(prefixCls, "-download")
  }, "\u4E0B\u8F7D\u6784\u5EFA\u65E5\u5FD7")), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, " ").concat(type === 'build' ? "".concat(prefixCls, "-hasBtn") : ''),
    id: "jobLog"
  }));
});