import "choerodon-ui/pro/lib/tooltip/style";
import _Tooltip from "choerodon-ui/pro/lib/tooltip";
import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/pro/lib/modal/style";
import _Modal from "choerodon-ui/pro/lib/modal";
import "choerodon-ui/pro/lib/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/TablePro";

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/* eslint-disable jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */
import React, { useCallback, useEffect, useState } from 'react';
import { Page, Content, Header, Permission, Breadcrumb, Choerodon, HeaderButtons, Action } from '@choerodon/boot';
import { FormattedMessage } from 'react-intl';
import { withRouter } from 'react-router-dom';
import classNames from 'classnames';
import { observer } from 'mobx-react-lite';
import app from "../../images/app.svg";
import image from "../../images/image.svg";
import jar from "../../images/jar.svg";
import { StatusTag } from '@choerodon/components';
import { TabCode } from '@choerodon/master';
import { SMALL } from "../../utils/getModalWidth";
import YamlEditor from "../../components/yamlEditor";
import ReactCodeMirror from 'react-codemirror';
import { mapping } from "./stores/ListDataSet";
import { useDeployStore } from "./stores";
import TimePopover from "../../components/timePopover/TimePopover";
import UserInfo from "../../components/userInfo";
import Deploy from "./modals/deploy";
import BaseComDeploy from "./modals/base-comDeploy";
import BatchDeploy from "./modals/batch-deploy";
import Tips from "../../components/new-tips";
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/base16-dark.css';
import "./index.less";
var Column = _Table.Column;

var modalKey4 = _Modal.key();

var batchDeployModalKey = _Modal.key();

var commandModalKey = _Modal.key();

var modalStyle2 = {
  width: 'calc(100vw - 3.52rem)'
};
var statusTagsStyle = {
  marginRight: 8
};
var logOptions = {
  theme: 'base16-dark',
  mode: 'shell',
  readOnly: true,
  lineNumbers: false,
  lineWrapping: true
}; // eslint-disable-next-line no-undef

var HAS_BASE_PRO = false;

try {
  require.resolveWeak('@choerodon/base-pro');

  HAS_BASE_PRO = true;
} catch (error) {}

