import { Component, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { ModalController } from '@ionic/angular';
import { AppNotification } from '../../service/Notification';

@Component({
    selector: 'app-mpicker',
    templateUrl: './app-mpicker.html',
    styleUrls: ['./app-mpicker.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => AppMPicker),
            multi: true
        }
    ]
})
export class AppMPicker implements ControlValueAccessor {
    /**
     * 表单
     *
     * @type {*}
     * @memberof AppPicker
     */
    @Input()
    form: any;
    /**
     * 选择视图
     *
     * @type {*}
     * @memberof AppPicker
     */
    @Input()
    component: any;
    /**
     * 是否启用
     *
     * @type {boolean}
     * @memberof AppPicker
     */
    @Input()
    disabled: boolean;
    /**
     * 提示信息
     *
     * @type {string}
     * @memberof AppPicker
     */
    @Input()
    placeholder: string;
    /**
     * 标签文本
     *
     * @type {string}
     * @memberof IBizMPicker
     */
    @Input()
    labelText: string;
    /**
     * 是否必填
     *
     * @type {boolean}
     * @memberof IBizTextarea
     */
    @Input()
    allowEmpty: boolean;
    /**
     * 值
     *
     * @type {any[]}
     * @memberof IBizMPicker
     */
    public values: any[] = [];

    /**
     * Creates an instance of AppPicker.
     * @param {ModalController} modalCtrl
     * @memberof AppPicker
     */
    constructor(private modalCtrl: ModalController, private notification: AppNotification) { }

    /**
     * 打开选择视图
     *
     * @returns {Promise<any>}
     * @memberof AppPicker
     */
    public async openMPicker(): Promise<any> {
        if (this.component) {
            if (!this.form) {
                return;
            }
            const modal = await this.modalCtrl.create({
                component: this.component,
                componentProps: { isModalMode: true, srfReferData: this.form, oldSelected: this.values }
            });
            await modal.present();
            const result = await modal.onWillDismiss();
            const res: any = result.data;
            if (res && Object.is(res.ret, 'OK') && res.selected) {
                if (res.selected.length > 0) {
                    const items: any[] = res.selected;
                    this.onChange(JSON.stringify(items));
                    this.values = items;
                } else {
                    this.onChange(undefined);
                    this.values = [];
                }
            }
        } else {
            this.notification.error('未指定选择视图');
        }
    }

    /**
     * 删除
     *
     * @param {number} index
     * @memberof IBizMPicker
     */
    public removeItem(index: number): void {
        if (this.disabled) {
            return;
        }
        this.values.splice(index, 1);
        this.onChange(JSON.stringify(this.values));
    }

    /**
     * 输入
     *
     * @param {string[]} val
     * @memberof AppPicker
     */
    public writeValue(val: string[]): void {
        if (val) {
            if (val instanceof Array) {
                this.values = val;
            } else if (typeof(val) === 'string') {
                try {
                    this.values = JSON.parse(val);
                } catch (error) {
                    console.error(error);
                }
            }
        }else{
            this.values =[];
        }
    }

    private onChange: (val: any) => void = () => { };
    private onTouched: () => void = () => { };
    public registerOnChange(fn: any): void { this.onChange = fn; }
    public registerOnTouched(fn: any): void { this.onTouched = fn; }

}