· 6 years ago · Sep 10, 2019, 07:24 PM
1import {Component, OnInit} from '@angular/core';
2import {BaseComponent} from '../../base-component/base.component';
3import {Title} from '@angular/platform-browser';
4import {User} from '../../providers/user/user';
5import {Router} from '@angular/router';
6import {CompanyModel} from '../../models/CompanyModel';
7import {FormGroup, Validators, FormBuilder} from '@angular/forms';
8import {ValidationErrors} from '@angular/forms';
9import {AbstractControl} from '@angular/forms';
10import {AlertService} from 'ngx-alerts';
11
12
13@Component({
14 selector: 'app-company',
15 templateUrl: './company.component.html',
16 styleUrls: ['./company.component.css']
17})
18export class CompanyComponent extends BaseComponent implements OnInit {
19 public model: CompanyModel;
20 public isSubmit = false;
21 public isNew = true;
22 public step = 1;
23 public form: FormGroup;
24 public data = [];
25 public controller = 'company';
26
27 constructor(private title: Title,
28 public userApi: User,
29 public router: Router,
30 private formBuilder: FormBuilder,
31 private alert: AlertService) {
32 super(userApi, router);
33 }
34
35 ngOnInit() {
36 this.model = new CompanyModel;
37 const user = this.userApi.getCurrentUser();
38 this.data = user.companies;
39 this.title.setTitle('Мои организации');
40 this.createForm();
41 super.ngOnInit();
42
43 }
44
45 onFileChange(event) {
46 const reader = new FileReader();
47
48 if (event.target.files && event.target.files.length) {
49 const [file] = event.target.files;
50 if (!this.checkMime(file.type)) {
51 return;
52 }
53 reader.readAsDataURL(file);
54
55 reader.onload = () => {
56 this.model.file = reader.result;
57 };
58 }
59 }
60
61 /**
62 * Проверка на Mime
63 * @returns {boolean}
64 */
65 checkMime(type): boolean {
66 const exeMimeTypes = [
67 'application/x-ms-dos-executable',
68 'application/x-dosexec',
69 'application/x-msdownload',
70 'application/exe',
71 'application/x-exe',
72 'application/dos-exe',
73 'vms/exe',
74 'application/x-winexe',
75 'application/msdos-windows',
76 'application/x-msdos-program'
77 ];
78 let result = true;
79 if (exeMimeTypes.join(',').indexOf(type) >= 0) {
80 result = false;
81 this.alert.danger('Файл такого формата запрещен');
82 }
83 return result;
84 }
85
86 /**
87 * Создание формы
88 */
89 createForm(): void {
90 switch (this.step) {
91 case 1:
92 this.form = this.formBuilder.group({
93 name: [this.model.name, [Validators.required, Validators.min(1), this.ValidateSpace]],
94 inn: [this.model.inn, [Validators.required, Validators.min(10)]],
95 });
96 break;
97 case 2:
98 this.form = this.formBuilder.group({
99 adress: [this.model.adress, [Validators.required, Validators.min(10), this.ValidateSpace]],
100 adressFact: [this.model.adressFact, [Validators.required, Validators.min(10), this.ValidateSpace]],
101 kindOfActivity: [this.model.kindOfActivity],
102 });
103 break;
104 default:
105 this.form = this.formBuilder.group({
106 assets: [this.model.assets],
107 file: [this.model.file],
108 });
109 }
110 this.form.valueChanges.subscribe((e) => {
111 for (const key in this.form.value) {
112 this.model[key] = this.form.value[key];
113 }
114 });
115 }
116
117 /**
118 * Сохранить форму
119 * @param form
120 */
121 save(): void {
122 this.isSubmit = true;
123 const controls = this.form.controls;
124 if (this.form.invalid) {
125 Object.keys(controls).forEach(controlName => {
126 controls[controlName].markAsTouched();
127 });
128 this.isSubmit = false;
129 this.alert.danger('Ошибка проверки данных');
130 this.isSubmit = false;
131 return;
132 } else {
133 this.model.inn = this.model.inn + '';
134 let api: any;
135 if (this.model.id) {
136 api = this.userApi.saveCompany(this.model);
137 } else {
138 api = this.userApi.setNewCompany(this.model);
139 }
140
141 api.subscribe((result) => {
142 this.isSubmit = false;
143 Object.keys(controls).forEach(controlName => {
144 controls[controlName].markAsUntouched();
145 controls[controlName].markAsPristine();
146 });
147 this.alert.success('Новая компания сохранена!');
148 this.userApi.setUserData(result);
149 this.step = 1;
150 this.model = new CompanyModel;
151 this.createForm();
152
153 }, (err) => {
154 console.log(err);
155 this.alert.danger('Ошибка сохранения компании!');
156 });
157
158 this.isSubmit = false;
159 }
160
161 }
162
163 /**
164 * Проверка на пробелы
165 * @param {AbstractControl} ctrl
166 * @returns {ValidationErrors}
167 */
168 ValidateSpace(ctrl: AbstractControl): ValidationErrors | null {
169 let value = '';
170 try {
171 value = ctrl.value.trim();
172 } catch {
173 return null;
174 }
175 if (!value.length) {
176 return {required: ' '};
177 }
178 return null;
179 }
180
181 /**
182 * Переход по шагам формы
183 * @param {number} step
184 */
185 setStep(step: number): void {
186 this.isSubmit = true;
187 const controls = this.form.controls;
188 if (this.form.invalid && step > this.step) {
189 Object.keys(controls).forEach(controlName => {
190 controls[controlName].markAsTouched();
191 });
192 this.isSubmit = false;
193 this.alert.danger('Ошибка проверки данных');
194 this.isSubmit = false;
195 return;
196 } else {
197 this.step = step;
198 this.createForm();
199 }
200 }
201
202 /**
203 * Редактировать компанию
204 * @param {number} id
205 */
206 editCompany(id: number): void {
207 const user = this.userApi.getCurrentUser();
208 const company = user.companies.filter((cardItem) => {
209 return cardItem.id === id;
210 });
211 if (company.length) {
212 this.isNew = false;
213 this.model = company.pop();
214 this.step = 1;
215 this.createForm();
216 }
217 }
218
219 /**
220 * Удалить компанию
221 * @param {number} id
222 */
223 deleteCompany(id: number): void {
224 if (confirm('Удалить эту компанию?')) {
225 this.userApi.deleteCompany(id).subscribe((result) => {
226 this.step = 1;
227 this.model = new CompanyModel;
228 this.createForm();
229 this.alert.success('Компания удалена!');
230 this.userApi.setUserData(result);
231
232 }, (err) => {
233 this.alert.danger('Ошибка удаления компании!');
234 });
235 }
236 }
237
238 /**
239 * Новая компания
240 */
241 newCompany(): void {
242 this.step = 1;
243 this.model = new CompanyModel;
244 this.createForm();
245 }
246
247}