var Deployment = withRouter(observer(function (props) {
  var _useDeployStore = useDeployStore(),
      formatMessage = _useDeployStore.intl.formatMessage,
      _useDeployStore$AppSt = _useDeployStore.AppState.currentMenuType,
      id = _useDeployStore$AppSt.id,
      projectId = _useDeployStore$AppSt.projectId,
      intlPrefix = _useDeployStore.intlPrefix,
      prefixCls = _useDeployStore.prefixCls,
      listDs = _useDeployStore.listDs,
      deployStore = _useDeployStore.deployStore,
      envOptionsDs = _useDeployStore.envOptionsDs,
      pipelineOptionsDs = _useDeployStore.pipelineOptionsDs;

  useEffect(function () {
    var search = props.location.search;
    var urlQuery = new URLSearchParams(search);

    if (urlQuery.get('mode') || urlQuery.get('deployType')) {
      openBaseDeploy(urlQuery.get('mode'), urlQuery.get('deployType'));
      urlQuery["delete"]('mode');
      window.history.replaceState(null, null, "/#/devops/deployment-operation?".concat(urlQuery.toString()));
    }
  }, []);

  function refresh() {
    envOptionsDs.query();
    pipelineOptionsDs.query();
    listDs.query();
  }

  function openDeploy() {
    _Modal.open({
      key: modalKey4,
      style: modalStyle2,
      drawer: true,
      title: formatMessage({
        id: "".concat(intlPrefix, ".manual")
      }),
      children: /*#__PURE__*/React.createElement(Deploy, {
        deployStore: deployStore,
        refresh: deployAfter,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls,
        hasHostDeploy: true,
        random: Math.random()
      }),
      afterClose: function afterClose() {
        deployStore.setCertificates([]);
        deployStore.setAppService([]);
        deployStore.setConfigValue('');
      },
      okText: formatMessage({
        id: 'deployment'
      })
    });
  }

  function openBaseDeploy(deployWay, middleware) {
    _Modal.open({
      key: _Modal.key(),
      style: modalStyle2,
      drawer: true,
      title: '基础组件部署',
      children: /*#__PURE__*/React.createElement(BaseComDeploy, Object.assign({
        random: Math.random()
      }, deployWay ? {
        deployWay: deployWay
      } : {}, middleware ? {
        middleware: middleware
      } : {}, {
        refresh: refresh
      })),
      okText: '部署'
    });
  }

  function openBatchDeploy() {
    _Modal.open({
      key: batchDeployModalKey,
      style: modalStyle2,
      drawer: true,
      title: formatMessage({
        id: "".concat(intlPrefix, ".batch")
      }),
      children: /*#__PURE__*/React.createElement(BatchDeploy, {
        deployStore: deployStore,
        refresh: deployAfter,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls
      }),
      afterClose: function afterClose() {
        deployStore.setCertificates([]);
        deployStore.setAppService([]);
        deployStore.setShareAppService([]);
        deployStore.setConfigValue('');
      },
      okText: formatMessage({
        id: 'deployment'
      })
    });
  }

  function linkToInstance(record) {
    var history = props.history,
        search = props.location.search;

    if (record) {
      var instanceId = record.get('instanceId');
      var appServiceId = record.get('appServiceId');
      var envId = record.get('envId');
      history.push({
        pathname: '/devops/resource',
        search: "".concat(search, "&activeKey=").concat(TabCode.get('/devops/resource').tabCodes[0]),
        state: {
          instanceId: instanceId,
          appServiceId: appServiceId,
          envId: envId
        }
      });
    }

    history.push("/devops/resource".concat(search));
  }

  function deployAfter(instance) {
    var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'instance';
    var history = props.history,
        search = props.location.search;

    if (instance.config) {
      history.push("/devops/deployment-operation".concat(search));
    } else {
      history.push({
        pathname: '/devops/resource',
        search: "".concat(search, "&activeKey=").concat(TabCode.get('/devops/resource').tabCodes[0]),
        state: {
          instanceId: instance.id,
          appServiceId: instance.appServiceId,
          envId: instance.envId,
          viewType: type
        }
      });
    }
  }

  function renderNumber(_ref) {
    var _classNames;

    var record = _ref.record;
    var errorInfo = record.get('errorInfo');
    var deployStatus = record.get('deployStatus');
    var type = record.get('deployType');
    var viewId = record.get('viewId');
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
      className: classNames((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-content-table-mark ").concat(prefixCls, "-content-table-mark-").concat(type), true), _defineProperty(_classNames, 'c7ncd-number-base', type === 'baseComponent'), _classNames))
    }, formatMessage({
      id: "".concat(intlPrefix, ".type.").concat(type)
    })), /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-content-table-number")
    }, "#", viewId), errorInfo && deployStatus === 'failed' && /*#__PURE__*/React.createElement(_Tooltip, {
      title: errorInfo
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: "error",
      className: "".concat(prefixCls, "-content-icon-failed")
    })));
  }

  function renderDeployStatus(_ref2) {
    var value = _ref2.value,
        record = _ref2.record;
    var errMsg = record.get('errorMessage');
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(StatusTag, {
      colorCode: value || '',
      name: value ? formatMessage({
        id: "".concat(intlPrefix, ".status.").concat(value)
      }) : 'unKnow',
      style: statusTagsStyle
    }), errMsg && /*#__PURE__*/React.createElement(_Tooltip, {
      title: errMsg
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: "info",
      style: {
        color: 'rgb(247, 103, 118)'
      }
    })));
  }

  function renderExecutor(_ref3) {
    var value = _ref3.value,
        record = _ref3.record;

    var _ref4 = value || {},
        realName = _ref4.realName,
        loginName = _ref4.loginName,
        ldap = _ref4.ldap,
        imageUrl = _ref4.imageUrl,
        email = _ref4.email;

    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UserInfo, {
      name: realName || '',
      id: ldap ? loginName : email,
      avatar: imageUrl,
      className: "".concat(prefixCls, "-content-table-user")
    }), /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-content-table-time")
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-content-table-time-text")
    }, "\u6267\u884C\u4E8E"), /*#__PURE__*/React.createElement(TimePopover, {
      content: record.get('deployTime')
    })));
  }

  function renderInstance(_ref5) {
    var value = _ref5.value,
        record = _ref5.record;

    if (record.get('deployMode') === 'host') {
      return '';
    }

    if (record.get('deployMode') === 'env' && !value) {
      return '';
    }

    return /*#__PURE__*/React.createElement(_Tooltip, {
      title: value || ''
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-content-table-instance"),
      onClick: function onClick() {
        return linkToInstance(record);
      }
    }, value || ''));
  }

  function getBackPath() {
    var state = props.location.state;

    var _ref6 = state || {},
        backPath = _ref6.backPath;

    return backPath || '';
  }
  /**
   * 部署方式和载体的渲染
   * @param value
   * @param record
   */


  var renderDeployMethod = function renderDeployMethod(_ref7) {
    var value = _ref7.value,
        record = _ref7.record;
    var deployMode = record.get('deployMode');
    var deployPayloadName = record.get('deployPayloadName');
    return /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement(StatusTag, {
      color: deployMode === 'host' ? 'rgb(142, 187, 252)' : 'rgb(116, 217, 221)',
      name: deployMode === 'host' ? '主机' : '环境',
      style: statusTagsStyle
    }), deployPayloadName);
  };
  /**
   * 部署对象渲染
   */


  var renderDeployObejct = function renderDeployObejct(_ref8) {
    var _iconMap$deployObject, _iconMap$deployObject2;

    var value = _ref8.value,
        record = _ref8.record;
    var deployObjectType = record.get('deployObjectType');
    var deployObjectName = record.get('deployObjectName');
    var deployObjectVersion = record.get('deployObjectVersion');
    var iconMap = {
      app: {
        img: app,
        text: '应用服务'
      },
      jar: {
        img: jar,
        text: 'jar包'
      },
      image: {
        img: image,
        text: 'Docker镜像'
      }
    };
    return [/*#__PURE__*/React.createElement("p", {
      className: "c7ncd-deploy-content-deployObjectP"
    }, /*#__PURE__*/React.createElement(_Tooltip, {
      title: (_iconMap$deployObject = iconMap[deployObjectType]) === null || _iconMap$deployObject === void 0 ? void 0 : _iconMap$deployObject.text
    }, /*#__PURE__*/React.createElement("img", {
      src: (_iconMap$deployObject2 = iconMap[deployObjectType]) === null || _iconMap$deployObject2 === void 0 ? void 0 : _iconMap$deployObject2.img,
      alt: ""
    })), /*#__PURE__*/React.createElement("span", {
      className: "c7ncd-deploy-content-deployObjectName"
    }, deployObjectName)), /*#__PURE__*/React.createElement("p", {
      className: "c7ncd-deploy-content-deployObjectP"
    }, /*#__PURE__*/React.createElement(_Tooltip, {
      title: deployObjectVersion
    }, /*#__PURE__*/React.createElement("span", {
      className: "c7ncd-deploy-content-deployObjectVersion"
    }, "\u7248\u672C:", ' ', deployObjectVersion)))];
  };

  var renderDeploySource = useCallback(function (_ref9) {
    var value = _ref9.value,
        record = _ref9.record;

    var _ref10 = value || {},
        type = _ref10.type,
        marketAppName = _ref10.marketAppName,
        marketServiceName = _ref10.marketServiceName,
        projectName = _ref10.projectName;

    if (!type) {
      return null;
    }

    var hasMarketInfo = type === 'market' && marketServiceName;
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-content-source-wrap")
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-content-source")
    }, formatMessage({
      id: "".concat(intlPrefix, ".source.deploy.").concat(type)
    })), type === 'share' && /*#__PURE__*/React.createElement(_Tooltip, {
      title: projectName,
      placement: "top"
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-content-source-text")
    }, projectName)), hasMarketInfo && /*#__PURE__*/React.createElement(_Tooltip, {
      title: marketAppName,
      placement: "top"
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-content-source-text")
    }, marketAppName))), hasMarketInfo && /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-content-source-market")
    }, /*#__PURE__*/React.createElement("span", null, formatMessage({
      id: "".concat(intlPrefix, ".marketService")
    }), ":\xA0"), /*#__PURE__*/React.createElement(_Tooltip, {
      title: marketServiceName
    }, /*#__PURE__*/React.createElement("span", null, marketServiceName))));
  }, []);
  var openCommandModal = useCallback(function (log) {
    _Modal.open({
      key: commandModalKey,
      title: '查看指令',
      style: {
        width: SMALL
      },
      children: /*#__PURE__*/React.createElement(ReactCodeMirror, {
        value: log || '',
        options: logOptions,
        className: "".concat(prefixCls, "-content-command")
      }),
      okText: formatMessage({
        id: 'close'
      }),
      okCancel: false,
      drawer: true
    });
  }, []);
  var renderAction = useCallback(function (_ref11) {
    var record = _ref11.record;

    if (record.get('log')) {
      return /*#__PURE__*/React.createElement(Action, {
        data: [{
          text: '查看指令',
          action: function action() {
            return openCommandModal(record.get('log'));
          }
        }]
      });
    }

    return null;
  }, []);
  return /*#__PURE__*/React.createElement(Page, {
    service: ['choerodon.code.project.deploy.app-deployment.deployment-operation.ps.default']
  }, /*#__PURE__*/React.createElement(Header, {
    title: /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "app.head"
    }),
    backPath: getBackPath()
  }, /*#__PURE__*/React.createElement(HeaderButtons, {
    items: [{
      name: formatMessage({
        id: "".concat(intlPrefix, ".manual")
      }),
      icon: 'cloud_done-o',
      display: true,
      permissions: ['choerodon.code.project.deploy.app-deployment.deployment-operation.ps.manual'],
      handler: openDeploy
    }, {
      name: formatMessage({
        id: "".concat(intlPrefix, ".batch")
      }),
      icon: 'cloud_done-o',
      display: true,
      permissions: ['choerodon.code.project.deploy.app-deployment.deployment-operation.ps.batch'],
      handler: openBatchDeploy
    }, {
      name: '基础组件部署',
      icon: 'cloud_done-o',
      display: HAS_BASE_PRO,
      permissions: ['choerodon.code.project.deploy.app-deployment.deployment-operation.ps.basedComponent'],
      handler: function handler() {
        return openBaseDeploy();
      }
    }, {
      icon: 'refresh',
      display: true,
      handler: refresh
    }],
    showClassName: false
  })), /*#__PURE__*/React.createElement(Breadcrumb, null), /*#__PURE__*/React.createElement(Content, {
    className: "".concat(prefixCls, "-content")
  }, /*#__PURE__*/React.createElement(_Table, {
    dataSet: listDs,
    className: "".concat(prefixCls, "-content-table"),
    rowHeight: "auto"
  }, /*#__PURE__*/React.createElement(Column, {
    name: "deployId",
    renderer: renderNumber,
    align: "left",
    header: /*#__PURE__*/React.createElement(Tips, {
      helpText: formatMessage({
        id: "".concat(intlPrefix, ".id.tips")
      }),
      title: formatMessage({
        id: "".concat(intlPrefix, ".number")
      })
    }),
    width: 150
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderAction,
    width: 60
  }), /*#__PURE__*/React.createElement(Column, {
    header: /*#__PURE__*/React.createElement(Tips, {
      helpText: "\u90E8\u7F72\u65B9\u5F0F\u5206\u4E3A\uFF1A\u4E3B\u673A\u90E8\u7F72\u4E0E\u73AF\u5883\u90E8\u7F72",
      title: "\u90E8\u7F72\u65B9\u5F0F&\u8F7D\u4F53"
    }),
    name: mapping.deployMethod.value,
    renderer: renderDeployMethod
  }), /*#__PURE__*/React.createElement(Column, {
    name: "deployResult",
    renderer: renderDeployStatus,
    header: "\u6267\u884C\u7ED3\u679C",
    width: 90
  }), /*#__PURE__*/React.createElement(Column, {
    name: "instanceName",
    renderer: renderInstance
  }), /*#__PURE__*/React.createElement(Column, {
    name: "deploySourceVO",
    renderer: renderDeploySource
  }), /*#__PURE__*/React.createElement(Column, {
    name: mapping.deployObject.value,
    renderer: renderDeployObejct,
    header: /*#__PURE__*/React.createElement(Tips, {
      helpText: "\u90E8\u7F72\u5BF9\u8C61\u5206\u4E3A\uFF1A\u5E94\u7528\u670D\u52A1\u3001jar\u5305\u4E0EDocker\u955C\u50CF",
      title: "\u90E8\u7F72\u5BF9\u8C61"
    })
  }), /*#__PURE__*/React.createElement(Column, {
    name: "executeUser",
    renderer: renderExecutor
  }))));
}));
export default Deployment;