import {Component, OnInit} from '@angular/core';
import {environment} from '../../../../environments/environment';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {IconService} from '../../../services/icon.service';
import {NzMessageService, NzModalService, NzUploadFile} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {ConfigService} from '../../../services/config.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-brand',
    templateUrl: './brand.component.html',
    styleUrls: ['./brand.component.scss']
})
export class BrandComponent implements OnInit {
    WEB_SERVE_URL = environment.baseUrl;
    imageUrl = environment.imageUrl;
    searchForm: FormGroup; // 搜索框
    requestData = []; // 列表数据
    total: number; // 页码
    pageNum = 1; // 页码
    pageSize = 10; // 条码
    loading = true;
    isVisible = false;
    editFlag = false;
    id: number;
    validateForm!: FormGroup;
    imgFile = [];
    previewImage: string | undefined = '';
    previewVisible = false;

    goodTypData;

    constructor(
        private form: FormBuilder,
        private config: ConfigService,
        private iconService: IconService,
        private message: NzMessageService,
        private router: Router,
        private modalService: NzModalService,
        private fb: FormBuilder,
    ) {
    }

    ngOnInit(): void {
        this.init();
    }

    public init(): void {
        this.searchForm = this.form.group({
            title: [null],
            goodTypeId: [null],
        });
        this.validateForm = this.fb.group({
            title: [null, [Validators.required]],
            goodTypeId: [null, [Validators.required]],
        });
        this.getRequest(true, this.searchForm.value);

        this.config.getListGoodsType({
            pageNum: 1,
            pageSize: 1000000,
        }, data => {
            this.goodTypData = data['return_data']['list'];
        });
    }

    // 图片查看
    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 getRequest(reset: boolean = false, whereObject: object) {

        this.loading = false;
        if (reset) {
            this.pageNum = 1;
        }
        whereObject['pageNum'] = this.pageNum;
        whereObject['pageSize'] = this.pageSize;
        this.config.getBrandByList(whereObject, data => {
            if (data['return_code'] === '000000') {
                this.requestData = data['return_data'].list;
                this.total = data['return_data'].total;
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

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


    // 修改
    public getEdit(id?: number): void {
        this.validateForm.reset();
        this.editFlag = false;
        this.imgFile = [];
        this.id = id;
        if (id != null) {
            this.editFlag = true;
            this.config.findById(id, data => {
                data['return_data'].goodTypeId = String(data['return_data'].goodTypeId);
                if (data['return_data']['img'] != null && data['return_data']['img'] !== '') {
                    const img = String(data['return_data']['img']);
                    const imgArray = [];
                    imgArray.push(
                        {
                            uid: 1,
                            name: img,
                            status: 'done',
                            url: environment.imageUrl + img
                        });
                    this.imgFile = imgArray;
                }
                this.validateForm.patchValue(data['return_data']);
            });
        }
        this.isVisible = true;
    }

    // 查看详情
    public getDetail(id: number): void {
        this.router.navigate(['/admin/company/company-detail'], {
            queryParams: {
                companyId: id
            }
        }).then(r => console.log(r));
    }

    handleOk(): 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.imgFile.length !== 0) {
            if (this.imgFile[0]['response'] != null) {
                this.validateForm.value.img = this.imgFile[0]['response']['return_data'][0];
            } else {
                this.validateForm.value.img = this.imgFile[0].name;
            }
        }
        if (this.editFlag) {
            this.validateForm.value.id = this.id;
            this.config.updateBrand(this.validateForm.value, data => {
                if (data['return_code'] === '000000') {
                    this.isVisible = false;
                    this.message.success('修改成功');
                    this.getRequest(true, this.searchForm.value);
                } else {
                    this.message.create('error', data['return_msg']);
                }
            });
        } else {
            console.log('123');
            this.config.insertBrand(this.validateForm.value, data => {
                if (data['return_code'] === '000000') {
                    this.isVisible = false;
                    this.message.success('添加成功');
                    this.getRequest(true, this.searchForm.value);
                } else {
                    this.message.create('error', data['return_msg']);
                }
            });
        }
    }

    handleCancel(): void {
        this.isVisible = false;
    }


    // 對話框删除
    showDeleteConfirm(id): void {
        this.modalService.confirm({
            nzTitle: '确定删除',
            nzOkText: '是',
            nzOnOk: () => this.onDelete(id),
            nzCancelText: '否',
        });
    }

    onDelete(ids) {
        this.config.getByDelete({
            id: ids
        }, data => {
            if (data['return_code'] === '000000') {
                this.message.create('success', `删除成功！`);
                this.getRequest(true, this.searchForm.value);
            } else {
                this.message.create('error', data['return_msg']);
            }
        });
    }
}

