"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _dataGrid = _interopRequireWildcard(require("devextreme-react/data-grid"));
var _axiosClient = _interopRequireDefault(require("../axiosClient"));
var _tagBox = _interopRequireDefault(require("devextreme-react/tag-box"));
var _form = require("devextreme-react/form");
var _custom_store = _interopRequireDefault(require("devextreme/data/custom_store"));
var _successAndErrorMsg = require("../successAndErrorMsg/successAndErrorMsg");
var _tableUtilities = _interopRequireDefault(require("../tableUtilities"));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
var SignPermission = function SignPermission() {
  var allowedPageSizes = [5, 10, 100];
  var exportFormats = ['excel', 'pdf'];
  var _useState = (0, _react.useState)(null),
    _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
    roleNameData = _useState2[0],
    setRoleNameData = _useState2[1];
  var _useState3 = (0, _react.useState)(null),
    _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
    selectedRowKeys = _useState4[0],
    setSelectedRowKeys = _useState4[1];
  var _useState5 = (0, _react.useState)(false),
    _useState6 = (0, _slicedToArray2["default"])(_useState5, 2),
    loadingRole = _useState6[0],
    setLoadingRole = _useState6[1];
  var _useState7 = (0, _react.useState)(null),
    _useState8 = (0, _slicedToArray2["default"])(_useState7, 2),
    roleError = _useState8[0],
    setRoleError = _useState8[1];
  var _useState9 = (0, _react.useState)(null),
    _useState10 = (0, _slicedToArray2["default"])(_useState9, 2),
    roleData = _useState10[0],
    setRoleData = _useState10[1];
  var _useState11 = (0, _react.useState)(null),
    _useState12 = (0, _slicedToArray2["default"])(_useState11, 2),
    signData = _useState12[0],
    setSignData = _useState12[1];
  function handleErrors(response) {
    if (response.status !== 200) throw Error(response.statusText);
    return response;
  }
  var gridDataSource = {
    store: new _custom_store["default"]({
      key: 'id',
      load: function load(loadOptions) {
        var _loadOptions$take;
        var pageSize = (_loadOptions$take = loadOptions.take) !== null && _loadOptions$take !== void 0 ? _loadOptions$take : 10;
        var pageIndex = 1;
        if (loadOptions.take && loadOptions.skip) pageIndex = Math.floor(loadOptions.skip / loadOptions.take) + 1;
        return (0, _axiosClient["default"])().request({
          url: "/sign-permissions?populate=*&pagination[page]=".concat(pageIndex, "&pagination[pageSize]=").concat(pageSize).concat((0, _tableUtilities["default"])({
            loadOptions: loadOptions,
            ignoreDeleted: true
          })),
          method: 'get'
        }).then(handleErrors).then(function (response) {
          return response;
        }).then(function (result) {
          // console.log(result);
          setSignData();
          return {
            data: result.data.data,
            totalCount: result.data.meta.pagination.total
          };
        });
      },
      insert: function insert(values) {
        if (values.attributes.users_permissions_roles) {
          var roleid = values.attributes.users_permissions_roles.data.id;
          delete values.attributes.users_permissions_roles;
          values.attributes.users_permissions_roles = roleid;
        }
        return (0, _axiosClient["default"])().request({
          url: '/sign-permissions',
          method: 'post',
          data: {
            data: values.attributes
          }
        }).then(handleErrors).then(function () {
          (0, _successAndErrorMsg.successMsg)();
        })["catch"](function (err) {
          console.log(err.message);
          (0, _successAndErrorMsg.errorMsg)();
        });
      },
      remove: function remove(key) {
        return (0, _axiosClient["default"])().request({
          url: "/sign-permissions/".concat(key),
          method: 'put',
          data: {
            data: {
              deleted: true
            }
          }
        }).then(handleErrors).then(function () {
          (0, _successAndErrorMsg.successMsg)();
        })["catch"](function (err) {
          console.log(err.message);
          (0, _successAndErrorMsg.errorMsg)();
        });
      },
      update: function update(key, values) {
        if (values.attributes.users_permissions_roles) {
          var roleid = values.attributes.users_permissions_roles.data.id;
          delete values.attributes.users_permissions_roles;
          values.attributes.users_permissions_roles = roleid;
        }
        return (0, _axiosClient["default"])().request({
          url: "/sign-permissions/".concat(key),
          method: 'put',
          data: {
            data: values.attributes
          }
        }).then(handleErrors).then(function (response) {
          (0, _successAndErrorMsg.successMsg)();
        })["catch"](function (err) {
          console.log(err.message);
          (0, _successAndErrorMsg.errorMsg)();
        });
      }
    })
  };
  var nameValidation = function nameValidation(data) {
    return new Promise(function (resolve, reject) {
      var columnName = data.column.dataField.replace('attributes.', '');
      return (0, _axiosClient["default"])().request({
        url: "/sign-permissions?filters[".concat(columnName, "][$eq]=").concat(data.value),
        method: 'get'
      }).then(function (response) {
        if (response.data.meta.pagination.total > 0) if (response.data.data[0].attributes.name === data.value) if (response.data.data[0].id !== data.data.id) reject('Name should be unique');
      })["catch"](function (err) {
        reject('Name should be unique');
      })["finally"](function () {
        resolve('SUCCESS');
      });
    });
  };
  (0, _react.useEffect)(function () {
    if (!roleData) {
      setLoadingRole(true);
      (0, _axiosClient["default"])().request({
        url: '/users-permissions/roles',
        method: 'get'
      }).then(function (response) {
        setRoleData(response.data.roles);
        setRoleError(null);
      })["catch"](function (err) {
        setRoleError(err.message);
        setRoleData(null);
      })["finally"](function () {
        setLoadingRole(false);
      });
    }
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  []);
  var RoleTagBox = function RoleTagBox() {
    return /*#__PURE__*/_react["default"].createElement(_tagBox["default"], {
      items: roleData,
      showSelectionControls: true,
      maxDisplayedTags: 5,
      displayExpr: "name",
      valueExpr: "id",
      selectAllMode: "allPages"
    });
  };
  var RoleNameCellRender = function RoleNameCellRender(item) {
    if (item.data.attributes.users_permissions_roles.data) {
      return item.data.attributes.users_permissions_roles.data.map(function (m) {
        return m.attributes.name;
      }).join(' ,');
    }
  };
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("h2", {
    className: 'content-block'
  }, "Sign permissions"), /*#__PURE__*/_react["default"].createElement("div", {
    className: 'content-block dx-card responsive-paddings'
  }, /*#__PURE__*/_react["default"].createElement(_dataGrid["default"], {
    id: "gridContainer",
    dataSource: gridDataSource,
    columnAutoWidth: true,
    focusedRowEnabled: true,
    rowAlternationEnabled: true,
    onExporting: onExporting,
    remoteOperations: true
  }, /*#__PURE__*/_react["default"].createElement(_dataGrid.Editing, {
    mode: "popup",
    useIcons: true,
    allowUpdating: true,
    allowAdding: true,
    allowDeleting: true
  }, /*#__PURE__*/_react["default"].createElement(_dataGrid.Popup, {
    title: "Sign permission Info",
    showTitle: true,
    width: 700,
    height: 550
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.Form, {
    labelMode: "floating"
  }, /*#__PURE__*/_react["default"].createElement(_form.Item, {
    itemType: "group",
    colCount: 2,
    colSpan: 2
  }, /*#__PURE__*/_react["default"].createElement(_form.Item, {
    dataField: "attributes.name"
  }), /*#__PURE__*/_react["default"].createElement(_form.Item, {
    dataField: "attributes.users_permissions_roles.data.id"
  }), /*#__PURE__*/_react["default"].createElement(_form.Item, {
    dataField: "attributes.sign_permissions.data.id"
  })))), /*#__PURE__*/_react["default"].createElement(_dataGrid.RemoteOperations, {
    filtering: true
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.Scrolling, {
    rowRenderingMode: "virtual"
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.Paging, {
    defaultPageSize: 10
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.Pager, {
    visible: true,
    showPageSizeSelector: true,
    showInfo: true,
    showNavigationButtons: true,
    allowedPageSizes: allowedPageSizes
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.FilterRow, {
    visible: true,
    applyFilter: ""
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.SearchPanel, {
    placeholder: "Search..."
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.Column, {
    dataField: "id",
    caption: "ID",
    alignment: "left"
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.Column, {
    dataField: "attributes.name",
    caption: "Name",
    alignment: "left"
  }, /*#__PURE__*/_react["default"].createElement(_dataGrid.RequiredRule, {
    message: "Name is required"
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.AsyncRule, {
    validationCallback: nameValidation,
    message: "item name should be unique"
  })), /*#__PURE__*/_react["default"].createElement(_dataGrid.Column, {
    dataField: "attributes.users_permissions_roles.data.id",
    caption: "Roles",
    editCellComponent: RoleTagBox,
    cellRender: RoleNameCellRender
  }, /*#__PURE__*/_react["default"].createElement(_dataGrid.Lookup, {
    valueExpr: "id",
    displayExpr: "name",
    dataSource: roleData
  })), /*#__PURE__*/_react["default"].createElement(_dataGrid.Column, {
    dataField: "attributes.sign_permissions.data.id",
    caption: "Sign permissions"
  }, /*#__PURE__*/_react["default"].createElement(_dataGrid.Lookup, {
    valueExpr: "id",
    displayExpr: "attributes.name",
    dataSource: gridDataSource
  })), /*#__PURE__*/_react["default"].createElement(_dataGrid.Column, {
    dataField: "attributes.createdAt",
    caption: "Created Date",
    alignment: "left",
    dataType: "datetime",
    format: "M/d/yyyy, HH:mm",
    allowEditing: false
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.Column, {
    dataField: "attributes.updatedAt",
    caption: "Update Date",
    alignment: "left",
    dataType: "datetime",
    format: "M/d/yyyy, HH:mm",
    allowEditing: false
  }), /*#__PURE__*/_react["default"].createElement(_dataGrid.Export, {
    enabled: true,
    formats: exportFormats
  }))));
};
var _default = exports["default"] = SignPermission;