import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/lib/tooltip/style";
import _Tooltip from "choerodon-ui/lib/tooltip";
import "choerodon-ui/pro/lib/select-box/style";
import _SelectBox from "choerodon-ui/pro/lib/select-box";
import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/lib/message/style";
import _message from "choerodon-ui/lib/message";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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; }

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 { axios } from '@choerodon/boot';
import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { usePipelineCreateStore } from "./stores";
import Tips from "../../../../components/new-tips";
import StageEditBlock from "./components/stageEditBlock";
import "./pipelineCreate.less";
var Option = _Select.Option;
var PipelineCreate = observer(function () {
  var _getAppServiceData, _editBlockStore$getMa, _getAppServiceData2, _editBlockStore$getMa2, _editBlockStore$getMa3;

  var _usePipelineCreateSto = usePipelineCreateStore(),
      PipelineCreateFormDataSet = _usePipelineCreateSto.PipelineCreateFormDataSet,
      modal = _usePipelineCreateSto.modal,
      editBlockStore = _usePipelineCreateSto.editBlockStore,
      createUseStore = _usePipelineCreateSto.createUseStore,
      _usePipelineCreateSto2 = _usePipelineCreateSto.AppState.currentMenuType,
      id = _usePipelineCreateSto2.id,
      projectId = _usePipelineCreateSto2.projectId,
      refreshTree = _usePipelineCreateSto.refreshTree,
      dataSource = _usePipelineCreateSto.dataSource,
      mainStore = _usePipelineCreateSto.mainStore,
      oldMainData = _usePipelineCreateSto.oldMainData,
      appService = _usePipelineCreateSto.appService,
      isEdit = _usePipelineCreateSto.isEdit;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      expandIf = _useState2[0],
      setExpandIf = _useState2[1];

  useEffect(function () {
    if (dataSource) {
      var name = dataSource.name,
          image = dataSource.image,
          versionName = dataSource.versionName;
      var appServiceId = dataSource.appServiceId; // 如果有appService 说明是复制流水线

      if (appService) {
        appServiceId = appService.id;
        PipelineCreateFormDataSet.getField('appServiceId').props.lookup = [{
          appServiceId: appServiceId,
          appServiceName: appService.name
        }];
      }

      PipelineCreateFormDataSet.loadData([{
        name: name,
        appServiceId: appServiceId,
        image: image,
        selectImage: '1',
        versionName: versionName,
        bbcl: !!versionName,
        versionNameRules: '${C7N_COMMIT_TIME}-${C7N_BRANCH}'
      }]); // editBlockStore.setStepData(stageList, true);
    }

    var init = /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var res;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return createUseStore.axiosGetDefaultImage();

              case 2:
                res = _context.sent;
                createUseStore.setDefaultImage(res);

                if (!dataSource) {
                  PipelineCreateFormDataSet.current.set('image', res);
                }

              case 5:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      return function init() {
        return _ref.apply(this, arguments);
      };
    }();

    init();
  }, [PipelineCreateFormDataSet, createUseStore, dataSource]);

  var handleCreate = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var result, origin, data, res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return PipelineCreateFormDataSet.validate();

            case 2:
              result = _context2.sent;

              if (!result) {
                _context2.next = 35;
                break;
              }

              origin = PipelineCreateFormDataSet.toData()[0];
              data = _objectSpread(_objectSpread(_objectSpread({}, dataSource), origin), {}, {
                image: origin.selectImage === '1' ? origin.image : null,
                devopsCiStageVOS: editBlockStore.getStepData.filter(function (s) {
                  return s.type === 'CI';
                }),
                devopsCdStageVOS: editBlockStore.getStepData.filter(function (s) {
                  return s.type === 'CD';
                })
              });

              if (!data.bbcl) {
                delete data.versionName;
              }

              if (!(data.devopsCiStageVOS.some(function (s) {
                return s.jobList.length === 0;
              }) || data.devopsCdStageVOS.some(function (s) {
                return s.jobList.length === 0;
              }))) {
                _context2.next = 10;
                break;
              }

              _message.error("\u6D41\u6C34\u7EBF\u4E2D\u5B58\u5728\u7A7A\u9636\u6BB5\uFF0C\u65E0\u6CD5".concat(modal.props.title.includes('创建') ? '创建' : '保存'));

              return _context2.abrupt("return", false);

            case 10:
              if (!(dataSource && !oldMainData)) {
                _context2.next = 22;
                break;
              }

              _context2.prev = 11;
              _context2.next = 14;
              return axios.put("/devops/v1/projects/".concat(projectId, "/cicd_pipelines/").concat(dataSource.id), data);

            case 14:
              editBlockStore.loadData(projectId, dataSource.id);
              refreshTree();
              return _context2.abrupt("return", true);

            case 19:
              _context2.prev = 19;
              _context2.t0 = _context2["catch"](11);
              return _context2.abrupt("return", false);

            case 22:
              _context2.prev = 22;
              _context2.next = 25;
              return createUseStore.axiosCreatePipeline(data, id);

            case 25:
              res = _context2.sent;
              refreshTree();
              modal.close();
              res.id && mainStore.setSelectedMenu({
                key: String(res.id)
              });
              return _context2.abrupt("return", true);

            case 32:
              _context2.prev = 32;
              _context2.t1 = _context2["catch"](22);
              return _context2.abrupt("return", false);

            case 35:
              return _context2.abrupt("return", false);

            case 36:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[11, 19], [22, 32]]);
    }));

    return function handleCreate() {
      return _ref2.apply(this, arguments);
    };
  }();

  var handleCancel = function handleCancel() {
    editBlockStore.setMainData(oldMainData);
  };

  modal.handleOk(handleCreate);
  modal.handleCancel(function () {
    if (oldMainData) {
      handleCancel();
    }
  });

  var handleChangeSelectImage = function handleChangeSelectImage(data) {
    if (data === createUseStore.getDefaultImage) {
      PipelineCreateFormDataSet.current.set('selectImage', '0');
    } else {
      PipelineCreateFormDataSet.current.set('selectImage', '1');
    }
  };

  var handleClickMore = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(e) {
      var pageSize, result;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              e.stopPropagation();
              pageSize = PipelineCreateFormDataSet.current.get('pageSize') + 20;
              _context3.next = 4;
              return axios.post("/devops/v1/projects/".concat(projectId, "/app_service/page_app_services_without_ci?page=0&size=").concat(pageSize));

            case 4:
              result = _context3.sent;

              if (result.length % 20 === 0) {
                result.push({
                  appServiceId: 'more',
                  appServiceName: '加载更多'
                });
              }

              PipelineCreateFormDataSet.current.set('pageSize', pageSize);
              PipelineCreateFormDataSet.getField('appServiceId').props.lookup = result;

            case 8:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));

    return function handleClickMore(_x) {
      return _ref3.apply(this, arguments);
    };
  }();

  var renderer = function renderer(_ref4) {
    var text = _ref4.text;

    var _ref5 = createUseStore.getCurrentAppService || {},
        appServiceName = _ref5.appServiceName;

    if (dataSource && dataSource.appServiceName) {
      return dataSource.appServiceName;
    }

    return appServiceName || text;
  };

  var optionRenderer = function optionRenderer(_ref6) {
    var text = _ref6.text;
    return text === '加载更多' ? /*#__PURE__*/React.createElement("a", {
      role: "none",
      style: {
        width: '100%',
        height: '100%',
        display: 'block'
      },
      onClick: handleClickMore
    }, text) : text;
  };

  function getAppServiceData() {
    return createUseStore.getCurrentAppService || {};
  }

  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(_Form, {
    columns: 3,
    dataSet: PipelineCreateFormDataSet
  }, /*#__PURE__*/React.createElement(_TextField, {
    name: "name" // disabled={dataSource}

  }), /*#__PURE__*/React.createElement(_Select, {
    disabled: dataSource,
    name: "appServiceId",
    searchable: true,
    searchMatcher: "appServiceName",
    addonAfter: /*#__PURE__*/React.createElement(Tips, {
      helpText: "\u6B64\u5904\u4EC5\u80FD\u770B\u5230\u60A8\u6709\u5F00\u53D1\u6743\u9650\u7684\u542F\u7528\u72B6\u6001\u7684\u5E94\u7528\u670D\u52A1\uFF0C\u5E76\u8981\u6C42\u8BE5\u5E94\u7528\u670D\u52A1\u5FC5\u987B\u6709master\u5206\u652F\uFF0C\u4E14\u5C1A\u672A\u6709\u5173\u8054\u7684\u6D41\u6C34\u7EBF"
    }),
    optionRenderer: optionRenderer,
    renderer: renderer
  }), /*#__PURE__*/React.createElement(_TextField, {
    style: {
      display: 'none'
    }
  }), /*#__PURE__*/React.createElement("div", {
    role: "none",
    className: "advanced_text",
    style: {
      cursor: 'pointer'
    },
    onClick: function onClick() {
      return setExpandIf(!expandIf);
    }
  }, "\u9AD8\u7EA7\u8BBE\u7F6E", /*#__PURE__*/React.createElement(_Icon, {
    style: {
      fontSize: 18
    },
    type: expandIf ? 'expand_less' : 'expand_more'
  })), expandIf ? [/*#__PURE__*/React.createElement(_Select, {
    combo: true,
    newLine: true,
    colSpan: 2,
    name: "image",
    onChange: handleChangeSelectImage,
    addonAfter: /*#__PURE__*/React.createElement(Tips, {
      helpText: "CI\u6D41\u7A0BRunner\u955C\u50CF\u662F\u8BE5\u6761\u6D41\u6C34\u7EBF\u4E2D\u6240\u6709CI\u4EFB\u52A1\u9ED8\u8BA4\u7684\u6267\u884C\u73AF\u5883\u3002\u60A8\u53EF\u76F4\u63A5\u4F7F\u7528\u6B64\u5904\u7ED9\u51FA\u7684\u9ED8\u8BA4Runner\u955C\u50CF\uFF0C\u6216\u662F\u8F93\u5165\u81EA\u5B9A\u4E49\u7684CI\u6D41\u7A0BRunner\u955C\u50CF"
    })
  }, /*#__PURE__*/React.createElement(Option, {
    value: createUseStore.getDefaultImage
  }, createUseStore.getDefaultImage)), /*#__PURE__*/React.createElement("div", {
    newLine: true,
    colSpan: 2,
    style: {
      position: 'relative',
      top: '15px'
    }
  }, /*#__PURE__*/React.createElement(_SelectBox, {
    name: "bbcl"
  }, /*#__PURE__*/React.createElement(Option, {
    value: false
  }, "\u5E73\u53F0\u9ED8\u8BA4"), /*#__PURE__*/React.createElement(Option, {
    value: true
  }, "\u81EA\u5B9A\u4E49")), /*#__PURE__*/React.createElement(_Tooltip, {
    title: /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("p", {
      style: {
        margin: 0
      }
    }, "\u6B64\u5904\u7248\u672C\u7B56\u7565\u6307\u7684\u662F\u6D41\u6C34\u7EBF\u4E2D\u751F\u6210\u7684\u5E94\u7528\u670D\u52A1\u7248\u672C\u7684\u540D\u79F0\u7B56\u7565;"), /*#__PURE__*/React.createElement("p", {
      style: {
        margin: 0
      }
    }, "\u9009\u62E9\u4E3A\u5E73\u53F0\u9ED8\u8BA4\u540E\uFF0C\u4FBF\u4F1A\u9ED8\u8BA4\u4F7F\u7528\u201C\u65F6\u95F4\u6233+\u5206\u652F\u540D\u201D\u7684\u547D\u540D\u89C4\u5219;"), /*#__PURE__*/React.createElement("p", {
      style: {
        margin: 0
      }
    }, "\u82E5\u9009\u62E9\u4E3A\u81EA\u5B9A\u4E49\uFF0C\u5219\u652F\u6301\u7528\u6237\u8F93\u5165\u4E00\u4E2A\u56FA\u5B9A\u6216\u52A8\u6001\u7684\u53C2\u6570\u4F5C\u4E3A\u7248\u672C\u547D\u540D\u89C4\u5219"))
  }, /*#__PURE__*/React.createElement(_Icon, {
    type: "help",
    className: "c7ncd-select-tips-icon",
    style: {
      position: 'absolute',
      top: '-12px',
      left: '55px'
    }
  }))), PipelineCreateFormDataSet.current.get('bbcl') ? /*#__PURE__*/React.createElement(_TextField, {
    newLine: true,
    colSpan: 2,
    addonAfter: /*#__PURE__*/React.createElement(Tips, {
      helpText: [/*#__PURE__*/React.createElement("p", {
        style: {
          margin: 0
        }
      }, "\u81EA\u5B9A\u4E49\u547D\u540D\u89C4\u5219\u652F\u6301\u8F93\u5165\u56FA\u5B9A\u53C2\u6570\u4F8B\u5982\uFF1A0.1.0\uFF0C\u90A3\u4E48\u4E4B\u540E\u6D41\u6C34\u7EBF\u751F\u6210\u7684\u7248\u672C\u540D\u79F0\uFF0C\u5C06\u6C38\u8FDC\u4E3A\u56FA\u5B9A\u76840.1.0\u3002"), /*#__PURE__*/React.createElement("p", {
        style: {
          margin: 0
        }
      }, "\u540C\u65F6\uFF0C\u652F\u6301\u4F7F\u7528\u52A8\u6001\u53C2\u6570\u53CA\u5404\u79CD\u53D8\u91CF\uFF0C\u4F8B\u5982\uFF1A${CI_PIPELINE_ID}-${C7N_BRANCH} \uFF0C\u5219\u8868\u793A\u547D\u540D\u89C4\u5219\u4E3A\uFF1Agitlab\u6D41\u6C34\u7EBFid+\u5206\u652F\u540D\u3002\n\u66F4\u591A\u652F\u6301\u7684\u53D8\u91CF\uFF0C\u8BF7\u53C2\u8003 ", /*#__PURE__*/React.createElement("a", {
        style: {
          color: 'cornflowerblue'
        },
        target: "_blank",
        href: "https://docs.gitlab.com/ee/ci/variables/predefined_variables.html"
      }, "GitLab\u53D8\u91CF"))]
    }),
    name: "versionName"
  }) : /*#__PURE__*/React.createElement(_TextField, {
    newLine: true,
    colSpan: 2,
    addonAfter: /*#__PURE__*/React.createElement(Tips, {
      helpText: "\u5E73\u53F0\u9ED8\u8BA4\u7684\u7248\u672C\u547D\u540D\u89C4\u5219\u4E3A\uFF1A${C7N_COMMIT_TIME}-${C7N_BRANCH}\uFF0C\u5373\u8868\u793A\u8BE5\u6D41\u6C34\u7EBF\u4E2D\u751F\u6210\u7684\u7248\u672C\u540D\u79F0\u4E3A\"\u65F6\u95F4\u6233+\u5206\u652F\u540D\""
    }),
    name: "versionNameRules"
  })] : ''), /*#__PURE__*/React.createElement(StageEditBlock, {
    editBlockStore: editBlockStore,
    edit: true,
    isEdit: isEdit,
    image: PipelineCreateFormDataSet.current.get('image'),
    appServiceId: PipelineCreateFormDataSet.current.get('appServiceId'),
    appServiceCode: ((_getAppServiceData = getAppServiceData()) === null || _getAppServiceData === void 0 ? void 0 : _getAppServiceData.appServiceCode) || ((_editBlockStore$getMa = editBlockStore.getMainData) === null || _editBlockStore$getMa === void 0 ? void 0 : _editBlockStore$getMa.appServiceCode),
    appServiceName: ((_getAppServiceData2 = getAppServiceData()) === null || _getAppServiceData2 === void 0 ? void 0 : _getAppServiceData2.appServiceName) || ((_editBlockStore$getMa2 = editBlockStore.getMainData) === null || _editBlockStore$getMa2 === void 0 ? void 0 : _editBlockStore$getMa2.appServiceName),
    appServiceType: getAppServiceData().type || ((_editBlockStore$getMa3 = editBlockStore.getMainData) === null || _editBlockStore$getMa3 === void 0 ? void 0 : _editBlockStore$getMa3.appServiceType),
    dataSource: dataSource
  }), /*#__PURE__*/React.createElement("p", {
    className: "pipeline_createInfo"
  }, /*#__PURE__*/React.createElement(_Icon, {
    className: "pipeline_createInfo-icon",
    type: "error"
  }), "\u6B64\u9875\u9762\u5B9A\u4E49\u4E86CI\u9636\u6BB5\u6216\u5176\u4E2D\u7684\u4EFB\u52A1\u540E\uFF0CGitLab\u4ED3\u5E93\u4E2D\u7684.gitlab-ci.yml\u6587\u4EF6\u4E5F\u4F1A\u540C\u6B65\u4FEE\u6539\u3002"));
});
export default PipelineCreate;