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

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

import React, { useCallback, useEffect, useMemo } from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { observer } from 'mobx-react-lite';
import { axios, Choerodon } from '@choerodon/boot';
import map from 'lodash/map';
import includes from 'lodash/includes';
import Tips from "../../../../components/new-tips";
import { useCreateAppServiceStore } from "./stores";
import "./index.less";
var Option = _Select.Option,
    OptGroup = _Select.OptGroup;
var FILE_TYPE = 'image/png, image/jpeg, image/gif, image/jpg';
var CreateForm = injectIntl(observer(function (props) {
  var _useCreateAppServiceS = useCreateAppServiceStore(),
      modal = _useCreateAppServiceS.modal,
      store = _useCreateAppServiceS.store,
      organizationId = _useCreateAppServiceS.AppState.currentMenuType.organizationId,
      formatMessage = _useCreateAppServiceS.intl.formatMessage,
      intlPrefix = _useCreateAppServiceS.intlPrefix,
      prefixCls = _useCreateAppServiceS.prefixCls,
      refresh = _useCreateAppServiceS.refresh,
      formDs = _useCreateAppServiceS.formDs;

  var record = formDs.current;
  var optionLoading = useMemo(function () {
    return /*#__PURE__*/React.createElement(Option, {
      value: "loading"
    }, /*#__PURE__*/React.createElement("div", {
      className: "c7ncd-select-option-loading",
      onClick: function onClick(e) {
        e.preventDefault();
        e.stopPropagation();
      },
      role: "none"
    }, /*#__PURE__*/React.createElement(_Spin, null)));
  }, []);
  modal.handleOk( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return formDs.submit();

          case 3:
            _context.t0 = _context.sent;

            if (!(_context.t0 !== false)) {
              _context.next = 7;
              break;
            }

            refresh();
            return _context.abrupt("return", true);

          case 7:
            return _context.abrupt("return", false);

          case 10:
            _context.prev = 10;
            _context.t1 = _context["catch"](0);
            Choerodon.handleResponseError(_context.t1);
            return _context.abrupt("return", false);

          case 14:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 10]]);
  })));
  /**
   * 触发上传按钮
   */

  function triggerFileBtn() {
    var ele = document.getElementById('file');
    ele.click();
  }
  /**
   * 选择文件
   * @param e
   */


  function selectFile(_x) {
    return _selectFile.apply(this, arguments);
  }

  function _selectFile() {
    _selectFile = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(e) {
      var formdata, img, data;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              formdata = new FormData();
              img = e.target.files[0];

              if (includes(FILE_TYPE, img.type)) {
                _context2.next = 5;
                break;
              }

              Choerodon.prompt(formatMessage({
                id: "".concat(intlPrefix, ".file.failed")
              }));
              return _context2.abrupt("return");

            case 5:
              formdata.append('file', e.target.files[0]);
              _context2.prev = 6;
              _context2.next = 9;
              return axios.post("/hfle/v1/".concat(organizationId, "/files/multipart?bucketName=devops-service&fileName=").concat(img.name.split('.')[0]), formdata, {
                header: {
                  'Content-Type': 'multipart/form-data'
                }
              });

            case 9:
              data = _context2.sent;

              if (data) {
                record.set('imgUrl', data);
              }

              _context2.next = 16;
              break;

            case 13:
              _context2.prev = 13;
              _context2.t0 = _context2["catch"](6);
              Choerodon.handleResponseError(e);

            case 16:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[6, 13]]);
    }));
    return _selectFile.apply(this, arguments);
  }

  function renderSourceOption(_ref2) {
    var text = _ref2.text;
    return /*#__PURE__*/React.createElement(_Tooltip, {
      title: text,
      placement: "left"
    }, text);
  }

  function getAppServiceOptions() {
    if (store.getAppServiceLoading || !record) {
      return optionLoading;
    }

    return record.get('appServiceSource') === 'normal_service' ? map(store.getAppService[0] && store.getAppService[0].appServiceList, function (_ref3) {
      var id = _ref3.id,
          name = _ref3.name;
      return /*#__PURE__*/React.createElement(Option, {
        value: id,
        key: id
      }, name);
    }) : map(store.getAppService, function (_ref4) {
      var groupId = _ref4.id,
          groupName = _ref4.name,
          appServiceList = _ref4.appServiceList;
      return /*#__PURE__*/React.createElement(OptGroup, {
        label: groupName,
        key: groupId
      }, map(appServiceList, function (_ref5) {
        var id = _ref5.id,
            name = _ref5.name;
        return /*#__PURE__*/React.createElement(Option, {
          value: id,
          key: id
        }, name);
      }));
    });
  }

  var renderTemplateOption = useCallback(function (_ref6) {
    var value = _ref6.value,
        text = _ref6.text,
        optionRecord = _ref6.record;

    if (optionRecord === null || optionRecord === void 0 ? void 0 : optionRecord.get('remark')) {
      return /*#__PURE__*/React.createElement(Tips, {
        title: text,
        helpText: optionRecord === null || optionRecord === void 0 ? void 0 : optionRecord.get('remark')
      });
    }

    return text;
  }, []);
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-create-wrap")
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      backgroundImage: record.get('imgUrl') ? "url('".concat(record.get('imgUrl'), "')") : ''
    },
    className: "".concat(prefixCls, "-create-img"),
    onClick: triggerFileBtn,
    role: "none"
  }, /*#__PURE__*/React.createElement("div", {
    className: "create-img-mask"
  }, /*#__PURE__*/React.createElement(_Icon, {
    type: "photo_camera",
    className: "create-img-icon"
  })), /*#__PURE__*/React.createElement(_Input, {
    id: "file",
    type: "file",
    accept: FILE_TYPE,
    onChange: selectFile,
    style: {
      display: 'none'
    }
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-create-text")
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "".concat(intlPrefix, ".icon")
  })), /*#__PURE__*/React.createElement(_Form, {
    dataSet: formDs
  }, /*#__PURE__*/React.createElement(_Select, {
    name: "type",
    clearButton: false,
    addonAfter: /*#__PURE__*/React.createElement(Tips, {
      helpText: formatMessage({
        id: "".concat(intlPrefix, ".type.tips")
      })
    })
  }, /*#__PURE__*/React.createElement(Option, {
    value: "normal"
  }, formatMessage({
    id: "".concat(intlPrefix, ".type.normal")
  })), /*#__PURE__*/React.createElement(Option, {
    value: "test"
  }, formatMessage({
    id: "".concat(intlPrefix, ".type.test")
  }))), /*#__PURE__*/React.createElement(_TextField, {
    name: "code",
    autoFocus: true,
    addonAfter: /*#__PURE__*/React.createElement(Tips, {
      helpText: formatMessage({
        id: "".concat(intlPrefix, ".code.tips")
      })
    })
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "name",
    colSpan: 3
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-create-wrap-template-title")
  }, /*#__PURE__*/React.createElement(Tips, {
    helpText: formatMessage({
      id: "".concat(intlPrefix, ".template.tips")
    }),
    title: formatMessage({
      id: "".concat(intlPrefix, ".template")
    })
  })), /*#__PURE__*/React.createElement(_Form, {
    dataSet: formDs,
    className: "".concat(prefixCls, "-create-wrap-form")
  }, /*#__PURE__*/React.createElement(_SelectBox, {
    name: "appServiceSource",
    optionRenderer: renderSourceOption
  }), ['normal_service', 'share_service'].includes(formDs.current.get('appServiceSource')) ? [/*#__PURE__*/React.createElement(_Select, {
    name: "templateAppServiceId",
    searchable: true,
    disabled: !record.get('appServiceSource'),
    notFoundContent: /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "".concat(intlPrefix, ".empty")
    })
  }, getAppServiceOptions()), /*#__PURE__*/React.createElement(_Select, {
    name: "templateAppServiceVersionId",
    searchable: true,
    searchMatcher: "version",
    clearButton: false,
    disabled: !record.get('templateAppServiceId')
  })] : /*#__PURE__*/React.createElement(_Select, {
    name: "devopsAppTemplateId",
    searchable: true,
    searchMatcher: "param",
    addonAfter: /*#__PURE__*/React.createElement(Tips, {
      helpText: formatMessage({
        id: 'c7ncd.template.tips'
      })
    }),
    optionRenderer: renderTemplateOption
  })));
}));
export default CreateForm;