import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/pro/lib/modal/style";
import _Modal from "choerodon-ui/pro/lib/modal";

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, { Fragment, useMemo, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { injectIntl } from 'react-intl';
import { Action, axios } from '@choerodon/boot';
import { useResourceStore } from "../../../stores";
import { useMainStore } from "../../stores";
import CustomForm from "../../contents/custom/modals/form-view";
import eventStopProp from "../../../../../utils/eventStopProp";
import openWarnModal from "../../../../../utils/openWarnModal";
import { useTreeItemStore } from "./stores";

var modalKey = _Modal.key();

var modalStyle = {
  width: 'calc(100vw - 3.52rem)'
};

function CustomItem(_ref) {
  var record = _ref.record,
      name = _ref.name,
      intlPrefix = _ref.intlPrefix,
      formatMessage = _ref.intl.formatMessage;

  var _useResourceStore = useResourceStore(),
      treeDs = _useResourceStore.treeDs,
      _useResourceStore$res = _useResourceStore.resourceStore,
      _useResourceStore$res2 = _useResourceStore$res.getSelectedMenu,
      itemType = _useResourceStore$res2.itemType,
      parentId = _useResourceStore$res2.parentId,
      setUpTarget = _useResourceStore$res.setUpTarget,
      checkExist = _useResourceStore$res.checkExist,
      _useResourceStore$ite = _useResourceStore.itemTypes,
      CUSTOM_GROUP = _useResourceStore$ite.CUSTOM_GROUP,
      CUSTOM_ITEM = _useResourceStore$ite.CUSTOM_ITEM,
      projectId = _useResourceStore.AppState.currentMenuType.projectId;

  var _useMainStore = useMainStore(),
      customStore = _useMainStore.customStore;

  var _useTreeItemStore = useTreeItemStore(),
      treeItemStore = _useTreeItemStore.treeItemStore;

  function freshTree() {
    treeDs.query();
  }

  function freshMenu() {
    freshTree();

    var _record$get$split = record.get('parentId').split('**'),
        _record$get$split2 = _slicedToArray(_record$get$split, 1),
        envId = _record$get$split2[0];

    if (itemType === CUSTOM_GROUP && envId === parentId) {
      setUpTarget({
        type: CUSTOM_GROUP,
        id: parentId
      });
    } else {
      setUpTarget({
        type: CUSTOM_ITEM,
        id: record.get('id')
      });
    }
  }

  function getEnvIsNotRunning() {
    var _record$get$split3 = record.get('parentId').split('**'),
        _record$get$split4 = _slicedToArray(_record$get$split3, 1),
        envId = _record$get$split4[0];

    var envRecord = treeDs.find(function (item) {
      return item.get('key') === envId;
    });
    var connect = envRecord.get('connect');
    return !connect;
  }

  function deleteItem() {
    _Modal.open({
      key: _Modal.key(),
      title: formatMessage({
        id: "".concat(intlPrefix, ".custom.delete.title")
      }, {
        name: record.get('name')
      }),
      children: formatMessage({
        id: "".concat(intlPrefix, ".custom.delete.des")
      }),
      okText: formatMessage({
        id: 'delete'
      }),
      okProps: {
        color: 'red'
      },
      cancelProps: {
        color: 'dark'
      },
      onOk: handleDelete
    });
  }

  function handleDelete() {
    return _handleDelete.apply(this, arguments);
  }

  function _handleDelete() {
    _handleDelete = _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 treeItemStore.deleteCustom(projectId, record.get('id'));

            case 3:
              freshTree();
              return _context.abrupt("return", true);

            case 7:
              _context.prev = 7;
              _context.t0 = _context["catch"](0);
              return _context.abrupt("return", false);

            case 10:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 7]]);
    }));
    return _handleDelete.apply(this, arguments);
  }

  function checkDataExist() {
    return checkExist({
      projectId: projectId,
      type: 'custom',
      envId: record.get('parentId').split('**')[0],
      id: record.get('id')
    }).then(function (isExist) {
      if (!isExist) {
        openWarnModal(freshTree, formatMessage);
      }

      return isExist;
    });
  }

  function openModal() {
    checkDataExist().then(function (query) {
      if (query) {
        _Modal.open({
          key: modalKey,
          style: modalStyle,
          drawer: true,
          title: formatMessage({
            id: 'resource.edit.header'
          }),
          children: /*#__PURE__*/React.createElement(CustomForm, {
            id: record.get('id'),
            envId: record.get('parentId').split('**')[0],
            type: "edit",
            store: customStore,
            refresh: freshMenu
          }),
          okText: formatMessage({
            id: 'save'
          })
        });
      }
    });
  }

  function getSuffix() {
    var status = record.get('status');
    var disabled = getEnvIsNotRunning() || status === 'operating';

    if (disabled) {
      return null;
    }

    var actionData = [{
      service: ['choerodon.code.project.deploy.app-deployment.resource.ps.custome-resource.update'],
      text: formatMessage({
        id: 'edit'
      }),
      action: openModal
    }, {
      service: ['choerodon.code.project.deploy.app-deployment.resource.ps.custom-resource.delete'],
      text: formatMessage({
        id: 'delete'
      }),
      action: deleteItem
    }];
    return /*#__PURE__*/React.createElement(Action, {
      placement: "bottomRight",
      data: actionData,
      onClick: eventStopProp
    });
  }

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Icon, {
    type: "filter_b_and_w"
  }), name, getSuffix());
}

CustomItem.defaultProps = {
  name: ''
};
export default injectIntl(observer(CustomItem));