import "./chunk-BFN3CBP7.js";
import "./chunk-GMPCSGFS.js";
import {
  ClientDatatableComponent
} from "./chunk-3RTU34A3.js";
import "./chunk-YWQICJL7.js";
import "./chunk-BP5JJWGC.js";
import "./chunk-IGGXREIH.js";
import "./chunk-E6CBXFRG.js";
import {
  MenuMapService
} from "./chunk-3FLJCSSF.js";
import {
  ToastrService
} from "./chunk-2YLAF7RI.js";
import {
  CommonSharedModule,
  DynamicFontSizeDirective,
  TimezoneService
} from "./chunk-7NQGM4EA.js";
import {
  DefaultValueAccessor,
  FormBuilder,
  FormControlName,
  FormGroupDirective,
  NgControlStatus,
  NgControlStatusGroup,
  NgSelectOption,
  RadioControlValueAccessor,
  ReactiveFormsModule,
  SelectControlValueAccessor,
  TranslatePipe,
  TranslateService,
  Validators,
  ɵNgNoValidate,
  ɵNgSelectMultipleOption
} from "./chunk-NLYGDKUR.js";
import "./chunk-ZEL7H2AL.js";
import {
  GridApiService,
  LocalStorageService
} from "./chunk-P7K2QEDI.js";
import {
  DatePipe,
  NgForOf,
  NgIf,
  Title,
  ɵsetClassDebugInfo,
  ɵɵProvidersFeature,
  ɵɵStandaloneFeature,
  ɵɵadvance,
  ɵɵdefineComponent,
  ɵɵdirectiveInject,
  ɵɵelementEnd,
  ɵɵelementStart,
  ɵɵgetCurrentView,
  ɵɵlistener,
  ɵɵnextContext,
  ɵɵpipe,
  ɵɵpipeBind1,
  ɵɵproperty,
  ɵɵresetView,
  ɵɵrestoreView,
  ɵɵtemplate,
  ɵɵtext,
  ɵɵtextInterpolate,
  ɵɵtextInterpolate1
} from "./chunk-GKZIWABI.js";
import "./chunk-CVWHNZRK.js";

