import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {environment} from '../../../../environments/environment';
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 {MerchantStoreService} from '../../../services/merchant-store.service';
import {CommonsService} from "../../../services/commons.service";

declare var AMap: any;    // 一定要声明AMap，要不然报错找不到AMap
declare var AMapUI: any;

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

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

    constructor(
        private fb: FormBuilder,
        private merchantStore: MerchantStoreService,
        private message: NzMessageService, // 信息提示
        private commonsService: CommonsService,
        private activatedRoute: ActivatedRoute,
    ) {
    }
    ngOnInit(): void {
        this.activatedRoute.queryParams.subscribe(queryParams => {
            if (queryParams.storeId != null) {
                this.editFlag = true;
                this.id = queryParams.storeId;
                this.getDetails(queryParams.storeId);
            } else {
                this.getMap();
            }
        });
        this.validateForm = this.fb.group({
            storeName: [null, [Validators.required]],
            address: [null, [Validators.required]],
            contactName: [null, [Validators.required]],
            prestoreType: [null, [Validators.required]],
            telephone: [null, [Validators.required]],
            latitude: [29.553134, [Validators.required]],
            longitude: [106.565428, [Validators.required]],
            deviceSn: [null],
            deviceKey: [null],
            deviceName: [null],
            regionId: [null],
            brandId: [null],
            type: [null],
        });

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

    }

    // 图片查看
    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;
    }

    // 返回
    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.logoFile.length !== 0) {
            if (this.logoFile[0]['response'] != null) {
                this.validateForm.value.storeLogo = this.logoFile[0]['response']['return_data'][0];
            } else {
                this.validateForm.value.storeLogo = this.logoFile[0].name;
            }
        }
        if (this.editFlag) {
            this.validateForm.value.id = this.id;
            this.merchantStore.updateMerchantStore(this.validateForm.value, data => {
                if (data['return_code'] === '000000') {
                    this.getBack();
                    this.message.success('修改成功');
                } else {
                    this.message.create('error', '修改失败');
                }
            });
        } else {

            this.merchantStore.insertMerchantStore(this.validateForm.value, data => {
                if (data['return_code'] === '000000') {
                    this.getBack();
                    this.message.success('添加成功');
                } else {
                    this.message.create('error', '保存失败');
                }
            });
        }
    }

    public getDetails(id) {
        this.merchantStore.getMerchantStoreById(id, data => {
            if (data['return_code'] === '000000') {
                console.log(data);
                data['return_data']['brandId'] = String(data['return_data']['brandId']);
                data['return_data']['type'] = String(data['return_data']['type']);
                data['return_data']['prestoreType'] = String(data['return_data']['prestoreType']);
                if (data['return_data']['storeLogo'] != null && data['return_data']['storeLogo'] !== '') {
                    const logo = String(data['return_data']['storeLogo']);
                    const logoArray = [];
                    logoArray.push(
                        {
                            uid: 1,
                            name: logo,
                            status: 'done',
                            url: environment.imageUrl + logo
                        });
                    this.logoFile = logoArray;
                }
                this.validateForm.patchValue(data['return_data']);
                this.getMap();
            } else {
                this.message.create('error', data['return_msg']);
            }
        });
    }

    // 地图要放到函数里。
    getMap() {
        // tslint:disable-next-line:variable-name
        AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
            const map = new AMap.Map('container', {
                resizeEnable: true,
                scrollWheel: false,
                center: [this.validateForm.value.longitude, this.validateForm.value.latitude], // 初始化中心点坐标
                zoom: 13,
            });
            AMap.plugin(['AMap.ToolBar', 'AMap.Autocomplete'], () => {
                const toolbar = new AMap.ToolBar();
                map.addControl(toolbar);
            });
            const autoOptions = {
                // input 为绑定输入提示功能的input的DOM ID
                input: 'input'
            };
            const autoComplete = new AMap.Autocomplete(autoOptions);
            const placeSearch = new AMap.PlaceSearch({
                map: map
            });  // 构造地点查询类
            AMap.event.addListener(autoComplete, 'select', select); // 注册监听，当选中某条记录时会触发
            function select(e) {
                placeSearch.setCity(e.poi.adcode);
                placeSearch.search(e.poi.name);  // 关键字查询查询
            }

            const positionPicker = new PositionPicker({
                mode: 'dragMap',
                map: map
            });
            positionPicker.on('success', positionResult => {
                console.log(positionResult);
                positionResult['latitude'] = positionResult.position.lat;
                positionResult['longitude'] = positionResult.position.lng;
                positionResult['regionId'] = positionResult.regeocode.addressComponent.adcode;
                this.validateForm.patchValue(positionResult);
            });
            positionPicker.on('fail', positionResult => {
                console.log(positionResult);
            });
            positionPicker.setMode('dragMap');
            positionPicker.start();
            map.panBy(0, 1);

            map.addControl(new AMap.ToolBar({
                liteStyle: true
            }));
        });
    }

}
