import {
  FormlyConfigModule,
  FormlyFieldSelectFromDbComponent,
  FormlyForm
} from "./chunk-NFRJCL7R.js";
import {
  ToastrService
} from "./chunk-2YLAF7RI.js";
import {
  CommonSharedModule,
  Store
} from "./chunk-7NQGM4EA.js";
import {
  FormArray,
  FormControl,
  FormGroup,
  FormGroupDirective,
  NgControlStatusGroup,
  TranslatePipe,
  TranslateService,
  ɵNgNoValidate
} from "./chunk-NLYGDKUR.js";
import {
  ActivatedRoute,
  GridApiService,
  LocalStorageService,
  Router
} from "./chunk-P7K2QEDI.js";
import {
  ChangeDetectorRef,
  EventEmitter,
  Location,
  NgClass,
  NgIf,
  NgStyle,
  Observable,
  Title,
  catchError,
  forkJoin,
  map,
  of,
  tap,
  ɵsetClassDebugInfo,
  ɵɵStandaloneFeature,
  ɵɵadvance,
  ɵɵdefineComponent,
  ɵɵdirectiveInject,
  ɵɵelement,
  ɵɵelementContainerEnd,
  ɵɵelementContainerStart,
  ɵɵelementEnd,
  ɵɵelementStart,
  ɵɵgetCurrentView,
  ɵɵlistener,
  ɵɵloadQuery,
  ɵɵnextContext,
  ɵɵpipe,
  ɵɵpipeBind1,
  ɵɵproperty,
  ɵɵpureFunction1,
  ɵɵpureFunction2,
  ɵɵqueryRefresh,
  ɵɵresetView,
  ɵɵrestoreView,
  ɵɵtemplate,
  ɵɵtext,
  ɵɵtextInterpolate,
  ɵɵtextInterpolate1,
  ɵɵviewQuery
} from "./chunk-GKZIWABI.js";
import {
  __spreadProps,
  __spreadValues
} from "./chunk-CVWHNZRK.js";