// src/app/@lcp-framework/pages/user-role-policy/user-role-policy.component.ts
function UserRolePolicyComponent_div_21_option_5_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "option", 21);
    \u0275\u0275text(1);
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const role_r3 = ctx.$implicit;
    \u0275\u0275property("value", role_r3.id);
    \u0275\u0275advance();
    \u0275\u0275textInterpolate(role_r3.name);
  }
}
function UserRolePolicyComponent_div_21_Template(rf, ctx) {
  if (rf & 1) {
    const _r1 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "div", 17)(1, "select", 18);
    \u0275\u0275listener("change", function UserRolePolicyComponent_div_21_Template_select_change_1_listener() {
      \u0275\u0275restoreView(_r1);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.getPolicyList());
    });
    \u0275\u0275elementStart(2, "option", 19);
    \u0275\u0275text(3);
    \u0275\u0275pipe(4, "translate");
    \u0275\u0275elementEnd();
    \u0275\u0275template(5, UserRolePolicyComponent_div_21_option_5_Template, 2, 2, "option", 20);
    \u0275\u0275elementEnd()();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext();
    \u0275\u0275advance(3);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(4, 2, "select_any"));
    \u0275\u0275advance(2);
    \u0275\u0275property("ngForOf", ctx_r1.roleList);
  }
}
function UserRolePolicyComponent_div_22_option_5_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "option", 21);
    \u0275\u0275text(1);
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const user_r5 = ctx.$implicit;
    \u0275\u0275property("value", user_r5.id);
    \u0275\u0275advance();
    \u0275\u0275textInterpolate(user_r5.name);
  }
}
function UserRolePolicyComponent_div_22_Template(rf, ctx) {
  if (rf & 1) {
    const _r4 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "div", 17)(1, "select", 22);
    \u0275\u0275listener("change", function UserRolePolicyComponent_div_22_Template_select_change_1_listener() {
      \u0275\u0275restoreView(_r4);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.getPolicyList());
    });
    \u0275\u0275elementStart(2, "option", 19);
    \u0275\u0275text(3);
    \u0275\u0275pipe(4, "translate");
    \u0275\u0275elementEnd();
    \u0275\u0275template(5, UserRolePolicyComponent_div_22_option_5_Template, 2, 2, "option", 20);
    \u0275\u0275elementEnd()();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext();
    \u0275\u0275advance(3);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(4, 2, "select_any"));
    \u0275\u0275advance(2);
    \u0275\u0275property("ngForOf", ctx_r1.userList);
  }
}
var _UserRolePolicyComponent = class _UserRolePolicyComponent {
  constructor(fb, toastr, gridApiService, translate, commonService, localStorageService, titleService, datePipe, timezoneService) {
    this.fb = fb;
    this.toastr = toastr;
    this.gridApiService = gridApiService;
    this.translate = translate;
    this.commonService = commonService;
    this.localStorageService = localStorageService;
    this.titleService = titleService;
    this.datePipe = datePipe;
    this.timezoneService = timezoneService;
    this.policyList = [];
    this.tempPolicyList = [];
    this.roleList = [];
    this.userList = [];
    this.policyTableConfig = {
      columns: [
        { key: "isChecked", label: "", sortable: false, searchable: false, type: "checkbox" },
        { key: "id", label: "ID", sortable: false, searchable: false, isHtmlValue: true, colFilterHide: true },
        { key: "policyName", label: "Policy Name", sortable: true, searchable: true, isHtmlValue: true },
        { key: "slug", label: "Slug", sortable: true, searchable: true, isHtmlValue: true },
        { key: "policyDescription", label: "Policy Description", sortable: true, searchable: true, isHtmlValue: true },
        { key: "updatedBy", label: "Updated By", sortable: true, searchable: true, isHtmlValue: true },
        { key: "updatedAt", label: "Updated At", sortable: true, searchable: true, isHtmlValue: true }
      ],
      pageSizes: [5, 10, 25, 50],
      defaultPageSize: 5,
      searchable: true,
      headerConfig: {
        showHeader: true,
        addButton: void 0,
        enableFilter: true,
        enableColumnSelector: true,
        enableExport: true
      }
    };
    this.mappingForm = this.fb.group({
      policy_type: ["user", Validators.required],
      user: [""],
      role: [""]
    });
    this.user_info = JSON.parse(this.localStorageService.getData("user_data"));
  }
  ngOnInit() {
    const translateTitle = this.translate.instant("user_role_policy_map_entity");
    this.titleService.setTitle(translateTitle);
    this.resetComponent();
  }
  resetComponent() {
    this.mappingForm.reset({
      policy_type: "user",
      user: "",
      role: ""
    });
    this.getUserList();
    this.getRoleList();
    this.getPolicyList();
  }
  mapPolicies() {
    console.log(this.mappingForm.invalid);
    if (this.mappingForm.invalid) {
      const key = "please_select_all_the_required_fields";
      const errorMessage = this.translate.instant(key);
      this.toastr.error(errorMessage, "Error");
      return;
    }
    const policy_type = this.mappingForm.get("policy_type")?.value;
    const role_id = this.mappingForm.get("role")?.value;
    const user_id = this.mappingForm.get("user")?.value;
    if (policy_type === "user") {
      this.executeUserMap(user_id);
    } else {
      this.executeRoleMap(role_id);
    }
  }
  updateRadioButton() {
    this.mappingForm.patchValue({
      user: "",
      role: ""
    });
    this.getPolicyList();
  }
  getPolicyList() {
    const role_id = this.mappingForm.get("role")?.value;
    const user_id = this.mappingForm.get("user")?.value;
    const joinCondition = [
      ...role_id && [
        {
          join_type: "LEFT",
          table_name: "role_policies",
          join_condition: `role_policies.role_id = ${role_id} AND role_policies.policy_id = policies.id`
        }
      ],
      ...user_id && [
        {
          join_type: "LEFT",
          table_name: "user_policies",
          join_condition: `user_policies.user_id = ${user_id} AND user_policies.policy_id = policies.id`
        }
      ]
    ];
    const param = {
      company_id: 1,
      print_query: true,
      primary_table: "policies",
      start_index: 0,
      limit_range: 1e3,
      sort_columns: [["policies.name", "asc"]],
      group_by: [
        "policies.id",
        "user_details.first_name",
        "user_details.last_name",
        ...role_id && ["role_policies.role_id"],
        ...user_id && ["user_policies.user_id"]
      ],
      includes: [
        {
          join_type: "LEFT",
          table_name: "user_details",
          join_condition: "user_details.user_id = policies.updated_by"
        },
        ...joinCondition
      ],
      search_all: [
        {
          column_name: "policies.status_id",
          value: "1",
          operator: "="
        }
      ],
      select_columns: [
        ["policies.id"],
        ["policies.name"],
        ["policies.uuid"],
        ["policies.slug"],
        ["policies.description"],
        ["CONCAT(user_details.first_name, ' ', user_details.last_name)", "updated_by"],
        ["policies.updated_at"],
        ...role_id && [["role_policies.role_id"]],
        ...user_id && [["user_policies.user_id"]]
      ]
    };
    this.gridApiService.getListData(param).subscribe((response) => {
      if (response.status) {
        this.policyList = (response.data?.records || []).map((record) => {
          return {
            isChecked: record?.role_id || record?.user_id ? true : false,
            id: record.id,
            policyUUID: record.uuid,
            policyName: record.name,
            policyDescription: record?.description ?? "-",
            slug: record.slug,
            updatedBy: record.updated_by,
            updatedAt: this.formatDateTime(record.updated_at)
          };
        });
        this.tempPolicyList = this.policyList;
      } else {
        this.policyList = [];
        this.tempPolicyList = [];
        const key = response.message;
        const errorMessage = this.translate.instant(key);
        this.toastr.error(`Code: ${response.code} , ${errorMessage}`);
      }
    }, (error) => {
      this.roleList = [];
      const key = "error";
      const errorMessage = this.translate.instant(key);
      this.toastr.error(errorMessage, "Error");
    });
  }
  getRoleList() {
    const param = {
      company_id: 1,
      print_query: false,
      primary_table: "roles",
      start_index: 0,
      limit_range: 1e3,
      sort_columns: [["roles.name", "asc"]],
      search_all: [
        {
          column_name: "roles.status_id",
          value: "1",
          operator: "="
        }
      ],
      select_columns: [["roles.id"], ["roles.name"], ["roles.uuid"]]
    };
    this.gridApiService.getListData(param).subscribe((response) => {
      if (response.status) {
        this.roleList = response.data?.records || [];
      } else if (!response.status) {
        this.roleList = [];
        const key = response.message;
        const errorMessage = this.translate.instant(key);
        this.toastr.error(`Code: ${response.code} , ${errorMessage}`);
      }
    }, (error) => {
      this.roleList = [];
      const key = "error";
      const errorMessage = this.translate.instant(key);
      this.toastr.error(errorMessage, "Error");
    });
  }
  formatDateTime(dateTime) {
    return this.timezoneService.transformDateTime(dateTime);
  }
  getUserList() {
    const param = {
      company_id: 1,
      print_query: false,
      primary_table: "users",
      start_index: 0,
      limit_range: 1e3,
      sort_columns: [["concat(user_details.first_name, ' ', user_details.last_name)", "asc"]],
      search_all: [
        {
          column_name: "users.status_id",
          value: "1",
          operator: "="
        },
        {
          value: ["super_admin", "company_admin"],
          operator: "NOT IN",
          column_name: "users.role"
        }
      ],
      includes: [
        {
          table_name: "user_details",
          join_type: "INNER",
          join_condition: "users.id = user_details.user_id"
        }
      ],
      select_columns: [["users.id"], ["concat(user_details.first_name, ' ', user_details.last_name)", "name"], ["users.uuid"]]
    };
    this.gridApiService.getListData(param).subscribe((response) => {
      if (response.status) {
        this.userList = response.data?.records || [];
      } else if (!response.status) {
        this.userList = [];
        const key = response.message;
        const errorMessage = this.translate.instant(key);
        this.toastr.error(`Code: ${response.code} , ${errorMessage}`);
      }
    }, (error) => {
      this.userList = [];
      const key = "error";
      const errorMessage = this.translate.instant(key);
      this.toastr.error(errorMessage, "Error");
    });
  }
  executeUserMap(user_id) {
    let param = {
      action: ["hard_delete", "insert"],
      table: ["user_policies", "user_policies"],
      table_mapping: ["table1", "table2"],
      conditions: {
        table1: [{ user_id }]
      },
      data: {
        table2: []
      }
    };
    let selectedPolicies = this.policyList.filter((p) => p.isChecked).map((p) => {
      return {
        user_id,
        policy_id: p.id
      };
    });
    param.data.table2 = selectedPolicies;
    this.gridApiService.executeTransaction(param).subscribe((response) => {
      if (response.status) {
        const key = "user_policy_mapping_successfully";
        const successMessage = this.translate.instant(key);
        this.toastr.success(successMessage);
      } else if (!response.status) {
        const key = response.message;
        const errorMessage = this.translate.instant(key);
        this.toastr.error(`Code: ${response.code} , ${errorMessage}`);
      }
    }, (error) => {
      const key = "error";
      const errorMessage = this.translate.instant(key);
      this.toastr.error(errorMessage, "Error");
    });
  }
  executeRoleMap(role_id) {
    let param = {
      action: ["hard_delete", "insert"],
      table: ["role_policies", "role_policies"],
      table_mapping: ["table1", "table2"],
      conditions: {
        table1: [{ role_id }]
      },
      data: {
        table2: []
      }
    };
    let selectedPolicies = this.policyList.filter((p) => p.isChecked).map((p) => {
      return {
        role_id,
        policy_id: p.id
      };
    });
    param.data.table2 = selectedPolicies;
    this.gridApiService.executeTransaction(param).subscribe((response) => {
      if (response.status) {
        const key = "role_policy_mapping_successfully";
        const successMessage = this.translate.instant(key);
        this.toastr.success(successMessage);
      } else if (!response.status) {
        const key = response.message;
        const errorMessage = this.translate.instant(key);
        this.toastr.error(`Code: ${response.code} , ${errorMessage}`);
      }
    }, (error) => {
      const key = "error_mapping_role_policies";
      const errorMessage = this.translate.instant(key);
      this.toastr.error(errorMessage, "Error");
    });
  }
  onPolicyDataChange(data) {
    const itemsToUse = !data || data.length === 0 ? this.policyList : data;
    this.tempPolicyList = [...itemsToUse];
  }
  onPolicySortChange(sort) {
    const items = [...this.tempPolicyList];
    items.sort((a, b) => {
      const aVal = a[sort.column];
      const bVal = b[sort.column];
      return sort.direction === "asc" ? aVal > bVal ? 1 : -1 : aVal < bVal ? 1 : -1;
    });
    this.onPolicyDataChange(items);
  }
};
_UserRolePolicyComponent.\u0275fac = function UserRolePolicyComponent_Factory(t) {
  return new (t || _UserRolePolicyComponent)(\u0275\u0275directiveInject(FormBuilder), \u0275\u0275directiveInject(ToastrService), \u0275\u0275directiveInject(GridApiService), \u0275\u0275directiveInject(TranslateService), \u0275\u0275directiveInject(MenuMapService), \u0275\u0275directiveInject(LocalStorageService), \u0275\u0275directiveInject(Title), \u0275\u0275directiveInject(DatePipe), \u0275\u0275directiveInject(TimezoneService));
};
_UserRolePolicyComponent.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _UserRolePolicyComponent, selectors: [["app-user-role-policy"]], standalone: true, features: [\u0275\u0275ProvidersFeature([DatePipe]), \u0275\u0275StandaloneFeature], decls: 30, vars: 14, consts: [[1, "space-y-6", 3, "formGroup"], [1, "header-panel", "mb-1", "mt-0", "flex", "flex-col", "gap-5", "px-2", "md:flex-row", "md:items-center"], ["appDynamicFontSize", "title", 1, "font-bold", "dark:text-white-light"], [1, "flex", "items-center", "gap-4", "md:flex-row", "md:items-center", "md:ltr:ml-auto", "md:rtl:mr-auto"], [1, "flex", "flex-col", "gap-2", "md:flex-row", "md:items-center"], ["appDynamicFontSize", "body", 1, "relative", "mb-2", "flex-grow", "md:mb-0"], [1, "flex", "list-inside", "space-x-3", "pt-2", "font-semibold", "text-gray-700", "dark:text-[#d0d2d6]", "rtl:space-x-reverse"], [1, "flex", "cursor-pointer", "items-center"], ["type", "radio", "name", "policy_type", "value", "role", "formControlName", "policy_type", 1, "form-radio", 3, "click"], [1, "text-gray-900", "dark:text-white-dark"], ["type", "radio", "name", "policy_type", "value", "user", "formControlName", "policy_type", 1, "form-radio", 3, "click"], ["class", "align-center inline-contents relative justify-center", 4, "ngIf"], [1, "relative", "h-full", "w-full"], [1, "panel", "mt-5", "h-full", "w-full", "rounded-md", "bg-white"], [3, "dataChange", "sortChange", "data", "config"], [1, "mt-4", "flex", "justify-end"], ["type", "submit", 1, "hover:bg-primary-dark", "dark:bg-primary-dark", "dark:focus:ring-primary-dark", "rounded-md", "bg-primary", "px-6", "py-2", "text-white", "shadow-sm", "focus:outline-none", "focus:ring-2", "focus:ring-primary", "focus:ring-offset-2", "dark:text-white", 3, "click"], [1, "align-center", "inline-contents", "relative", "justify-center"], ["appDynamicFontSize", "body", "id", "role", "formControlName", "role", 1, "form-select", "mr-2", "flex", "w-full", "items-center", "text-gray-700", "dark:bg-gray-800", "dark:text-white-dark", 3, "change"], ["value", ""], [3, "value", 4, "ngFor", "ngForOf"], [3, "value"], ["appDynamicFontSize", "body", "id", "user", "formControlName", "user", 1, "form-select", "mr-2", "flex", "w-full", "items-center", "text-gray-700", "dark:bg-gray-800", "dark:text-white-dark", 3, "change"]], template: function UserRolePolicyComponent_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "form", 0)(1, "div", 1)(2, "div", 2);
    \u0275\u0275text(3);
    \u0275\u0275pipe(4, "translate");
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(5, "div", 3)(6, "div", 4)(7, "div", 5)(8, "ul", 6)(9, "li")(10, "label", 7)(11, "input", 8);
    \u0275\u0275listener("click", function UserRolePolicyComponent_Template_input_click_11_listener() {
      return ctx.updateRadioButton();
    });
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(12, "span", 9);
    \u0275\u0275text(13);
    \u0275\u0275pipe(14, "translate");
    \u0275\u0275elementEnd()()();
    \u0275\u0275elementStart(15, "li")(16, "label", 7)(17, "input", 10);
    \u0275\u0275listener("click", function UserRolePolicyComponent_Template_input_click_17_listener() {
      return ctx.updateRadioButton();
    });
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(18, "span", 9);
    \u0275\u0275text(19);
    \u0275\u0275pipe(20, "translate");
    \u0275\u0275elementEnd()()()()();
    \u0275\u0275template(21, UserRolePolicyComponent_div_21_Template, 6, 4, "div", 11)(22, UserRolePolicyComponent_div_22_Template, 6, 4, "div", 11);
    \u0275\u0275elementEnd()()();
    \u0275\u0275elementStart(23, "div", 12)(24, "div", 13)(25, "div")(26, "app-client-datatable", 14);
    \u0275\u0275listener("dataChange", function UserRolePolicyComponent_Template_app_client_datatable_dataChange_26_listener($event) {
      return ctx.onPolicyDataChange($event);
    })("sortChange", function UserRolePolicyComponent_Template_app_client_datatable_sortChange_26_listener($event) {
      return ctx.onPolicySortChange($event);
    });
    \u0275\u0275elementEnd()()()();
    \u0275\u0275elementStart(27, "div", 15)(28, "button", 16);
    \u0275\u0275listener("click", function UserRolePolicyComponent_Template_button_click_28_listener() {
      return ctx.mapPolicies();
    });
    \u0275\u0275text(29, " Submit ");
    \u0275\u0275elementEnd()()();
  }
  if (rf & 2) {
    let tmp_4_0;
    let tmp_5_0;
    \u0275\u0275property("formGroup", ctx.mappingForm);
    \u0275\u0275advance(3);
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(4, 8, "user_role_policy_map_entity"), " ");
    \u0275\u0275advance(10);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(14, 10, "role_permission"));
    \u0275\u0275advance(6);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(20, 12, "user_permission"));
    \u0275\u0275advance(2);
    \u0275\u0275property("ngIf", ((tmp_4_0 = ctx.mappingForm.get("policy_type")) == null ? null : tmp_4_0.value) === "role");
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", ((tmp_5_0 = ctx.mappingForm.get("policy_type")) == null ? null : tmp_5_0.value) === "user");
    \u0275\u0275advance(4);
    \u0275\u0275property("data", ctx.tempPolicyList)("config", ctx.policyTableConfig);
  }
}, dependencies: [CommonSharedModule, NgForOf, NgIf, \u0275NgNoValidate, NgSelectOption, \u0275NgSelectMultipleOption, DefaultValueAccessor, SelectControlValueAccessor, RadioControlValueAccessor, NgControlStatus, NgControlStatusGroup, DynamicFontSizeDirective, TranslatePipe, ReactiveFormsModule, FormGroupDirective, FormControlName, ClientDatatableComponent] });
var UserRolePolicyComponent = _UserRolePolicyComponent;
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(UserRolePolicyComponent, { className: "UserRolePolicyComponent", filePath: "src\\app\\@lcp-framework\\pages\\user-role-policy\\user-role-policy.component.ts", lineNumber: 46 });
})();
export {
  UserRolePolicyComponent
};
//# sourceMappingURL=chunk-E5U3C7L5.js.map
