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

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

import React, { useCallback } from 'react';
import { Page, Header, Breadcrumb, Content, Permission, Action, Choerodon, HeaderButtons } from '@choerodon/boot';
import { observer } from 'mobx-react-lite';
import { useAppTemplateStore } from "./stores";
import TimePopover from "../../components/time-popover";
import TemplateServices from "./services";
import isEmpty from 'lodash/isEmpty';
import AddTemplate from "./components/addTemplate";
import { mapping } from "./stores/TableDataSet";
import "./index.less";
var Column = _Table.Column;
var TemplateTable = observer(function () {
  var _useAppTemplateStore = useAppTemplateStore(),
      formatMessage = _useAppTemplateStore.formatMessage,
      prefixCls = _useAppTemplateStore.prefixCls,
      intlPrefix = _useAppTemplateStore.intlPrefix,
      tableDs = _useAppTemplateStore.tableDs,
      organizationId = _useAppTemplateStore.organizationId,
      permissionCodes = _useAppTemplateStore.permissionCodes,
      pageType = _useAppTemplateStore.pageType;

  var refresh = useCallback(function () {
    tableDs.query();
  }, []);
  /**
   * 创建自定义模板
   */

  var handleCreateAppTemplate = useCallback(function (record) {
    var templateId = record ? record.get('id') : null;

    _Modal.open({
      title: formatMessage({
        id: "".concat(intlPrefix, ".title.").concat(templateId ? 'edit' : 'create')
      }),
      key: _Modal.key(),
      children: /*#__PURE__*/React.createElement(AddTemplate, {
        refresh: refresh,
        templateId: templateId,
        pageType: pageType
      }),
      drawer: true,
      okText: formatMessage({
        id: templateId ? 'save' : 'create'
      }),
      style: {
        width: '3.8rem'
      }
    });
  }, []);
  var openOperationModal = useCallback(function (modalProps) {
    _Modal.open(_objectSpread({
      key: _Modal.key(),
      movable: false
    }, modalProps));
  }, []);
  var openEnabledModal = useCallback(function (_ref) {
    var record = _ref.record;

    if (!record) {
      return;
    }

    var enabled = record.get('enable');

    if (enabled) {
      _Modal.open({
        key: _Modal.key(),
        title: formatMessage({
          id: "".concat(intlPrefix, ".enable.title")
        }, {
          name: record.get('name')
        }),
        children: formatMessage({
          id: "".concat(intlPrefix, ".enable.des")
        }),
        movable: false,
        onOk: function onOk() {
          return handleEnabled(true, record);
        }
      });
    } else {
      handleEnabled(false, record);
    }
  }, []);
  var handleEnabled = useCallback( /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(enabled, record) {
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (record) {
                _context.next = 2;
                break;
              }

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

            case 2:
              _context.prev = 2;
              _context.next = 5;
              return TemplateServices.handleEnabled(record.get('id'), enabled ? 'disable' : 'enable', organizationId);

            case 5:
              if (!_context.sent) {
                _context.next = 8;
                break;
              }

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

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

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

            case 15:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[2, 11]]);
    }));

    return function (_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }(), []);
  var openPermissionModal = useCallback(function (_ref3) {
    var record = _ref3.record;

    if (!record) {
      return;
    }

    openOperationModal({
      title: formatMessage({
        id: "".concat(intlPrefix, ".permission.title")
      }),
      children: formatMessage({
        id: "".concat(intlPrefix, ".permission.des")
      }),
      onOk: function onOk() {
        return handlePermission({
          record: record
        });
      }
    });
  }, []);
  var handlePermission = useCallback( /*#__PURE__*/function () {
    var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(_ref4) {
      var record;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              record = _ref4.record;

              if (record) {
                _context2.next = 3;
                break;
              }

              return _context2.abrupt("return");

            case 3:
              _context2.prev = 3;
              _context2.next = 6;
              return TemplateServices.addTemplatePermission(record.get('id'), organizationId);

            case 6:
              refresh();
              _context2.next = 12;
              break;

            case 9:
              _context2.prev = 9;
              _context2.t0 = _context2["catch"](3);
              Choerodon.handleResponseError(_context2.t0);

            case 12:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[3, 9]]);
    }));

    return function (_x3) {
      return _ref5.apply(this, arguments);
    };
  }(), []);
  var handleDelete = useCallback(function (_ref6) {
    var record = _ref6.record;

    if (!record) {
      return;
    }

    var modalProps = {
      title: formatMessage({
        id: "".concat(intlPrefix, ".delete.title")
      }, {
        name: record.get('name')
      }),
      children: formatMessage({
        id: "".concat(intlPrefix, ".delete.des")
      }),
      okText: formatMessage({
        id: 'delete'
      }),
      okProps: {
        color: 'red'
      },
      cancelProps: {
        color: 'dark'
      }
    };
    tableDs["delete"](record, modalProps);
  }, []);
  var openNoPermissionModal = useCallback(function () {
    openOperationModal({
      title: formatMessage({
        id: "".concat(intlPrefix, ".permission.no.title")
      }),
      children: formatMessage({
        id: "".concat(intlPrefix, ".permission.no.des")
      }),
      okText: formatMessage({
        id: 'iknow'
      }),
      okCancel: false
    });
  }, []);
  var renderName = useCallback(function (_ref7) {
    var value = _ref7.value,
        record = _ref7.record;

    // type 为P：预定义；C: 自定义
    if (record.get('type') === 'P' || record.get('status') !== 'S' || !record.get('enable')) {
      return /*#__PURE__*/React.createElement("span", null, value);
    }

    return /*#__PURE__*/React.createElement(Permission, {
      service: permissionCodes.edit,
      defaultChildren: /*#__PURE__*/React.createElement("span", {
        className: "table-unClick"
      }, value)
    }, /*#__PURE__*/React.createElement("span", {
      role: "none",
      onClick: function onClick() {
        return handleCreateAppTemplate(record);
      },
      className: "table-link"
    }, value));
  }, []);
  var renderDate = useCallback(function (_ref8) {
    var value = _ref8.value;
    return /*#__PURE__*/React.createElement(TimePopover, {
      datetime: value
    });
  }, []);
  var renderUrl = useCallback(function (_ref9) {
    var value = _ref9.value,
        record = _ref9.record;
    var text = value ? "../".concat(value.split('/')[value.split('/').length - 1]) : '';

    if (record && !record.get('permission')) {
      return /*#__PURE__*/React.createElement("span", {
        role: "none",
        onClick: openNoPermissionModal,
        className: "".concat(prefixCls, "-table-url")
      }, text);
    }

    return /*#__PURE__*/React.createElement("a", {
      href: value,
      rel: "nofollow me noopener noreferrer",
      target: "_blank"
    }, text);
  }, []);
  var renderSource = useCallback(function (_ref10) {
    var value = _ref10.value;
    return value === 'C' ? '自定义' : '预定义';
  }, []);
  var renderStatus = useCallback(function (_ref11) {
    var value = _ref11.value,
        record = _ref11.record;
    // eslint-disable-next-line no-nested-ternary
    var status = value === 'S' ? record.get('enable') ? 'enable' : 'disable' : value;
    return /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-table-status ").concat(prefixCls, "-table-status-").concat(status)
    }, formatMessage({
      id: "".concat(intlPrefix, ".status.").concat(status)
    }));
  }, []);
  var renderAction = useCallback(function (_ref12) {
    var record = _ref12.record;
    var enabled = record.get('enable');
    var status = record.get('status');
    var builtIn = record.get('type') === 'P';
    var hasPermission = record.get('permission');
    var deleteData = {
      service: permissionCodes["delete"],
      text: '删除',
      action: function action() {
        return handleDelete({
          record: record
        });
      }
    };
    var actionData = [];

    switch (status) {
      case 'S':
        actionData.push({
          service: permissionCodes[enabled ? 'disable' : 'enable'],
          text: enabled ? '停用' : '启用',
          action: function action() {
            return openEnabledModal({
              record: record
            });
          }
        });

        if (!enabled) {
          actionData.push(deleteData);
        } else if (!hasPermission) {
          actionData.push({
            service: permissionCodes.permission,
            text: '获取GitLab仓库权限',
            action: function action() {
              return openPermissionModal({
                record: record
              });
            }
          });
        }

        break;

      case 'F':
        actionData.push(deleteData);
        break;

      default:
        break;
    }

    return !builtIn && !isEmpty(actionData) && /*#__PURE__*/React.createElement(Action, {
      data: actionData
    });
  }, []);
  return /*#__PURE__*/React.createElement(Page, null, /*#__PURE__*/React.createElement(Header, null, /*#__PURE__*/React.createElement(HeaderButtons, {
    items: [{
      name: formatMessage({
        id: "".concat(intlPrefix, ".title.create")
      }),
      icon: 'playlist_add',
      display: 'true',
      permissions: permissionCodes.create,
      handler: function handler() {
        return handleCreateAppTemplate();
      }
    }, {
      icon: 'refresh',
      display: true,
      handler: refresh
    }],
    showClassName: false
  })), /*#__PURE__*/React.createElement(Breadcrumb, null), /*#__PURE__*/React.createElement(Content, null, /*#__PURE__*/React.createElement(_Table, {
    dataSet: tableDs,
    className: "table-default-color"
  }, /*#__PURE__*/React.createElement(Column, {
    name: mapping.appTemplate.name,
    renderer: renderName
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderAction,
    width: 60
  }), /*#__PURE__*/React.createElement(Column, {
    name: mapping.temCode.name
  }), /*#__PURE__*/React.createElement(Column, {
    name: mapping.repo.name,
    renderer: renderUrl
  }), /*#__PURE__*/React.createElement(Column, {
    name: mapping.source.name,
    renderer: renderSource,
    width: 100
  }), /*#__PURE__*/React.createElement(Column, {
    name: mapping.createTime.name,
    renderer: renderDate,
    width: 100
  }), /*#__PURE__*/React.createElement(Column, {
    name: mapping.status.name,
    renderer: renderStatus,
    width: 80
  }))));
});
export default TemplateTable;