add-internal-services.component.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. import { DashboardService } from './../../../shared/dashboard.service';
  2. import { HttpClient } from '@angular/common/http';
  3. import { AuthServiceService } from './../../../shared/auth-service.service';
  4. import { ActivatedRoute, Params } from '@angular/router';
  5. import { Subscription, empty } from 'rxjs';
  6. import { Location } from '@angular/common';
  7. import { FormGroup,FormControl, Validators, FormArray, FormBuilder } from '@angular/forms';
  8. import { Component, OnInit, OnDestroy } from '@angular/core';
  9. import { NgxSpinnerService } from 'ngx-spinner';
  10. import { ToastrService } from 'ngx-toastr';
  11. @Component({
  12. selector: 'app-add-internal-services',
  13. templateUrl: './add-internal-services.component.html',
  14. styleUrls: ['./add-internal-services.component.css']
  15. })
  16. export class AddInternalServicesComponent implements OnInit {
  17. constructor(private formBuilder: FormBuilder,
  18. private dashboardSer: DashboardService,
  19. private route: ActivatedRoute,
  20. private spinner: NgxSpinnerService,
  21. private toastr: ToastrService,
  22. private authSer: AuthServiceService,
  23. private http: HttpClient,
  24. private location: Location) { }
  25. addInternalForm: FormGroup; //form group
  26. fields: FormArray; //form array fields inside form group
  27. typeMode: boolean = false; //to check edit or create
  28. //typePageEdit: string = '';
  29. //typeCreatePage: string = '';
  30. typeLink = 'إنشاء جديد'; //type path text create or edit
  31. pageId: number; //pageId for edit
  32. editSubscription: Subscription; //subscription edit
  33. //editObjectPhoto = [];
  34. lastIndex:number; //to get the last index of checkChangeImage on photo case in edit
  35. fieldsData = []; //to in edit mode collect all fields in this array
  36. internalPages = [];
  37. //array of photos data
  38. imageBase64 = [{
  39. photo: '',
  40. photo_type: '',
  41. }];
  42. checkChangeImage = [false]; //check change for any image if change in edit mode or no
  43. urlImg = ['../../assets/image/avatar.png'];
  44. checkSaveClick:boolean = false; //to make button save disabled when submitted form
  45. checkAdd:boolean = false; //to check on edit or create mode to send id in edit mode
  46. photoType: string = ''; //type of photos
  47. checkValidateField: boolean = false; //to send save if all validation of fields is true
  48. showLink: boolean = false;
  49. ngOnInit() {
  50. //show / hide notification search in header
  51. this.authSer.notificationLogin = true;
  52. this.authSer.showSearchHeader = false;
  53. this.authSer.showHeaderLogin = false;
  54. this.authSer.showHeaderDashBoard = true;
  55. //show / hide notification search in header
  56. this.authSer.notificationLogin = true;
  57. this.authSer.showSearchHeader = false;
  58. this.authSer.showHeaderLogin = false;
  59. this.authSer.showHeaderDashBoard = true;
  60. this.authSer.showDashboardHeader = true;
  61. this.authSer.internalHeader = false;
  62. this.dashboardSer.getInternalPages().subscribe(
  63. (responce) => {
  64. console.log(responce);
  65. this.internalPages = responce['pages'];
  66. },
  67. (error) => {
  68. console.log(error);
  69. }
  70. )
  71. //init form data
  72. this.addInternalForm = new FormGroup({
  73. name: new FormControl(null , Validators.required),
  74. name_en: new FormControl(null , Validators.required),
  75. status: new FormControl('1', Validators.required),
  76. fields: this.formBuilder.array([ this.createItem() ])
  77. });
  78. //edit mode
  79. this.editSubscription = this.route.params.subscribe(
  80. (params: Params) => {
  81. if(params['typeInternalMode'] == 'edit') {
  82. this.typeLink = 'تعديل';
  83. this.imageBase64 = [];
  84. this.checkChangeImage = [];
  85. //redifine form data
  86. this.addInternalForm = new FormGroup({
  87. name: new FormControl(null , Validators.required),
  88. name_en: new FormControl(null , Validators.required),
  89. status: new FormControl(null, Validators.required),
  90. fields: this.formBuilder.array([])
  91. });
  92. this.spinner.show();
  93. this.typeMode = true;
  94. this.pageId = params['editInternalId'];
  95. this.dashboardSer.getItemData(this.pageId, 'internalSer').subscribe(
  96. (responce) => {
  97. console.log('responcce', responce);
  98. this.addInternalForm.patchValue({
  99. name: responce['internal_service'].name,
  100. name_en: responce['internal_service'].name_en,
  101. status: responce['internal_service'].status,
  102. });
  103. this.fieldsData = responce['internal_service'].fields;
  104. console.log(this.fieldsData);
  105. this.fields = this.addInternalForm.get('fields') as FormArray;
  106. for(let i = 0; i < this.fieldsData.length; i++) {
  107. this.fields.push(
  108. this.formBuilder.group({
  109. name: this.fieldsData[i].name,
  110. name_en: this.fieldsData[i].name_en,
  111. photo: this.fieldsData[i].photo,
  112. status: this.fieldsData[i].status,
  113. link_type: this.fieldsData[i].link_type,
  114. link: this.fieldsData[i].link,
  115. link2: this.fieldsData[i].link2,
  116. })
  117. )
  118. }
  119. //for loop to append url photo to array to show it
  120. for(let i=0; i<this.fieldsData.length; i++) {
  121. this.urlImg[i] = this.fieldsData[i].photo ? this.authSer.pathImg + this.fieldsData[i].photo : '../../assets/image/avatar.png';
  122. this.checkChangeImage[i] = false;
  123. this.imageBase64[i] = {
  124. photo: this.fieldsData[i].photo ? this.fieldsData[i].photo : '',
  125. photo_type: 'edit'
  126. }
  127. }
  128. //this.lastIndex = this.checkChangeImage.length;
  129. console.log('edit image base 64' , this.imageBase64);
  130. console.log('edit check change image', this.checkChangeImage);
  131. console.log('edit mode url image ' , this.urlImg);
  132. this.spinner.hide();
  133. },
  134. (error) => {
  135. console.log(error);
  136. }
  137. );
  138. } else{
  139. this.typeLink = 'إنشاء جديد';
  140. }
  141. }
  142. );
  143. };
  144. //to make at least on element in form array
  145. createItem(): FormGroup {
  146. if(this.typeMode) {
  147. return this.formBuilder.group({
  148. name: '',
  149. name_en: '',
  150. photo: '',
  151. link: '',
  152. status: '1',
  153. link_type: '',
  154. link2: ''
  155. });
  156. } else {
  157. return this.formBuilder.group({
  158. name: '',
  159. name_en: '',
  160. photo: '',
  161. photo_type: '',
  162. link: '',
  163. status: '1',
  164. link_type: '',
  165. link2: '',
  166. });
  167. }
  168. };
  169. //add more title
  170. onAddTitle() {
  171. this.fields = this.addInternalForm.get('fields') as FormArray;
  172. this.fields.push(this.createItem());
  173. this.urlImg.push('../../assets/image/avatar.png');
  174. this.checkChangeImage.push(false);
  175. //create mode
  176. this.imageBase64.push({
  177. photo: '',
  178. photo_type: '',
  179. });
  180. this.checkAdd = true;
  181. console.log('image base 64',this.imageBase64);
  182. console.log('check change image', this.checkChangeImage);
  183. console.log('url images', this.urlImg);
  184. }
  185. //remove from array form
  186. removeTitle(index: number) {
  187. this.fields = this.addInternalForm.get('fields') as FormArray;
  188. this.fields.removeAt(index);
  189. this.imageBase64.splice(index,1);
  190. this.urlImg.splice(index, 1);
  191. this.checkChangeImage.splice(index, 1);
  192. console.log('image base 64',this.imageBase64);
  193. console.log('check change image', this.checkChangeImage);
  194. console.log('url images', this.urlImg);
  195. }
  196. //upload image
  197. onFileChanges(event,i) {
  198. console.log(event);
  199. alert(i);
  200. this.checkChangeImage[i] = true;
  201. var id_field = ''; //to get id of field from fields
  202. if(this.typeMode) {
  203. //edit mode we have two case if change photo or add new item
  204. if(!this.checkAdd) {
  205. id_field = this.fieldsData[i].id;
  206. //the data of photo user changed it
  207. const dataUploadEdit = {
  208. field_id : id_field,
  209. photo: event[0].base64,
  210. photo_type: event[0].type.split('/')[1].toLowerCase(),
  211. };
  212. //to check validate type of photo and send it to backend
  213. if(dataUploadEdit.photo_type != 'png') {
  214. if(dataUploadEdit.photo_type != 'gif') {
  215. this.toastr.warning('الصوره بصيغه png أو gif');
  216. }
  217. } else {
  218. //send photo change request
  219. this.http.post(this.authSer.pathApi + '/upload_internal_service_field' , dataUploadEdit ).subscribe(
  220. (responce) => {
  221. console.log(responce['photo']);
  222. },
  223. (error) => {
  224. console.log(error);
  225. }
  226. )
  227. }
  228. } else {
  229. //to collect all image base64 of photo upload in craete case
  230. this.photoType = event[0].type.split('/');
  231. this.imageBase64[i]={
  232. photo : event[0].base64,
  233. photo_type: this.photoType[1].toLowerCase(),
  234. };
  235. this.checkChangeImage[i] = true;
  236. console.log(' cheeck change iamge' , this.checkChangeImage);
  237. console.log('base 64 images',this.imageBase64);
  238. }
  239. } else {
  240. //to collect all image base64 of photo upload in craete case
  241. this.photoType = event[0].type.split('/');
  242. this.imageBase64[i]={
  243. photo : event[0].base64,
  244. photo_type: this.photoType[1].toLowerCase(),
  245. };
  246. this.checkChangeImage[i] = true;
  247. console.log(' cheeck change iamge' , this.checkChangeImage);
  248. console.log('base 64 images',this.imageBase64);
  249. }
  250. }
  251. //to upload url to view
  252. getUrl(event,i) {
  253. if (event.target.files && event.target.files[0]) {
  254. var reader = new FileReader();
  255. reader.readAsDataURL(event.target.files[0]); // read file as data url
  256. reader.onload = (event) => { // called once readAsDataURL is completed
  257. this.urlImg[i] = event.target['result'];
  258. console.log('url images' , this.urlImg[i]);
  259. }
  260. }
  261. }
  262. //to show link internal or external depend on value of radio button
  263. showCahngeRadio(type,index) {
  264. this.showLink = type;
  265. const fieldsValue = this.addInternalForm.get('fields')
  266. if(type == 'internal') {
  267. console.log(this.addInternalForm.get('fields')['controls'][index]['controls'].link.value = null);
  268. this.addInternalForm.get('fields')['controls'][index]['controls'].link.value = null
  269. } else if (type == 'external') {
  270. console.log(this.addInternalForm.get('fields')['controls'][index]['controls'].link2.value = null);
  271. this.addInternalForm.get('fields')['controls'][index]['controls'].link2.value = null
  272. }
  273. }
  274. //submitted form
  275. onSubmitted() {
  276. this.checkSaveClick = true;
  277. const formInternalData = this.addInternalForm.value;
  278. console.log(formInternalData);
  279. //edit mode
  280. if(this.typeMode) {
  281. //save edit
  282. for(let i = 0; i < this.imageBase64.length; i++) {
  283. if(this.imageBase64[i].photo_type == 'edit') {
  284. formInternalData['fields'][i].photo = this.imageBase64[i].photo;
  285. } else {
  286. formInternalData['fields'][i].photo = this.imageBase64[i].photo;
  287. formInternalData['fields'][i].photo_type = this.imageBase64[i].photo_type;
  288. }
  289. }
  290. console.log(formInternalData);
  291. //validateion in data fields
  292. for(let i = 0; i < formInternalData['fields'].length; i++) {
  293. if(formInternalData['fields'][i].photo == '') {
  294. this.toastr.warning('قم باختيار صوره للعنصر ' + (i+1) );
  295. this.checkValidateField = true;
  296. this.checkSaveClick = false;
  297. } else if(formInternalData['fields'][i].name == '' || formInternalData['fields'][i].name_en == '' || formInternalData['fields'][i].apperance == '' || formInternalData['fields'][i].status == ''){
  298. this.toastr.warning('من فضلك قم بإكمال بيانات العنصر ' + (i + 1) );
  299. this.checkValidateField = true;
  300. this.checkSaveClick = false;this.checkValidateField = true;
  301. this.checkSaveClick = false;
  302. } else {
  303. this.checkValidateField = false;
  304. this.checkSaveClick = true;
  305. }
  306. }
  307. if(this.checkValidateField) {
  308. console.log('valid imagaes');
  309. } else {
  310. this.dashboardSer.editItem(this.pageId, formInternalData, 'internalSer').subscribe(
  311. (responce) => {
  312. console.log(responce);
  313. this.toastr.success('تم التعديل بنجاح ');
  314. this.checkSaveClick = false;
  315. this.location.back();
  316. }, (error) => {
  317. console.log(error);
  318. this.toastr.error('فشل التعديل !');
  319. this.checkSaveClick = false;
  320. }
  321. );
  322. }
  323. } else {
  324. //for loop to add photo & photo type in form data
  325. for(let i = 0; i< formInternalData['fields'].length; i++) {
  326. for(let j = 0; j < this.imageBase64.length; j++) {
  327. formInternalData['fields'][i].photo = this.imageBase64[i].photo;
  328. formInternalData['fields'][i].photo_type = this.imageBase64[i].photo_type;
  329. }
  330. }
  331. console.log('form data',formInternalData);
  332. //for loop for validation of fields
  333. for(let i=0; i< formInternalData['fields'].length; i++) {
  334. if(formInternalData['fields'][i].photo == '') {
  335. this.checkValidateField = true;
  336. this.checkSaveClick = false;
  337. this.toastr.warning('من فضلك قم بإدخال صوره العنصر ' + ' ' + (i + 1) );
  338. } else if(formInternalData['fields'][i].photo_type != 'png') {
  339. if(formInternalData['fields'][i].photo_type != 'gif') {
  340. this.toastr.warning(' يجب أن تكون الصوره بصيغه png او gif للعنصر' + ' ' + (i + 1) );
  341. }
  342. this.checkValidateField = true;
  343. this.checkSaveClick = false;
  344. }else if(formInternalData['fields'][i].name == '' || formInternalData['fields'][i].status == '') {
  345. this.toastr.warning('من فضلك قم بإكمال بيانات العنصر ' + (i + 1) );
  346. this.checkValidateField = true;
  347. this.checkSaveClick = false;
  348. }
  349. else {
  350. console.log('rightImage');
  351. this.checkSaveClick = true;
  352. this.checkValidateField = false;
  353. }
  354. }
  355. if(this.checkValidateField) {
  356. console.log('logical images error');
  357. }else {
  358. this.dashboardSer.addItem(formInternalData, 'internalSer').subscribe(
  359. (responce) => {
  360. console.log(responce);
  361. this.toastr.success('تم الاضافه بنجاح');
  362. this.location.back();
  363. this.checkSaveClick = false;
  364. },
  365. (error) => {
  366. console.log(error);
  367. this.checkSaveClick = false;
  368. }
  369. );
  370. }
  371. }
  372. };
  373. ngOnDestroy() {
  374. this.editSubscription.unsubscribe();
  375. }
  376. }