import "choerodon-ui/pro/lib/spin/style";
import _Spin from "choerodon-ui/pro/lib/spin";
import "choerodon-ui/pro/lib/tooltip/style";
import _Tooltip from "choerodon-ui/pro/lib/tooltip";
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 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, { useMemo, Fragment } from 'react';
import { Action, Choerodon } from '@choerodon/boot';
import TimePopover from "../../../../../components/time-popover";
import UserInfo from "../../../../../components/userInfo";
import ClickText from "../../../../../components/click-text";
import DeployConfigForm from "./modals/deploy-config";
import { handlePromptError } from "../../../../../utils";
import { useEnvironmentStore } from "./stores";
import { useResourceStore } from "../../../stores";
var Column = _Table.Column;

var deleteModalKey = _Modal.key();

var modifyModalKey = _Modal.key();

export default function DeployConfig() {
  var configModalStyle = useMemo(function () {
    return {
      width: 'calc(100vw - 3.52rem)',
      minWidth: '2rem'
    };
  }, []);

  var _useResourceStore = useResourceStore(),
      prefixCls = _useResourceStore.prefixCls,
      intlPrefix = _useResourceStore.intlPrefix;

  var _useEnvironmentStore = useEnvironmentStore(),
      projectId = _useEnvironmentStore.AppState.currentMenuType.id,
      envStore = _useEnvironmentStore.envStore,
      formatMessage = _useEnvironmentStore.intl.formatMessage,
      configDs = _useEnvironmentStore.configDs,
      configFormDs = _useEnvironmentStore.configFormDs,
      baseInfoDs = _useEnvironmentStore.baseInfoDs;

  var disabled = useMemo(function () {
    var record = baseInfoDs.current;
    var notReady = !record;
    return notReady;
  }, [baseInfoDs.current]);

  function refresh() {
    configDs.query();
  }

  function checkDelete() {
    return _checkDelete.apply(this, arguments);
  }

  function _checkDelete() {
    _checkDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var record, valueId, name, deleteModal, res, modalProps;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              record = configDs.current;
              valueId = record.get('id');
              name = record.get('name');
              deleteModal = _Modal.open({
                movable: false,
                closable: false,
                key: deleteModalKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".config.delete.disable")
                }, {
                  name: name
                }),
                children: /*#__PURE__*/React.createElement(_Spin, null),
                footer: null
              });
              _context.prev = 4;
              _context.next = 7;
              return envStore.checkDelete(projectId, valueId);

            case 7:
              res = _context.sent;

              if (handlePromptError(res)) {
                modalProps = {
                  title: formatMessage({
                    id: "".concat(intlPrefix, ".config.delete.disable")
                  }, {
                    name: name
                  }),
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".config.delete.des")
                  }),
                  okText: formatMessage({
                    id: 'delete'
                  }),
                  onOk: function onOk() {
                    return handleDelete(record);
                  },
                  okProps: {
                    color: 'red'
                  },
                  cancelProps: {
                    color: 'dark'
                  },
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement(Fragment, null, okBtn, cancelBtn);
                  }
                }; // configDs.delete(record, modalProps);

                deleteModal.update(modalProps);
              } else if (!res.failed) {
                deleteModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".config.delete.describe")
                  }),
                  okCancel: false,
                  okText: formatMessage({
                    id: 'iknow'
                  }),
                  footer: function footer(OkBtn) {
                    return /*#__PURE__*/React.createElement(Fragment, null, OkBtn);
                  }
                });
              } else {
                deleteModal.close();
              }

              _context.next = 15;
              break;

            case 11:
              _context.prev = 11;
              _context.t0 = _context["catch"](4);
              Choerodon.handleResponseError(_context.t0);
              deleteModal.close();

            case 15:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[4, 11]]);
    }));
    return _checkDelete.apply(this, arguments);
  }

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

  function _handleDelete() {
    _handleDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(record) {
      var res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;
              _context2.next = 3;
              return envStore.deleteRecord(projectId, record.get('id'));

            case 3:
              res = _context2.sent;

              if (!handlePromptError(res, false)) {
                _context2.next = 8;
                break;
              }

              refresh();
              _context2.next = 9;
              break;

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

            case 9:
              _context2.next = 15;
              break;

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

            case 15:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[0, 11]]);
    }));
    return _handleDelete.apply(this, arguments);
  }

  function openModifyModal(record) {
    var valueId = record.get('id');
    var envRecord = baseInfoDs.current;
    var envId = envRecord.get('id');
    configFormDs.transport.read = {
      url: "/devops/v1/projects/".concat(projectId, "/deploy_value?value_id=").concat(valueId),
      method: 'get'
    };
    configFormDs.query();

    _Modal.open({
      drawer: true,
      key: modifyModalKey,
      style: configModalStyle,
      title: formatMessage({
        id: "".concat(intlPrefix, ".modify.config")
      }),
      children: /*#__PURE__*/React.createElement(DeployConfigForm, {
        isModify: true,
        store: envStore,
        dataSet: configFormDs,
        refresh: refresh,
        envId: envId,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls
      }),
      afterClose: function afterClose() {
        configFormDs.transport.read = null;
        configFormDs.reset();
        envStore.setValue('');
      },
      okText: formatMessage({
        id: 'save'
      })
    });
  }

  function renderName(_ref) {
    var value = _ref.value,
        record = _ref.record;
    return /*#__PURE__*/React.createElement(ClickText, {
      permissionCode: ['choerodon.code.project.deploy.app-deployment.resource.ps.update-deploy-config'],
      clickAble: !disabled,
      value: value,
      onClick: openModifyModal,
      record: record,
      showToolTip: true
    });
  }

  function renderActions() {
    var actionData = [{
      service: ['choerodon.code.project.deploy.app-deployment.resource.ps.delete-config'],
      text: formatMessage({
        id: 'delete'
      }),
      action: checkDelete
    }];
    return /*#__PURE__*/React.createElement(Action, {
      data: actionData
    });
  }

  function renderUser(_ref2) {
    var value = _ref2.value,
        record = _ref2.record;
    var url = record.get('createUserUrl');
    return /*#__PURE__*/React.createElement(UserInfo, {
      name: value || '',
      avatar: url
    });
  }

  function renderDate(_ref3) {
    var value = _ref3.value;
    return value ? /*#__PURE__*/React.createElement(TimePopover, {
      datetime: value
    }) : null;
  }

  function renderDescription(_ref4) {
    var value = _ref4.value;
    return /*#__PURE__*/React.createElement(_Tooltip, {
      title: value
    }, value);
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-tab-table"
  }, /*#__PURE__*/React.createElement(_Table, {
    dataSet: configDs,
    border: false
  }, /*#__PURE__*/React.createElement(Column, {
    name: "name",
    sortable: true,
    renderer: renderName
  }), !disabled && /*#__PURE__*/React.createElement(Column, {
    renderer: renderActions,
    width: 70
  }), /*#__PURE__*/React.createElement(Column, {
    name: "description",
    renderer: renderDescription
  }), /*#__PURE__*/React.createElement(Column, {
    name: "appServiceName",
    sortable: true
  }), /*#__PURE__*/React.createElement(Column, {
    name: "envName",
    sortable: true
  }), /*#__PURE__*/React.createElement(Column, {
    name: "createUserRealName",
    renderer: renderUser
  }), /*#__PURE__*/React.createElement(Column, {
    name: "lastUpdateDate",
    renderer: renderDate,
    sortable: true
  })));
}