· 4 years ago · Jun 21, 2021, 02:44 AM
1import { Component, ElementRef, OnInit, ViewChild, Input } from '@angular/core';
2import { DEFAULT_EDITOR_CONFIG } from 'src/app/shared/configs/tinymce.config';
3import { differenceWith, intersectionWith } from 'lodash';
4import { ApiService } from '../../../shared/services/api.service';
5import Swal from 'sweetalert2';
6import {
7 REMOVE_OPTIONS_CONFIG,
8 CURRENT_OPTIONS_CONFIG,
9 ADD_OPTIONS_CONFIG,
10} from 'src/app/shared/configs/selectize-options.config';
11import { FormControl, FormGroup, Validators } from '@angular/forms';
12import { DiscussionService } from 'src/app/shared/services/discussion.service';
13import { ModalService } from 'src/app/shared/services/modal.service';
14import { forkJoin } from 'rxjs';
15import { map } from 'rxjs/operators';
16
17@Component({
18 selector: 'app-form-discussion',
19 templateUrl: './form-discussion.component.html',
20 styleUrls: ['./form-discussion.component.scss'],
21})
22export class FormDiscussionComponent implements OnInit {
23 @ViewChild('modalCloseBtnRef') modalCloseBtnRef: ElementRef;
24 @Input() discussionSelectedCategory: string = '';
25 @Input() discussionSelectedSubCategory: string;
26 @Input() discussionSelectedChildcategory: string;
27
28 discussionForm: FormGroup;
29 editorConfig = DEFAULT_EDITOR_CONFIG;
30 inputlabel = ''; // this is for input file upload
31 category: string[] = [];
32 subcategory: string[] = [];
33 brands: string[] = [];
34 category_list = [];
35 sub_category_list = [];
36 brands_list = [];
37 user_logged_in: any;
38 uploaded_file_name: any = '';
39 currentOptions: any = [
40 {
41 label: 'Cables and Connectors',
42 value: 'Cables and Connectors',
43 },
44 ];
45 currentOptionsConfig = CURRENT_OPTIONS_CONFIG;
46
47 removeOptions: any = [];
48 removeOptionsConfig = REMOVE_OPTIONS_CONFIG;
49 removeOptionsValue: string[];
50
51 addOptions: any = [];
52 addOptionsConfig = ADD_OPTIONS_CONFIG;
53 addOptionsValue: string[];
54
55 constructor(
56 private modalService: ModalService,
57 private API: ApiService,
58 private discussionService: DiscussionService
59 ) {}
60
61 ngOnInit(): void {
62 this.initForm();
63 // this.getMainCategoryList();
64 // this.getBrandsList();
65 this.getLoggedInUser();
66
67 forkJoin({
68 mainCategory: this.getMainCategoryList(),
69 brandList: this.getBrandsList(),
70 }).subscribe(({ mainCategory, brandList }) => {
71 this.category_list = mainCategory;
72 this.brands_list = brandList;
73
74 // this will watch for input changes on category selectize
75 this.discussionForm
76 .get('category')
77 .valueChanges.subscribe((value) => {
78 console.log('Category has been changed');
79 this.onChangeCategory(value);
80 });
81
82 // patch the value once category selection has been loaded
83 this.discussionForm.patchValue({
84 category: [+this.discussionSelectedSubCategory],
85 });
86 });
87 }
88
89 initForm() {
90 this.discussionForm = new FormGroup({
91 subject: new FormControl(null, Validators.required),
92 editor: new FormControl(null, Validators.required),
93 attachment: new FormControl(null),
94 category: new FormControl(null, Validators.required),
95 subcategory: new FormControl(null, Validators.required),
96 brands: new FormControl(null, Validators.required),
97 notifyCheckbox: new FormControl(true),
98 postAsQuestion: new FormControl(null),
99 file: new FormControl('', [Validators.required]),
100 uploadedFile: new FormControl(null),
101 });
102 }
103
104 onFileChange(event) {
105 if (event.target.files.length > 0) {
106 const file = event.target.files[0];
107 this.inputlabel = file.name;
108 this.discussionForm.patchValue({
109 file: file,
110 });
111 } else {
112 this.inputlabel = '';
113 }
114 }
115
116 // Selectize functions
117 removeSelectedOption() {
118 this.currentOptions = differenceWith(
119 this.currentOptions,
120 this.removeOptionsValue,
121 (oldValue: any, selectedValue: any) => {
122 return (
123 oldValue[this.currentOptionsConfig.valueField] ===
124 selectedValue
125 );
126 }
127 );
128 this.refreshRemoveAndAddOptions();
129 }
130
131 addSelectedOptions() {
132 if (this.addOptionsValue && this.addOptionsValue.length > 0) {
133 const optionsToAdd = intersectionWith(
134 this.addOptions,
135 this.addOptionsValue,
136 (option: any, value: any) => {
137 return option[this.addOptionsConfig.valueField] === value;
138 }
139 );
140 if (optionsToAdd && optionsToAdd.length > 0) {
141 optionsToAdd.forEach((option: any) => {
142 this.currentOptions.push(option);
143 });
144 }
145 this.refreshRemoveAndAddOptions();
146 }
147 }
148
149 refreshRemoveAndAddOptions() {
150 this.removeOptions = this.currentOptions;
151
152 this.addOptions = differenceWith(
153 '',
154 this.removeOptions,
155 (allValue: any, removedValue: any) => {
156 return (
157 allValue[this.currentOptionsConfig.valueField] ===
158 removedValue[this.removeOptionsConfig.valueField]
159 );
160 }
161 );
162 }
163
164 // End Selectize functions
165
166 onFormSubmit() {
167 if (this.inputlabel !== '') {
168 this.fileUpload().subscribe((res) => {
169 this.discussionForm.patchValue({
170 uploadedFile: res.devMessage,
171 });
172
173 this.createDiscussion();
174 });
175 } else {
176 this.createDiscussion();
177 }
178 }
179
180 getMainCategoryList() {
181 let tmp_url = '';
182 if (this.discussionSelectedCategory == 'products') {
183 tmp_url = '/products/get-product-list';
184 } else if (this.discussionSelectedCategory == 'solutions') {
185 tmp_url = '/solutions/get-solution-list';
186 }
187 // this.API.post(tmp_url).subscribe((data) => {
188 // if (data.statusCode == 200) {
189 // data.devMessage.forEach((element) => {
190 // var tmp = {
191 // key: element.key,
192 // label: element.category_name,
193 // value: element.key,
194 // };
195 // this.category_list.push(tmp);
196 // });
197 // } else {
198 // }
199 // });
200
201 return this.API.post(tmp_url).pipe(
202 map((res) => {
203 if (res.statusCode == 200) {
204 return res.devMessage.map((element) => {
205 return {
206 key: element.key,
207 label: element.category_name,
208 value: element.key,
209 };
210 });
211 }
212 })
213 );
214 }
215
216 onChangeCategory(category_id: any) {
217 this.sub_category_list = [];
218 let tmp_url = '';
219
220 if (category_id != '') {
221 if (this.discussionSelectedCategory == 'products') {
222 tmp_url = '/products/get-sub-categories-in-set';
223 } else if (this.discussionSelectedCategory == 'solutions') {
224 tmp_url = '/solutions/get-sub-categories-in-set';
225 }
226 this.API.post(tmp_url, {
227 category_id: JSON.stringify(category_id),
228 }).subscribe((data) => {
229 if (data.statusCode == 200) {
230 data.devMessage.forEach((element) => {
231 var tmp = {
232 key: element.key,
233 label: element.category_name,
234 value: element.key,
235 };
236 this.sub_category_list.push(tmp);
237 });
238
239 // patch the value once subcategory selection has been loaded
240 this.discussionForm.patchValue({
241 subcategory: [+this.discussionSelectedChildcategory],
242 });
243 } else {
244 }
245 });
246 }
247 }
248
249 getBrandsList() {
250 // this.API.post('/brands/get-brands-list').subscribe((data) => {
251 // if (data.statusCode == 200) {
252 // data.devMessage.forEach((element) => {
253 // var tmp = {
254 // key: element.key,
255 // label: element.brand_name,
256 // value: element.key,
257 // };
258 // this.brands_list.push(tmp);
259 // });
260 // } else {
261 // }
262 // });
263
264 return this.API.post('/brands/get-brands-list').pipe(
265 map((res) => {
266 if (res.statusCode == 200) {
267 return res.devMessage.map((element) => {
268 return {
269 key: element.key,
270 label: element.brand_name,
271 value: element.key,
272 };
273 });
274 }
275 })
276 );
277 }
278
279 getLoggedInUser() {
280 if (localStorage.getItem('user_info') !== null) {
281 this.user_logged_in = JSON.parse(localStorage.getItem('user_info'));
282 }
283 }
284
285 createDiscussion() {
286 const formValue = this.discussionForm.value;
287 const newDiscussion = {
288 title: formValue.subject,
289 desc: formValue.editor,
290 categories: JSON.stringify(formValue.category),
291 sub_categories: JSON.stringify(formValue.subcategory),
292 brands: JSON.stringify(formValue.brands),
293 is_a_question: formValue.postAsQuestion,
294 notify_chkbox: formValue.notifyCheckbox,
295 user_id: this.user_logged_in.key,
296 discussion_category: this.discussionSelectedCategory,
297 uploadedFile: this.inputlabel != '' ? formValue.uploadedFile : '',
298 };
299
300 this.closeModal();
301
302 this.discussionService.createDiscussion(newDiscussion).subscribe(
303 (res) => {
304 if (res.statusCode == 200) {
305 Swal.fire(
306 'Success!',
307 'Discussion has been saved!',
308 'success'
309 );
310 this.discussionService.discussionsUpdated.emit(true);
311 this.discussionForm.reset();
312 }
313 },
314 (err) => console.log(err)
315 );
316 }
317
318 fileUpload() {
319 const formData = new FormData();
320 formData.append('file', this.discussionForm.get('file').value);
321 return this.API.post_form_data('/uploads/upload-file', formData);
322 }
323
324 closeModal() {
325 this.modalService.close('discussionModal');
326 }
327}
328