import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {MerchantService} from '../../../services/merchant.service';
import {NzMessageService, NzUploadFile} from 'ng-zorro-antd';
import {ActivatedRoute} from '@angular/router';
import {ValidatorsService} from '../../../services/validators.service';
import {environment} from '../../../../environments/environment';

function getBase64(file: File): Promise<string | ArrayBuffer | null> {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

@Component({
    selector: 'app-merchant-edit',
    templateUrl: './merchant-edit.component.html',
    styleUrls: ['./merchant-edit.component.scss']
})
export class MerchantEditComponent implements OnInit {

    validateForm!: FormGroup;
    data: any;
    editFlag = false;
    id: number;
    passwordVisible = false;
    logoFile = [];
    WEB_SERVE_URL = environment.baseUrl;
    previewImage: string | undefined = '';
    previewVisible = false;

    constructor(
        private fb: FormBuilder,
        private merchant: MerchantService,
        private message: NzMessageService, // 信息提示
        private activatedRoute: ActivatedRoute,
    ) {
    }

    ngOnInit(): void {
        this.activatedRoute.queryParams.subscribe(queryParams => {
            if (queryParams.merchantId != null) {
                this.editFlag = true;
                this.id = queryParams.merchantId;
                this.getDetails(queryParams.merchantId);
            }
        });
        this.validateForm = this.fb.group({
            loginTelephone: [null, [Validators.required]],
            password: [null, [Validators.required, ValidatorsService.minLength(6)]],
            merchantName: [null, [Validators.required]],
            telephone: [null, [Validators.required]],
            address: [null, [Validators.required]],
            bankName: [null],
            bankAccount: [null],
            bankHolder: [null],
            status: [null],
            createTime: [null],
            merchantDesc: [null],
            secUser: {},
        });
    }

    // 返回
    getBack() {
        history.back();
    }

    // 重置
    public resetForm(): void {
        this.validateForm.reset();
    }

    // 保存
    public getSave(): void {
        // tslint:disable-next-line:forin
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
            if (this.validateForm.controls[i].errors != null) {
                this.message.error('必填项不能为空');
                return;
            }
        }

        console.log(this.validateForm.value);
        this.validateForm.value['secUser']['telephone'] = this.validateForm.value.loginTelephone;
        this.validateForm.value['secUser']['password'] = this.validateForm.value.password;
        if (this.logoFile.length !== 0) {
            if (this.logoFile[0]['response'] != null) {
                this.validateForm.value.merchantLogo = this.logoFile[0]['response']['return_data'][0];
            } else {
                this.validateForm.value.merchantLogo = this.logoFile[0].name;
            }
        }

        if (this.editFlag) {
            this.validateForm.value.id = this.id;
            this.merchant.updateMerchant(this.validateForm.value, data => {
                if (data['return_code'] === '000000') {
                    this.getBack();
                    this.message.success('修改成功');
                } else {
                    this.message.create('error', data['return_msg']);
                }
            });
        } else {

            this.merchant.insertMerchant(this.validateForm.value, data => {
                console.log(data);
                if (data['return_code'] === '000000') {
                    this.getBack();
                    this.message.success('添加成功');
                } else {
                    this.message.create('error', data['return_msg']);
                }
            });
        }
    }

    // 图片查看
    handlePreview = async (file: NzUploadFile) => {
        if (!file.url && !file.preview) {
            // tslint:disable-next-line:no-non-null-assertion
            file.preview = await getBase64(file.originFileObj!);
        }
        this.previewImage = file.url || file.preview;
        this.previewVisible = true;
    }

    public getDetails(id) {
        this.merchant.getMerchantById(id, data => {
            if (data['return_code'] === '000000') {
                data['return_data'].loginTelephone = data['return_data'].secUser.loginName;
                data['return_data'].password = data['return_data'].secUser.password;
                if (data['return_data']['merchantLogo'] != null && data['return_data']['merchantLogo'] !== '') {
                    const logo = String(data['return_data']['merchantLogo']);
                    const logoArray = [];
                    logoArray.push(
                        {
                            uid: 1,
                            name: logo,
                            status: 'done',
                            url: environment.imageUrl + logo
                        });
                    this.logoFile = logoArray;
                }
                this.validateForm.patchValue(data['return_data']);
            } else {
                this.message.create('error', data['return_msg']);
            }
        });
    }
}