// src/app/@lcp-framework/pages/form-builder/form-builder.component.ts
var _c0 = (a0) => [a0];
var _c1 = (a0, a1) => [a0, a1];
var _c2 = (a0, a1) => ({ width: a0, height: a1 });
function FormBuilderComponent_button_7_Template(rf, ctx) {
  if (rf & 1) {
    const _r1 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "button", 16);
    \u0275\u0275listener("click", function FormBuilderComponent_button_7_Template_button_click_0_listener() {
      \u0275\u0275restoreView(_r1);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.location.back());
    });
    \u0275\u0275text(1);
    \u0275\u0275pipe(2, "translate");
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    \u0275\u0275advance();
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(2, 1, "back"), " ");
  }
}
function FormBuilderComponent_span_11_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "span", 17);
    \u0275\u0275text(1);
    \u0275\u0275pipe(2, "translate");
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext();
    \u0275\u0275property("ngClass", \u0275\u0275pureFunction1(4, _c0, ctx_r1.store.fontsize === "large" ? "text-base" : ctx_r1.store.fontsize === "medium" ? "text-sm" : "text-xs"));
    \u0275\u0275advance();
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(2, 2, "draft"), " ");
  }
}
function FormBuilderComponent_span_12_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "span", 18);
    \u0275\u0275text(1);
    \u0275\u0275pipe(2, "translate");
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext();
    \u0275\u0275property("ngClass", \u0275\u0275pureFunction2(4, _c1, ctx_r1.store.fontsize === "large" ? "text-base" : ctx_r1.store.fontsize === "medium" ? "text-sm" : "text-xs", ctx_r1.processStatuses[ctx_r1.processStatus] == null ? null : ctx_r1.processStatuses[ctx_r1.processStatus].border_color));
    \u0275\u0275advance();
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(2, 2, ctx_r1.processStatuses[ctx_r1.processStatus].value), " ");
  }
}
function FormBuilderComponent_button_15_Template(rf, ctx) {
  if (rf & 1) {
    const _r3 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "button", 19);
    \u0275\u0275listener("click", function FormBuilderComponent_button_15_Template_button_click_0_listener() {
      \u0275\u0275restoreView(_r3);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.onSubmit(true));
    });
    \u0275\u0275text(1);
    \u0275\u0275pipe(2, "translate");
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext();
    \u0275\u0275property("disabled", ctx_r1.isDisabled);
    \u0275\u0275advance();
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(2, 2, "save_as_draft"), " ");
  }
}
function FormBuilderComponent_button_16_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "button", 20);
    \u0275\u0275text(1);
    \u0275\u0275pipe(2, "translate");
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext();
    \u0275\u0275property("disabled", ctx_r1.isDisabled);
    \u0275\u0275advance();
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(2, 2, "submit"), " ");
  }
}
function FormBuilderComponent_div_17_div_4_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "div", 30)(1, "h3", 31);
    \u0275\u0275text(2);
    \u0275\u0275elementEnd()();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext(2);
    \u0275\u0275advance(2);
    \u0275\u0275textInterpolate(ctx_r1.nestedFormModalConfig.title);
  }
}
function FormBuilderComponent_div_17_button_5_Template(rf, ctx) {
  if (rf & 1) {
    const _r4 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "button", 32);
    \u0275\u0275listener("click", function FormBuilderComponent_div_17_button_5_Template_button_click_0_listener() {
      \u0275\u0275restoreView(_r4);
      const ctx_r1 = \u0275\u0275nextContext(2);
      ctx_r1.nestedFormModalConfig.open = false;
      return \u0275\u0275resetView(ctx_r1.noNestedFormPermission = false);
    });
    \u0275\u0275elementStart(1, "span", 33);
    \u0275\u0275text(2, "Close");
    \u0275\u0275elementEnd();
    \u0275\u0275element(3, "i", 34);
    \u0275\u0275elementEnd();
  }
}
function FormBuilderComponent_div_17_div_7_Template(rf, ctx) {
  if (rf & 1) {
    const _r5 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "div", 35)(1, "span", 36);
    \u0275\u0275text(2, "No permission to view the details");
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(3, "button", 37);
    \u0275\u0275listener("click", function FormBuilderComponent_div_17_div_7_Template_button_click_3_listener() {
      \u0275\u0275restoreView(_r5);
      const ctx_r1 = \u0275\u0275nextContext(2);
      ctx_r1.nestedFormModalConfig.open = false;
      return \u0275\u0275resetView(ctx_r1.noNestedFormPermission = false);
    });
    \u0275\u0275text(4, "Close");
    \u0275\u0275elementEnd()();
  }
}
function FormBuilderComponent_div_17_ng_container_8_app_form_builder_1_Template(rf, ctx) {
  if (rf & 1) {
    const _r6 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "app-form-builder", 39);
    \u0275\u0275listener("closeModal", function FormBuilderComponent_div_17_ng_container_8_app_form_builder_1_Template_app_form_builder_closeModal_0_listener($event) {
      \u0275\u0275restoreView(_r6);
      const ctx_r1 = \u0275\u0275nextContext(3);
      return \u0275\u0275resetView(ctx_r1.onNestedFormSubmitted($event));
    })("nestedFormSuccess", function FormBuilderComponent_div_17_ng_container_8_app_form_builder_1_Template_app_form_builder_nestedFormSuccess_0_listener($event) {
      \u0275\u0275restoreView(_r6);
      const ctx_r1 = \u0275\u0275nextContext(3);
      return \u0275\u0275resetView(ctx_r1.onNestedFormSuccess($event));
    });
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext(3);
    \u0275\u0275property("uuid", ctx_r1.nestedFormUuid)("entityName", ctx_r1.nestedFormEntityName)("entityType", ctx_r1.nestedModalEntityType)("isModal", true)("isNested", true)("fieldKey", ctx_r1.nestedFormFieldKey);
  }
}
function FormBuilderComponent_div_17_ng_container_8_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementContainerStart(0);
    \u0275\u0275template(1, FormBuilderComponent_div_17_ng_container_8_app_form_builder_1_Template, 1, 6, "app-form-builder", 38);
    \u0275\u0275elementContainerEnd();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext(2);
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", ctx_r1.nestedFormEntityName);
  }
}
function FormBuilderComponent_div_17_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "div", 21);
    \u0275\u0275element(1, "div", 22);
    \u0275\u0275elementStart(2, "div", 23)(3, "div", 24);
    \u0275\u0275template(4, FormBuilderComponent_div_17_div_4_Template, 3, 1, "div", 25)(5, FormBuilderComponent_div_17_button_5_Template, 4, 0, "button", 26);
    \u0275\u0275elementStart(6, "div", 27);
    \u0275\u0275template(7, FormBuilderComponent_div_17_div_7_Template, 5, 0, "div", 28)(8, FormBuilderComponent_div_17_ng_container_8_Template, 2, 1, "ng-container", 29);
    \u0275\u0275elementEnd()()()();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext();
    \u0275\u0275advance(3);
    \u0275\u0275property("ngStyle", \u0275\u0275pureFunction2(5, _c2, ctx_r1.nestedFormModalConfig == null ? null : ctx_r1.nestedFormModalConfig.width, ctx_r1.nestedFormModalConfig == null ? null : ctx_r1.nestedFormModalConfig.height));
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", ctx_r1.nestedFormModalConfig == null ? null : ctx_r1.nestedFormModalConfig.title);
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", (ctx_r1.nestedFormModalConfig == null ? null : ctx_r1.nestedFormModalConfig.showClose) !== false);
    \u0275\u0275advance(2);
    \u0275\u0275property("ngIf", ctx_r1.noNestedFormPermission);
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", !ctx_r1.noNestedFormPermission);
  }
}
var _FormBuilderComponent = class _FormBuilderComponent {
  constructor(route, router, gridApiService, toastr, storeData, cdRef, location, translate, titleService, localStorageService) {
    this.route = route;
    this.router = router;
    this.gridApiService = gridApiService;
    this.toastr = toastr;
    this.storeData = storeData;
    this.cdRef = cdRef;
    this.location = location;
    this.translate = translate;
    this.titleService = titleService;
    this.localStorageService = localStorageService;
    this.form = new FormGroup({});
    this.options = {};
    this.model = {};
    this.fields = [];
    this.listDatas = {};
    this.defaultData = {};
    this.uploadedFiles = [];
    this.oldUploadedFiles = [];
    this.policyData = null;
    this.draftMode = false;
    this.isDrafted = false;
    this.processStatus = "submitted";
    this.isNestedFormModalOpen = false;
    this.nestedFormEntityName = null;
    this.nestedFormUuid = null;
    this.noNestedFormPermission = false;
    this.nestedFormFieldKey = null;
    this.nestedFormModalConfig = null;
    this.nestedModalEntityType = "popup_add";
    this.processStatuses = {
      submitted: {
        value: "table_process_status_val_0",
        border_color: "badge-outline-primary"
      },
      approved: {
        value: "table_process_status_val_1",
        border_color: "badge-outline-success"
      },
      rejected: {
        value: "table_process_status_val_2",
        border_color: "badge-outline-danger"
      },
      under_approval: {
        value: "table_process_status_val_3",
        border_color: "badge-outline-warning"
      },
      created: {
        value: "table_process_status_val_4",
        border_color: "badge-outline-success"
      },
      not_appear: {
        value: "table_process_status_val_5",
        border_color: "badge-outline-danger"
      }
    };
    this.isModal = false;
    this.isNested = false;
    this.fieldKey = null;
    this.closeModal = new EventEmitter();
    this.nestedFormSuccess = new EventEmitter();
  }
  ngOnInit() {
    if (!this.uuid) {
      this.route.paramMap.subscribe((params) => {
        const id = params.get("id");
        const uuid = params.get("uuid");
        const value = id || uuid;
        console.log(value);
        this.originaluid = value;
        this.unique_id = value;
      });
    }
    console.log(this.uuid);
    if (this.uuid) {
      this.unique_id = this.uuid;
    }
    console.log(this.unique_id);
    if (!this.entityName) {
      this.route.data.subscribe((data) => {
        this.pageInfo = data["pageInfo"];
        this.entity_name = this.pageInfo.fullEntity;
        this.entity_type = this.pageInfo.action_slug;
        this.draftMode = this.pageInfo.draft_mode;
      });
    }
    console.log(this.nestedModalEntityType);
    if (this.entityName) {
      this.entity_name = this.entityName;
      if (this.entityType) {
        this.entity_type = this.entityType;
      } else {
        if (this.unique_id) {
          this.entity_type = "popup_edit";
        } else {
          this.entity_type = "popup_add";
        }
      }
      const translateTitle = this.translate.instant(this.entity_name);
      this.titleService.setTitle(translateTitle);
    }
    this.user_info = JSON.parse(this.localStorageService.getData("user_data"));
    if (this.user_info.main?.policies) {
      this.policyData = this.user_info.main?.policies || null;
    }
    if (this.entity_type !== "add" && this.entity_type !== "popup_add" && !this.unique_id) {
      this.toastr.error("Invalid entity details given.");
      this.router.navigate(["/dashboard"]);
      return;
    }
    this.options = {
      formState: {
        componentInstance: this,
        // 'this' is the actual component reference
        submitted: false,
        isDraftMode: this.draftMode
      }
    };
    this.initStore();
    this.resetForm();
    this.form.valueChanges.subscribe((val) => {
      const rawValue = this.flatten(val);
      this.processStatus = rawValue?.process_status || "submitted";
      this.isDrafted = rawValue?.is_drafted || false;
    });
  }
  ngAfterViewInit() {
    const pageInfo = this.route.snapshot.data["pageInfo"] || "";
  }
  initStore() {
    this.storeData.select((d) => d.index).subscribe((d) => {
      this.store = d;
    });
  }
  uniqueValidator(key) {
    return (control) => {
      const value = control.value;
      if (!value || !this.listParams[key]) {
        return of(null);
      }
      let listParams = JSON.parse(JSON.stringify(this.listParams[key]));
      if (listParams.search_all) {
        listParams.search_all = listParams.search_all.map((item) => {
          Object.keys(item).forEach((sKey) => {
            if (typeof item[sKey] === "string") {
              if (item[sKey] === "this.label") {
                item[sKey] = value.trim();
              }
              if (item[sKey] === "this.value") {
                item[sKey] = this.unique_id;
              }
            }
          });
          return item;
        });
      }
      listParams = this.replacePlaceholders(listParams, this.model, false);
      return this.gridApiService.getAllList(listParams).pipe(map((response) => {
        if (response.status && response.code === 200) {
          const records = response.data?.records || [];
          return records.length > 0 ? null : { unique: true };
        } else {
          return null;
        }
      }), catchError(() => {
        return of(null);
      }));
    };
  }
  fetchList(field, key, reset = false) {
    return new Observable((observer) => {
      if (!reset && key && this.listDatas[key]) {
        if (field && field.props) {
          field.props.options = this.listDatas[key];
        }
        observer.next(this.listDatas[key]);
        observer.complete();
      } else if (key && this.listParams[key]) {
        const required = false;
        let listParams = this.localStorageService.replaceUniqueId(this.localStorageService.formatPayloadWithPolicyConditions(this.replacePlaceholders(this.listParams[key], this.model, required), this.policyData, field?.attached_policies || []), "$session_user_id", this.user_info.main.id);
        listParams.company_id = 1;
        listParams = this.localStorageService.replaceUniqueId(listParams, "$unique_id", this.unique_id || "");
        console.log(listParams);
        this.gridApiService.getAllList(listParams).subscribe((response) => {
          if (response.status && response.code === 200) {
            const records = response.data?.records || [];
            const options = [...records];
            this.listDatas[key] = options;
            if (field && field.props) {
              field.props.options = options;
            }
            observer.next(options);
            observer.complete();
          } else {
            observer.next([]);
            observer.complete();
          }
        }, (error) => {
          observer.error(error);
        });
      } else {
        observer.next([]);
        observer.complete();
      }
    });
  }
  trimFormValues(formGroup) {
    Object.keys(formGroup.controls).forEach((key) => {
      const control = formGroup.get(key);
      if (control instanceof FormControl) {
        const value = control.value;
        if (typeof value === "string") {
          control.setValue(value.trim(), { emitEvent: false });
        }
      } else if (control instanceof FormGroup || control instanceof FormArray) {
        this.trimFormValues(control);
      }
    });
  }
  onSubmit(draft_mode = false) {
    this.options.formState.submitted = true;
    if (this.form.invalid) {
      return;
    }
    this.trimFormValues(this.form);
    if (this.form.invalid) {
      return;
    }
    const uploadObservables = this.collectFileUploadObservables();
    if (uploadObservables.length === 0) {
      this.executeTransaction(draft_mode);
    } else {
      forkJoin(uploadObservables).subscribe({
        next: () => {
          this.executeTransaction(draft_mode);
        },
        error: (error) => {
          this.toastr.error("Error uploading files: " + error.message);
          if (this.uploadedFiles.length)
            this.deleteImageByName(this.uploadedFiles);
        }
      });
    }
  }
  redirectToCurrentPage() {
    const currentUrl = this.router.url;
    this.router.navigateByUrl("/", { skipLocationChange: true }).then(() => {
      this.router.navigate([currentUrl]);
    });
  }
  executeTransaction(draft_mode) {
    let transParam = this.replaceDataPlaceholders(this.transParam, this.model, false, draft_mode);
    transParam = this.replacePlaceholders(transParam, this.model);
    const val = transParam.data.table1[0].name;
    this.gridApiService.executeTransaction(transParam).subscribe((response) => {
      if (response.status) {
        if (this.oldUploadedFiles.length)
          this.deleteImageByName(this.oldUploadedFiles);
        const key = "transaction_successfully_executed";
        const successMessage = this.translate.instant(key);
        this.toastr.success(successMessage);
        if (this.isNested) {
          setTimeout(() => {
            this.nestedFormSuccess.emit({ value: val, fieldKey: this.fieldKey });
          }, 500);
        } else {
          this.redirectToCurrentPage();
        }
      } else {
        const key = response.message;
        const errorMessage = this.translate.instant(key);
        this.toastr.error(errorMessage, "Error");
        if (this.uploadedFiles.length)
          this.deleteImageByName(this.uploadedFiles);
      }
    }, (error) => {
      const key = "error";
      const errorMessage = this.translate.instant(key);
      this.toastr.error(errorMessage, "Error");
      if (this.uploadedFiles.length)
        this.deleteImageByName(this.uploadedFiles);
    });
  }
  deleteImageByName(images) {
    const uploadObservable = this.gridApiService.deleteImageByName({ images }).subscribe((response) => {
      if (response.status && response.code === 200) {
      }
    });
  }
  collectFileUploadObservables(fields = null, parentKey = "") {
    fields = fields || this.fields;
    const uploadObservables = [];
    this.uploadedFiles = [];
    this.oldUploadedFiles = [];
    fields.forEach((field) => {
      const fieldKey = parentKey ? `${parentKey}.${field.key}` : field.key;
      if (field.fieldGroup?.length) {
        uploadObservables.push(...this.collectFileUploadObservables(field.fieldGroup, fieldKey));
      }
      if (field.fieldArray?.fieldGroup) {
        const formArrayModel = this.model[field.key];
        formArrayModel.forEach((formArrayItem, index) => {
          const nestedFields = field.fieldArray.fieldGroup.map((nestedField) => {
            return __spreadProps(__spreadValues({}, nestedField), {
              key: `${fieldKey}[${index}].${nestedField.key}`
            });
          });
          uploadObservables.push(...this.collectFileUploadObservables(nestedFields));
        });
      }
      if (field.type === "file" || field.type === "image") {
        const controlName = fieldKey;
        const files = this.getFilesFromModel(controlName, parentKey);
        if (files && files.length > 0) {
          const formData = new FormData();
          if (Array.isArray(files)) {
            files.forEach((file) => {
              formData.append("image", file, file.name);
            });
          } else if (files) {
            formData.append("image", files[0], files.name);
          }
          const uploadObservable = this.gridApiService.uploadImageAndGetName(formData).pipe(tap((response) => {
            if (response.body && response.body.status) {
              const docNames = response.body.data.map((item) => item.docName).join(",");
              this.uploadedFiles.push(...response.body.data.map((item) => item.docName));
              const controlKey = this.removeSuffix(controlName, "_file");
              const formControl = this.getFormControlFromPath(controlKey);
              if (formControl) {
                formControl.setValue(docNames);
                this.setNestedValueInModel(this.model, controlKey, docNames);
              }
              const defaultValue = this.getNestedValueFromPath(this.defaultData, controlKey);
              if (defaultValue) {
                this.oldUploadedFiles.push(defaultValue);
              }
            }
          }));
          uploadObservables.push(uploadObservable);
        }
      }
    });
    return uploadObservables;
  }
  setNestedValueInModel(obj, path, value) {
    if (!obj || !path)
      return;
    const pathSegments = path.replace(/\[(\d+)\]/g, ".$1").split(".");
    let current = obj;
    for (let i = 0; i < pathSegments.length; i++) {
      const segment = pathSegments[i];
      if (i === pathSegments.length - 1) {
        current[segment] = value;
      } else {
        if (!current[segment]) {
          current[segment] = isNaN(Number(pathSegments[i + 1])) ? {} : [];
        }
        current = current[segment];
      }
    }
  }
  getNestedValueFromPath(obj, path) {
    if (!obj || !path)
      return void 0;
    const pathSegments = path.replace(/\[(\d+)\]/g, ".$1").split(".");
    let current = obj;
    for (const segment of pathSegments) {
      if (current && segment in current) {
        current = current[segment];
      } else {
        return void 0;
      }
    }
    return current;
  }
  getFormControlFromPath(path) {
    const pathSegments = path.replace(/\[(\d+)\]/g, ".$1").split(".");
    let control = this.form;
    for (const segment of pathSegments) {
      if (control instanceof FormGroup) {
        control = control.get(segment);
      } else if (control instanceof FormArray) {
        control = control.at(parseInt(segment, 10));
      } else {
        return null;
      }
    }
    return control;
  }
  getFilesFromModel(controlName, parentKey) {
    const keys = controlName.split(".");
    let modelValue = this.model;
    keys.forEach((key) => {
      if (modelValue) {
        const arrayMatch = key.match(/^(\w+)\[(\d+)\]$/);
        if (arrayMatch) {
          const arrayKey = arrayMatch[1];
          const index = parseInt(arrayMatch[2], 10);
          modelValue = modelValue[arrayKey]?.[index];
        } else {
          modelValue = modelValue[key];
        }
      }
    });
    return modelValue;
  }
  // private getFilesFromModel(controlName: string, parentKey: string): any {
  //   const keys = controlName.split('.');
  //   let modelValue = this.model;
  //   keys.forEach((key) => {
  //     if (modelValue && modelValue[key] !== undefined) {
  //       modelValue = modelValue[key];
  //     }
  //   });
  //   return modelValue;
  // }
  removeSuffix(value, suffix) {
    return value.endsWith(suffix) ? value.slice(0, -suffix.length) : value;
  }
  replacePlaceholders(obj, model, required = true) {
    const result = JSON.parse(JSON.stringify(obj));
    const placeholderPattern = /^\$(.+)/;
    const replaceInObject = (item) => {
      if (Array.isArray(item)) {
        return item.map(replaceInObject);
      } else if (typeof item === "object" && item !== null) {
        for (const key in item) {
          if (item.hasOwnProperty(key)) {
            item[key] = replaceInObject(item[key]);
          }
        }
        return item;
      } else if (typeof item === "string") {
        const match = item.match(placeholderPattern);
        if (match) {
          const placeholder = match[1];
          const value = this.getNestedProperty(placeholder, model);
          return value !== void 0 ? value : `$${required ? placeholder : ""}`;
        }
      }
      return item;
    };
    return replaceInObject(result);
  }
  titleChange() {
    const translateTitle = this.translate.instant(this.formEntity?.entity_name);
    this.titleService.setTitle(translateTitle);
  }
  replaceDataPlaceholders(obj, model, required = true, draft_mode) {
    const result = JSON.parse(JSON.stringify(obj));
    const placeholderPattern = /^\$(.+)/;
    const replaceInObject = (item, context = model) => {
      if (Array.isArray(item)) {
        return item.map((subItem) => replaceInObject(subItem, context));
      } else if (typeof item === "object" && item !== null) {
        for (const key in item) {
          if (item.hasOwnProperty(key)) {
            item[key] = key === "is_drafted" ? draft_mode : replaceInObject(item[key], context);
          }
        }
        return item;
      } else if (typeof item === "string") {
        const match = item.match(placeholderPattern);
        if (match) {
          const placeholder = match[1];
          let value;
          if (placeholder === "model") {
            value = context;
          } else {
            if (placeholder === "user_id") {
              value = this.user_info.main.id;
            } else if (placeholder === "unique_id") {
              value = this.unique_id;
            } else {
              value = this.getNestedProperty(placeholder, context);
            }
          }
          value = typeof value === "string" ? value?.trim() : value;
          return value !== void 0 ? value : required ? match[0] + placeholder : null;
        }
      }
      return item;
    };
    for (const tableKey in result.data) {
      if (result.data.hasOwnProperty(tableKey)) {
        const placeholdersInTable = result.data[tableKey];
        if (placeholdersInTable.length > 0) {
          const firstPlaceholder = placeholdersInTable[0];
          const firstKeyMatchKey = Object.keys(firstPlaceholder).find((key) => {
            const value = firstPlaceholder[key];
            return typeof value === "string" && value.startsWith("$");
          });
          const firstKeyMatch = firstPlaceholder && firstKeyMatchKey && firstPlaceholder[firstKeyMatchKey] && firstPlaceholder[firstKeyMatchKey].match(placeholderPattern);
          if (firstKeyMatch) {
            const firstKey = firstKeyMatch[1].split(".")[0];
            const key = firstKeyMatch[1].split(".")[1];
            if (model[firstKey] && Array.isArray(model[firstKey])) {
              result.data[tableKey] = model[firstKey].map((detail) => {
                const tableTemplate = JSON.parse(JSON.stringify(placeholdersInTable[0]));
                return replaceInObject(tableTemplate, { [firstKey]: detail });
              });
            } else if (model[firstKey] && model[firstKey][key] && Array.isArray(model[firstKey][key])) {
              result.data[tableKey] = model[firstKey][key].map((detail) => {
                detail = { [key]: detail };
                const tableTemplate = JSON.parse(JSON.stringify(placeholdersInTable[0]));
                return replaceInObject(tableTemplate, { [firstKey]: detail });
              });
            } else {
              result.data[tableKey] = replaceInObject(result.data[tableKey]);
            }
          } else {
          }
        }
      }
    }
    for (const tableKey in result.data) {
      if (result.data.hasOwnProperty(tableKey) && !Array.isArray(result.data[tableKey])) {
        result.data[tableKey] = replaceInObject(result.data[tableKey]);
      }
    }
    return result;
  }
  // private getNestedProperty(path: string, obj: any): any {
  //   return path.split('.').reduce((acc, part) => acc && acc[part], obj);
  // }
  getNestedProperty(path, obj) {
    const pathSegments = path.replace(/\[(\d+)\]/g, ".$1").split(".");
    return pathSegments.reduce((acc, part) => acc && acc[part], obj);
  }
  parseJSONField(value) {
    try {
      return typeof value === "string" ? JSON.parse(value) : value;
    } catch (error) {
      console.error("JSON Parsing Error:", error);
      return value;
    }
  }
  resetForm() {
    const listParams = {
      company_id: 1,
      print_query: false,
      primary_table: "master_entities",
      start_index: 0,
      limit_range: 1,
      sort_columns: [["master_entities.id", "desc"]],
      select_columns: [["master_entities.*"]],
      search_all: [
        { column_name: "master_entities.entity_name", operator: "=", value: this.entity_name },
        { column_name: "master_entities.entity_type", operator: "=", value: "form_builder_module" },
        { column_name: "master_entities.status_id", operator: "=", value: "1" }
      ]
    };
    this.gridApiService.getAllList(listParams).subscribe((response) => {
      if (response.status && response.data?.records?.length > 0) {
        let formEntity = response.data.records[0];
        formEntity.query_information = this.parseJSONField(formEntity.query_information);
        formEntity.form_information = this.parseJSONField(formEntity.form_information);
        formEntity.add_query_information = this.parseJSONField(formEntity.add_query_information);
        formEntity.edit_query_information = this.parseJSONField(formEntity.edit_query_information);
        formEntity.preset_query_information = this.parseJSONField(formEntity.preset_query_information);
        this.formEntity = formEntity;
        this.listParams = this.formEntity.query_information;
        this.transParam = this.entity_type === "add" || this.entity_type === "popup_add" ? this.formEntity.add_query_information : this.formEntity.edit_query_information;
        console.log(this.transParam);
        console.log(this.entity_type);
        this.model = __spreadProps(__spreadValues({}, this.formEntity.form_information.model), { unique_id: this.unique_id });
        this.defaultDataParam = this.formEntity.preset_query_information;
        const fieldsJson = this.formEntity.form_information.fields;
        const isNestedModal = !!this.nestedFormEntityName && (this.entity_type === "popup_add" || this.entity_type === "popup_edit");
        if (!isNestedModal) {
          this.fields = this.processFields(fieldsJson);
          this.setDefaultData();
          this.titleChange();
        }
      } else {
        this.toastr.error("Invalid entity details given.");
        this.router.navigate(["/dashboard"]);
      }
    }, (error) => {
      const key = "error";
      const errorMessage = this.translate.instant(key);
      this.toastr.error(errorMessage, "Error");
      this.router.navigate(["/dashboard"]);
    });
  }
  setDefaultData() {
    console.log(this.entity_type);
    console.log(this.defaultDataParam);
    if (this.entity_type !== "add" && this.defaultDataParam && this.entity_type !== "popup_add" && this.defaultDataParam) {
      if (this.defaultDataParam.primary_table) {
        this.processDefaultParam(this.defaultDataParam);
      } else {
        for (const formControl in this.defaultDataParam) {
          if (this.defaultDataParam.hasOwnProperty(formControl)) {
            this.processDefaultParam(this.defaultDataParam[formControl], formControl);
          }
        }
      }
    }
  }
  processDefaultParam(defaultParam, formControl = null) {
    const defaultDataParam = this.replacePlaceholders(defaultParam, this.model);
    this.gridApiService.getAllList(defaultDataParam).subscribe((response) => {
      if (response.status && response.data?.records?.length > 0) {
        let fieldsJson;
        if (formControl) {
          const control = this.form.get(`${formControl}`);
          if (control instanceof FormArray) {
            fieldsJson = response.data.records;
          } else {
            fieldsJson = response.data.records[0];
          }
          this.defaultData[formControl] = fieldsJson;
        } else {
          fieldsJson = response.data.records[0];
          this.defaultData = fieldsJson;
        }
        this.applyAvailableDataToForm(fieldsJson, formControl);
      } else if (!response.status) {
        this.toastr.error("Invalid entity details given.");
        this.router.navigate(["/dashboard"]);
      }
    }, (error) => {
      const key = "error";
      const errorMessage = this.translate.instant(key);
      this.toastr.error(errorMessage, "Error");
      this.router.navigate(["/dashboard"]);
    });
  }
  applyAvailableDataToForm(updateData, formControl = null) {
    if (Array.isArray(updateData) && formControl) {
      const formArray = this.form.get(formControl);
      if (formArray) {
        this.model[formControl] = updateData;
        this.patchFormArray(formArray, updateData);
      }
    } else {
      const keys = Object.keys(updateData);
      const formData = {};
      keys.forEach((key) => {
        if (formControl) {
          const controlPath = `${formControl}.${key}`;
          const control = this.form.get(controlPath);
          if (control && control instanceof FormArray) {
            const arrayValues = Array.isArray(updateData[key]) ? updateData[key] : `${updateData[key]}`.split(",").map((value) => isNaN(value) ? value : Number(value));
            this.model[formControl][key] = arrayValues;
            if (this.options && this.options.resetModel) {
              this.options.resetModel(this.model);
            }
          } else if (control) {
            if (Array.isArray(control?.value) && !Array.isArray(updateData[key])) {
              let parsedArray = [];
              if (updateData[key] && typeof updateData[key] === "string") {
                try {
                  const parsed = JSON.parse(updateData[key]);
                  parsedArray = Array.isArray(parsed) ? parsed : [];
                } catch (e) {
                  parsedArray = updateData[key].split(",").map((item) => {
                    const trimmed = item.replace(/[\[\]"]/g, "").trim();
                    return trimmed;
                  });
                }
              }
              this.model[formControl][key] = parsedArray;
              control.patchValue(parsedArray);
            } else {
              this.model[formControl][key] = updateData[key];
              control.patchValue(updateData[key]);
            }
          }
        } else {
          const control = this.form.get(key);
          if (control) {
            if (control instanceof FormArray) {
              const arrayValues = Array.isArray(updateData[key]) ? updateData[key] : `${updateData[key]}`.split(",").map((value) => isNaN(value) ? value : Number(value));
              this.model[key] = arrayValues;
              if (this.options && this.options.resetModel) {
                this.options.resetModel(this.model);
              }
            } else {
              control.patchValue(updateData[key]);
            }
          } else if (this.model) {
            this.model[key] = updateData[key];
          }
        }
      });
      if (!Array.isArray(updateData)) {
        if (formControl) {
          this.form.get(formControl)?.patchValue(formData);
        } else {
          this.form.patchValue(formData);
        }
      }
    }
  }
  patchFormArray(formArray, data) {
    formArray.clear();
    data.forEach((item) => {
      formArray.push(this.createFormGroup(item));
    });
    setTimeout(() => {
      if (this.options && this.options.resetModel) {
        this.options.resetModel(this.model);
      }
    }, 500);
    formArray.markAsPristine();
    formArray.markAsUntouched();
  }
  createFormGroup(data) {
    const group = {};
    Object.keys(data).forEach((key) => {
      group[key] = new FormControl(data[key]);
    });
    return new FormGroup(group);
  }
  processFields(fieldsJson) {
    const processedFields = fieldsJson.map((group) => {
      if (Array.isArray(group.fieldGroup)) {
        group.fieldGroup = this.processFields(group.fieldGroup);
        if (group.modal) {
          group.fieldGroup.forEach((field) => {
            field.modal = group.modal;
          });
        }
      }
      if (group.fieldArray && Array.isArray(group.fieldArray.fieldGroup)) {
        group.fieldArray.fieldGroup = this.processFields(group.fieldArray.fieldGroup);
        if (group.modal) {
          group.fieldArray.fieldGroup.forEach((field) => {
            field.modal = group.modal;
          });
        }
      } else if (group.fieldArray?.type === "select" || group.fieldArray?.type === "select-from-db") {
        group.fieldArray.type = "select-from-db";
        if (group.fieldArray.props)
          group.fieldArray.props.placeholder = group.fieldArray.props.placeholder || "Please select";
      }
      if (group.hooks && group.hooks.onInit) {
        if (group.parentConfig && group.parentConfig.hasParent) {
          group.hooks.onInit = (f) => {
            const parentKey = group.parentConfig.parentKey;
            const parentControl = this.form.get(parentKey);
            if (parentControl) {
              parentControl.valueChanges.pipe(tap((parentValue) => {
                this.form.patchValue({ [group.key]: "" });
                if (parentValue) {
                  this.fetchList(f, group.key, true);
                }
              })).subscribe();
            }
          };
        } else {
          group.hooks.onInit = (f) => this.fetchList(f, group.key);
        }
      } else if (group.fieldArray?.hooks && group.fieldArray.hooks.onInit) {
        if (group.fieldArray.parentConfig && group.fieldArray.parentConfig.hasParent) {
          group.fieldArray.hooks.onInit = (f) => {
            const parentKey = group.parentConfig.parentKey;
            const parentControl = this.form.get(parentKey);
            if (parentControl) {
              parentControl.valueChanges.pipe(tap((parentValue) => {
                this.form.patchValue({ [group.key]: "" });
                if (parentValue) {
                  this.fetchList(f, group.key, true);
                }
              })).subscribe();
            }
          };
        } else {
          group.fieldArray.hooks.onInit = (f) => this.fetchList(f, group.key);
        }
      }
      if (group.hooks && group.hooks.onInitFunc) {
        const dynamicHook = this.stringToFunction(group.hooks.onInitFunc);
        if (typeof dynamicHook === "function") {
          group.hooks.onInit = (f) => {
            dynamicHook(f);
          };
        }
      } else if (group.fieldArray?.hooks && group.fieldArray.hooks.onInitFunc) {
        const dynamicHook = this.stringToFunction(group.fieldArray.hooks.onInitFunc);
        if (typeof dynamicHook === "function") {
          group.fieldArray.hooks.onInit = (f) => {
            dynamicHook(f);
          };
        }
      }
      if (group.hooks && group.hooks.uniqueKey) {
        const uniqueKey = group.hooks.uniqueKey;
        group.modelOptions = {
          updateOn: "blur"
        };
        if (typeof uniqueKey === "string") {
          group.asyncValidators = { unique: { expression: this.uniqueValidator(uniqueKey), message: "this_value_cannot_be_duplicate" } };
        }
      } else if (group.fieldArray?.hooks && group.fieldArray.hooks.uniqueKey) {
        const uniqueKey = group.fieldArray.hooks.uniqueKey;
        group.fieldArray.modelOptions = {
          updateOn: "blur"
        };
        if (typeof uniqueKey === "string") {
          group.fieldArray.asyncValidators = { unique: { expression: this.uniqueValidator(uniqueKey), message: "this_value_cannot_be_duplicate" } };
        }
      }
      if (group.type === "select" || group.type === "select-from-db") {
        group.type = "select-from-db";
        if (group.props)
          group.props.placeholder = group.props.placeholder || "Please select";
        this.fetchList(group, group.key, true);
        if (!this.listParams || !this.listParams[group.key]) {
          const opts = group.templateOptions || group.props || {};
          if (opts.table && opts.valueColumn && opts.labelColumn) {
            this.listParams = this.listParams || {};
            this.listParams[group.key] = {
              primary_table: opts.table,
              select_columns: [[
                opts.valueColumn.includes("CONCAT(") ? opts.valueColumn : `${opts.table}.${opts.valueColumn}`
              ], [
                opts.labelColumn.includes("CONCAT(") ? opts.labelColumn : `${opts.table}.${opts.labelColumn}`
              ]],
              search_all: opts.search_all || [],
              sort_columns: opts.sort_columns || [],
              print_query: false,
              start_index: 0,
              limit_range: 1e3
            };
            this.fetchList(group, group.key, true);
          }
        }
      }
      if (group.type === "select-from-db") {
        this.fetchList(group, group.key, true);
        if (!this.listParams || !this.listParams[group.key]) {
          const opts = group.templateOptions || group.props || {};
          if (opts.table && opts.valueColumn && opts.labelColumn) {
            this.listParams = this.listParams || {};
            this.listParams[group.key] = {
              primary_table: opts.table,
              select_columns: [[
                opts.valueColumn.includes("CONCAT(") ? opts.valueColumn : `${opts.table}.${opts.valueColumn}`
              ], [
                opts.labelColumn.includes("CONCAT(") ? opts.labelColumn : `${opts.table}.${opts.labelColumn}`
              ]],
              search_all: opts.search_all || [],
              sort_columns: opts.sort_columns || [],
              print_query: false,
              start_index: 0,
              limit_range: 1e3
            };
            this.fetchList(group, group.key, true);
          }
        }
      }
      if (group.fieldArray && group.fieldArray.type === "select-from-db") {
        this.fetchList(group.fieldArray, group.key, true);
        if (!this.listParams || !this.listParams[group.key]) {
          const opts = group.fieldArray.templateOptions || group.fieldArray.props || {};
          if (opts.table && opts.valueColumn && opts.labelColumn) {
            this.listParams = this.listParams || {};
            this.listParams[group.key] = {
              primary_table: opts.table,
              select_columns: [[
                opts.valueColumn.includes("CONCAT(") ? opts.valueColumn : `${opts.table}.${opts.valueColumn}`
              ], [
                opts.labelColumn.includes("CONCAT(") ? opts.labelColumn : `${opts.table}.${opts.labelColumn}`
              ]],
              search_all: opts.search_all || [],
              sort_columns: opts.sort_columns || [],
              print_query: false,
              start_index: 0,
              limit_range: 1e3
            };
            this.fetchList(group.fieldArray, group.key, true);
          }
        }
      }
      if (this.entity_type === "details") {
        group.expressions = group.expressions || {};
        group.expressions["props.disabled"] = "true";
      }
      return group;
    });
    const selectKeys = this.collectSelectKeys(processedFields);
    selectKeys.forEach((key) => {
      const fieldConfig = this.findFieldConfigByKey(processedFields, key);
      this.fetchList(fieldConfig, key, true).subscribe({
        next: (options) => {
        },
        error: (err) => {
          console.error("Error fetching options for", key, err);
        }
      });
    });
    return processedFields;
  }
  stringToFunction(fnString) {
    try {
      return new Function("model", "formState", `return (${fnString})(model, formState);`);
    } catch (error) {
      console.error("Error creating function from string:", fnString, error);
      return () => null;
    }
  }
  flatten(obj) {
    return Object.keys(obj).reduce((acc, key) => {
      const value = obj[key];
      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        Object.assign(acc, this.flatten(value));
      } else {
        acc[key] = value;
      }
      return acc;
    }, {});
  }
  get isDisabled() {
    return this.processStatus === "under_approval";
  }
  // Method to open nested form-builder modal
  openAddNestedFormModal(entityName, fieldKey, modalConfig) {
    this.nestedModalEntityType = "popup_add";
    this.openNestedFormModal(entityName, fieldKey, modalConfig, null, "popup_add");
  }
  openNestedFormModal(entityName, fieldKey, modalConfig, uuid, mode) {
    console.log(entityName);
    console.log(fieldKey);
    console.log(uuid);
    this.noNestedFormPermission = false;
    const userData = this.user_info || JSON.parse(this.localStorageService.getData("user_data"));
    const unorgmenuList = userData?.unorgmenuList || [];
    let menuPermissionId = null;
    if (unorgmenuList && Array.isArray(unorgmenuList)) {
      const menuItem = unorgmenuList.find((item) => item.entity_name === entityName && (uuid ? item.action_slug === "edit" || item.action_slug === "popup_edit" : item.action_slug === "add" || item.action_slug === "popup_add"));
      if (menuItem) {
        menuPermissionId = menuItem.permission_id;
      }
    }
    let hasPermission = true;
    if (menuPermissionId && userData?.main?.permissions && Array.isArray(userData.main.permissions)) {
      const permObj = userData.main.permissions.find((perm) => perm.id == menuPermissionId);
      hasPermission = !!(permObj && permObj.accessible);
    }
    if (!hasPermission) {
      this.noNestedFormPermission = true;
      this.nestedFormModalConfig = { open: true, title: "No Permission" };
      return;
    }
    this.nestedFormEntityName = entityName;
    this.nestedFormUuid = uuid || null;
    console.log(mode);
    this.nestedModalEntityType = mode ? mode : uuid ? "popup_edit" : "popup_add";
    console.log(this.nestedModalEntityType);
    this.nestedFormFieldKey = fieldKey || null;
    this.nestedFormModalConfig = __spreadProps(__spreadValues({}, modalConfig || {}), { open: true });
  }
  // Method to close nested form-builder modal
  closeNestedFormModal() {
    if (this.nestedFormModalConfig) {
      this.nestedFormModalConfig.open = false;
    }
    this.nestedFormEntityName = null;
    this.nestedFormUuid = null;
    this.nestedModalEntityType = "popup_add";
  }
  // Method to handle nested form submission
  onNestedFormSubmitted(formData) {
    if (formData && formData.success) {
      this.closeNestedFormModal();
      this.refreshFormData();
    } else {
      this.closeNestedFormModal();
    }
  }
  // Method to refresh form data
  refreshFormData() {
    this.resetForm();
    this.toastr.success("Record created successfully. Form data refreshed.");
  }
  refreshSelectFromDbOptions() {
    this.fields = JSON.parse(JSON.stringify(this.fields));
    this.cdRef.detectChanges();
  }
  // Recursive helper to find a field config by key, searching all nested fieldGroups and fieldArrays
  findFieldConfigByKey(fields, key) {
    for (const field of fields) {
      if (typeof field === "object" && field !== null) {
        if (field.key === key) {
          return field;
        }
        if (Array.isArray(field.fieldGroup)) {
          const found = this.findFieldConfigByKey(field.fieldGroup, key);
          if (found)
            return found;
        }
        if (field.fieldArray && typeof field.fieldArray === "object" && Array.isArray(field.fieldArray.fieldGroup)) {
          const found = this.findFieldConfigByKey(field.fieldArray.fieldGroup, key);
          if (found)
            return found;
        }
      }
    }
    return null;
  }
  onNestedFormSuccess(event) {
    this.refreshSelectFromDbOptions();
    if (event && event.value && event.fieldKey) {
      const fieldConfig = this.findFieldConfigByKey(this.fields, event.fieldKey);
      this.fetchList(fieldConfig, event.fieldKey, true).subscribe(() => {
        Object.keys(this.listDatas).forEach((k) => {
        });
        const normalizedKey = event.fieldKey.trim();
        const options = this.listDatas[normalizedKey] || [];
        this.model[event.fieldKey] = event.value;
        const control = this.form.get(event.fieldKey);
        if (control) {
          control.setValue(event.value);
        }
        const currentValue = fieldConfig?.formControl?.value;
        if (fieldConfig?.formControl) {
          let updatedValue = [];
          if (Array.isArray(currentValue)) {
            updatedValue = currentValue.includes(event.value) ? currentValue : [...currentValue, event.value];
          } else if (currentValue !== void 0 && currentValue !== null) {
            updatedValue = [currentValue, event.value];
          } else {
            updatedValue = [event.value];
          }
          if (Array.isArray(options)) {
            updatedValue = updatedValue.map((val) => {
              if (typeof val === "string") {
                const found = options.find((opt) => opt.label === val || opt.name === val);
                if (found) {
                  return found.id !== void 0 ? found.id : found.value;
                }
              }
              return val;
            });
          }
          fieldConfig.formControl.setValue(updatedValue);
        }
        this.closeNestedFormModal();
      });
    }
  }
  collectSelectKeys(fields) {
    const selectKeys = [];
    const collectKeys = (field) => {
      if (typeof field === "object" && field !== null) {
        if (field.type === "select" || field.type === "select-from-db") {
          if (typeof field.key === "string") {
            selectKeys.push(field.key);
          }
        }
        if (field.fieldArray && typeof field.fieldArray === "object" && Array.isArray(field.fieldArray.fieldGroup)) {
          field.fieldArray.fieldGroup.forEach(collectKeys);
        }
        if (Array.isArray(field.fieldGroup)) {
          field.fieldGroup.forEach(collectKeys);
        }
      }
    };
    fields.forEach(collectKeys);
    return selectKeys;
  }
};
_FormBuilderComponent.\u0275fac = function FormBuilderComponent_Factory(t) {
  return new (t || _FormBuilderComponent)(\u0275\u0275directiveInject(ActivatedRoute), \u0275\u0275directiveInject(Router), \u0275\u0275directiveInject(GridApiService), \u0275\u0275directiveInject(ToastrService), \u0275\u0275directiveInject(Store), \u0275\u0275directiveInject(ChangeDetectorRef), \u0275\u0275directiveInject(Location), \u0275\u0275directiveInject(TranslateService), \u0275\u0275directiveInject(Title), \u0275\u0275directiveInject(LocalStorageService));
};
_FormBuilderComponent.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _FormBuilderComponent, selectors: [["app-form-builder"]], viewQuery: function FormBuilderComponent_Query(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275viewQuery(FormlyFieldSelectFromDbComponent, 5);
  }
  if (rf & 2) {
    let _t;
    \u0275\u0275queryRefresh(_t = \u0275\u0275loadQuery()) && (ctx.selectFromDbFields = _t);
  }
}, inputs: { uuid: "uuid", entityName: "entityName", entityType: "entityType", isModal: "isModal", isNested: "isNested", fieldKey: "fieldKey" }, outputs: { closeModal: "closeModal", nestedFormSuccess: "nestedFormSuccess" }, standalone: true, features: [\u0275\u0275StandaloneFeature], decls: 18, vars: 14, consts: [[1, "space-y-8"], [1, "grid", "grid-cols-1", "gap-6", "lg:grid-cols-1"], [1, "panel"], [1, "mb-5", "flex", "items-center", "justify-between"], [1, "text-lg", "font-semibold", "dark:text-white-light"], ["type", "button", "class", "btn-danger rounded-md border border-[#e0e6ed] px-4 py-2 font-semibold ltr:rounded-r rtl:rounded-l", 3, "click", 4, "ngIf"], [1, "mb-5"], ["novalidate", "", 3, "ngSubmit", "formGroup"], [1, "mb-5", "flex", "flex-wrap", "items-center", "justify-end", "gap-2"], ["class", "badge badge-outline-secondary", 3, "ngClass", 4, "ngIf"], ["class", "badge", 3, "ngClass", 4, "ngIf"], [3, "form", "fields", "options", "model"], [1, "flex", "flex-wrap", "justify-center", "gap-5"], ["type", "button", "class", "btn-primary flex items-center rounded-md border border-[#e0e6ed] px-4 py-2 font-semibold dark:border-[#253b5c] dark:bg-[#1b2e4b] dark:text-white-dark", 3, "disabled", "click", 4, "ngIf"], ["type", "submit", "class", "btn-primary flex items-center rounded-md border border-[#e0e6ed] px-4 py-2 font-semibold dark:border-[#253b5c] dark:bg-[#1b2e4b] dark:text-white-dark", 3, "disabled", 4, "ngIf"], ["class", "fixed inset-0 z-50 overflow-y-auto", 4, "ngIf"], ["type", "button", 1, "btn-danger", "rounded-md", "border", "border-[#e0e6ed]", "px-4", "py-2", "font-semibold", "ltr:rounded-r", "rtl:rounded-l", 3, "click"], [1, "badge", "badge-outline-secondary", 3, "ngClass"], [1, "badge", 3, "ngClass"], ["type", "button", 1, "btn-primary", "flex", "items-center", "rounded-md", "border", "border-[#e0e6ed]", "px-4", "py-2", "font-semibold", "dark:border-[#253b5c]", "dark:bg-[#1b2e4b]", "dark:text-white-dark", 3, "click", "disabled"], ["type", "submit", 1, "btn-primary", "flex", "items-center", "rounded-md", "border", "border-[#e0e6ed]", "px-4", "py-2", "font-semibold", "dark:border-[#253b5c]", "dark:bg-[#1b2e4b]", "dark:text-white-dark", 3, "disabled"], [1, "fixed", "inset-0", "z-50", "overflow-y-auto"], [1, "fixed", "inset-0", "bg-black/50", "transition-opacity", "dark:bg-black/70"], [1, "flex", "min-h-screen", "items-center", "justify-center", "p-4"], [1, "relative", "w-full", "max-w-5xl", "transform", "overflow-visible", "rounded-lg", "bg-white", "shadow-xl", "transition-all", "dark:border", "dark:border-gray-700", "dark:bg-gray-800", 3, "ngStyle"], ["class", "p-4 border-b", 4, "ngIf"], ["type", "button", "class", "btn-xs absolute -top-5 -right-5 z-20 rounded-full bg-white shadow-lg border border-gray-200 w-8 h-8 flex items-center justify-center text-gray-500 hover:text-gray-700 hover:bg-gray-100 focus:outline-none", 3, "click", 4, "ngIf"], [1, "max-h-[80vh]", "overflow-y-auto", "p-4"], ["class", "flex flex-col items-center justify-center min-h-[200px]", 4, "ngIf"], [4, "ngIf"], [1, "p-4", "border-b"], [1, "text-lg", "font-semibold"], ["type", "button", 1, "btn-xs", "absolute", "-top-5", "-right-5", "z-20", "rounded-full", "bg-white", "shadow-lg", "border", "border-gray-200", "w-8", "h-8", "flex", "items-center", "justify-center", "text-gray-500", "hover:text-gray-700", "hover:bg-gray-100", "focus:outline-none", 3, "click"], [1, "sr-only"], [1, "fa-solid", "fa-xmark", "text-2xl"], [1, "flex", "flex-col", "items-center", "justify-center", "min-h-[200px]"], [1, "text-lg", "text-red-600", "font-semibold", "mb-4"], [1, "btn", "btn-primary", 3, "click"], [3, "uuid", "entityName", "entityType", "isModal", "isNested", "fieldKey", "closeModal", "nestedFormSuccess", 4, "ngIf"], [3, "closeModal", "nestedFormSuccess", "uuid", "entityName", "entityType", "isModal", "isNested", "fieldKey"]], template: function FormBuilderComponent_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "div", 0)(1, "div", 1)(2, "div", 2)(3, "div", 3)(4, "h5", 4);
    \u0275\u0275text(5);
    \u0275\u0275pipe(6, "translate");
    \u0275\u0275elementEnd();
    \u0275\u0275template(7, FormBuilderComponent_button_7_Template, 3, 3, "button", 5);
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(8, "div", 6)(9, "form", 7);
    \u0275\u0275listener("ngSubmit", function FormBuilderComponent_Template_form_ngSubmit_9_listener() {
      return ctx.onSubmit(false);
    });
    \u0275\u0275elementStart(10, "div", 8);
    \u0275\u0275template(11, FormBuilderComponent_span_11_Template, 3, 6, "span", 9)(12, FormBuilderComponent_span_12_Template, 3, 7, "span", 10);
    \u0275\u0275elementEnd();
    \u0275\u0275element(13, "formly-form", 11);
    \u0275\u0275elementStart(14, "div", 12);
    \u0275\u0275template(15, FormBuilderComponent_button_15_Template, 3, 4, "button", 13)(16, FormBuilderComponent_button_16_Template, 3, 4, "button", 14);
    \u0275\u0275elementEnd()()()()()();
    \u0275\u0275template(17, FormBuilderComponent_div_17_Template, 9, 8, "div", 15);
  }
  if (rf & 2) {
    \u0275\u0275advance(5);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(6, 12, ctx.formEntity == null ? null : ctx.formEntity.entity_name));
    \u0275\u0275advance(2);
    \u0275\u0275property("ngIf", !ctx.entityName);
    \u0275\u0275advance(2);
    \u0275\u0275property("formGroup", ctx.form);
    \u0275\u0275advance(2);
    \u0275\u0275property("ngIf", ctx.isDrafted);
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", ctx.processStatus && ctx.processStatus != "submitted");
    \u0275\u0275advance();
    \u0275\u0275property("form", ctx.form)("fields", ctx.fields)("options", ctx.options)("model", ctx.model);
    \u0275\u0275advance(2);
    \u0275\u0275property("ngIf", ctx.entity_type !== "details" && ctx.draftMode);
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", ctx.entity_type !== "details");
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", ctx.nestedFormModalConfig == null ? null : ctx.nestedFormModalConfig.open);
  }
}, dependencies: [_FormBuilderComponent, CommonSharedModule, NgClass, NgIf, NgStyle, \u0275NgNoValidate, NgControlStatusGroup, TranslatePipe, FormlyConfigModule, FormlyForm, FormGroupDirective], styles: ["\n\n  formly-wrapper-form-field .mb-3 {\n  margin-bottom: 0.4rem;\n}\n  formly-field .form-control {\n  width: 100%;\n  border-radius: 0.375rem;\n  border-width: 1px;\n  --tw-border-opacity: 1;\n  border-color: rgb(224 230 237/var(--tw-border-opacity));\n  --tw-bg-opacity: 1;\n  background-color: rgb(255 255 255/var(--tw-bg-opacity));\n  padding-top: 0.375rem;\n  padding-bottom: 0.375rem;\n  padding-left: 0.8rem;\n  font-size: 0.75rem;\n  line-height: 1rem;\n  font-weight: 600;\n  --tw-text-opacity: 1;\n  color: rgb(14 23 38/var(--tw-text-opacity));\n  outline: 2px solid transparent !important;\n  outline-offset: 2px !important;\n}\n  formly-field .ng-select.form-control {\n  border-width: 0;\n  padding-top: 0;\n  padding-left: 0;\n  padding-bottom: 0;\n}\n  .was-validated .form-control:invalid,   .form-control.is-invalid {\n  --tw-text-opacity: 1;\n  border-color: rgb(231 81 90/var(--tw-text-opacity));\n  background-color: rgba(231, 81, 90, 0.0784313725);\n  color: inherit;\n}\n  .was-validated .ng-select:invalid .ng-select-container,   .ng-select.is-invalid .ng-select-container {\n  --tw-text-opacity: 1;\n  border-color: rgb(231 81 90/var(--tw-text-opacity));\n  background-color: rgba(231, 81, 90, 0.0784313725);\n  color: inherit;\n}\n  formly-field label.form-label span {\n  color: rgb(231 81 90/var(--tw-text-opacity));\n}\n  formly-field .has-error .form-label {\n  color: inherit;\n}\n  formly-field .invalid-feedback {\n  --tw-text-opacity: 1;\n  color: rgb(231 81 90/var(--tw-text-opacity));\n  margin-top: 0.25rem;\n}\n  formly-field .form-check {\n  display: block;\n  min-height: 1.5rem;\n  padding-left: 1.5em;\n  margin-bottom: 0.125rem;\n  float: left;\n  margin-right: 10px;\n  margin-top: 10px;\n}\n  formly-field .form-check .form-check-input {\n  float: left;\n  margin-left: -1.5em;\n}\n  .ng-select.ng-select-single .ng-select-container {\n  height: 30px;\n}\n  .ng-select .ng-select-container {\n  min-height: 30px;\n}\n/*# sourceMappingURL=form-builder.component.css.map */"] });
var FormBuilderComponent = _FormBuilderComponent;
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(FormBuilderComponent, { className: "FormBuilderComponent", filePath: "src\\app\\@lcp-framework\\pages\\form-builder\\form-builder.component.ts", lineNumber: 26 });
})();

export {
  FormBuilderComponent
};
//# sourceMappingURL=chunk-FXJXZPYD.js.map
