import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {environment} from '../../../../environments/environment';
import {CommonsService} from '../../../services/commons.service';
import {NzMessageService, NzUploadFile} from 'ng-zorro-antd';
import {ActivatedRoute} from '@angular/router';
import {DiscountService} from '../../../services/discount.service';

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-discount-edit',
    templateUrl: './discount-edit.component.html',
    styleUrls: ['./discount-edit.component.scss']
})
export class DiscountEditComponent implements OnInit {


    validateForm!: FormGroup;
    data: any;
    editFlag = false;
    id: number;
    discountImg = [];
    usingRange = [];
    usingScope = [];
    WEB_SERVE_URL = environment.baseUrl;
    previewImage: string | undefined = '';
    previewVisible = false;
    wx: WebSocket;

    constructor(
        private fb: FormBuilder,
        private discount: DiscountService,
        private common: CommonsService,
        private commonsService: CommonsService,
        private message: NzMessageService, // 信息提示
        private activatedRoute: ActivatedRoute,
    ) {
    }

    ngOnInit(): void {
        this.activatedRoute.queryParams.subscribe(queryParams => {
            if (queryParams.discountId != null) {
                this.editFlag = true;
                this.id = queryParams.discountId;
                this.getDetails(queryParams.discountId);
            }
        });
        this.validateForm = this.fb.group({
            discountName: [null, [Validators.required]],
            discountCondition: [null],
            discountType: [null, [Validators.required]],
            discountPrice: [null, [Validators.required]],
            salesEndTime: [null, [Validators.required]],
            useScope: [null, [Validators.required]],
            effectiveDay: [1, [Validators.required]],
            receiveNumber: [1, [Validators.required]],
            status: [null],
            usingRange: [null],
            createTime: [null],
            secUser: {},
        });

        this.commonsService.getDictionary('USING_RANGE', data => {
            this.usingScope = data['return_data'];
        });

        this.commonsService.getDictionary('USING_ATTRIBUTION', data => {
            this.usingRange = data['return_data'];
        });
    }


    // 返回
    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;
            }
        }

        if (this.discountImg.length !== 0) {
            if (this.discountImg[0]['response'] != null) {
                this.validateForm.value.discountImg = this.discountImg[0]['response']['return_data'][0];
            } else {
                this.validateForm.value.discountImg = this.discountImg[0].name;
            }
        } else {
            this.message.error('请上传卡券图片');
            return;
        }

        if (this.editFlag) {
            this.common.showConfirm('是否确定修改,确定将下架', dataR => {
                if (dataR) {
                    this.validateForm.value.id = this.id;
                    this.discount.updateDiscount(this.validateForm.value, data => {
                        if (data['return_code'] === '000000') {
                            this.getBack();
                            this.message.success('修改成功，卡券已下架！');
                        } else {
                            this.message.error(data['return_msg']);
                        }
                    });
                }
            });
        } else {
            this.discount.insertDiscount(this.validateForm.value, data => {
                if (data['return_code'] === '000000') {
                    this.getBack();
                    this.message.success('添加成功');
                } else {
                    this.message.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.discount.getDiscountById(id, data => {
            if (data['return_code'] === '000000') {
                data['return_data']['discountType'] = String(data['return_data']['discountType']);
                if (data['return_data']['discountImg'] != null && data['return_data']['discountImg'] !== '') {
                    const discountImg = String(data['return_data']['discountImg']);
                    const couponArray = [];
                    couponArray.push(
                        {
                            uid: 1,
                            name: discountImg,
                            status: 'done',
                            url: environment.imageUrl + discountImg
                        });
                    this.discountImg = couponArray;
                }

                this.validateForm.patchValue(data['return_data']);
            } else {
                this.message.create('error', data['return_msg']);
            }
        });
    }


}
