import { Component, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Component({
    selector: 'app-toggle',
    templateUrl: './app-toggle.html',
    styleUrls: ['./app-toggle.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => AppToggle),
            multi: true
        }
    ]
})
export class AppToggle implements ControlValueAccessor {

    /**
     * 编辑器值
     *
     * @type {string}
     * @memberof AppToggle
     */
    public value: any;

    /**
     * 是否启用
     *
     * @type {boolean}
     * @memberof AppToggle
     */
    @Input()
    disabled: boolean;

    /**
     * 提示信息
     *
     * @type {string}
     * @memberof AppToggle
     */
    @Input()
    placeholder: string;

    /**
     * 数据发生改变
     *
     * @param {*} detail
     * @memberof AppToggle
    */
    public onValueChange({ detail }): void {
        if (detail && detail.checked !== this.value) {
            if(detail.checked){
                if(this.value === 1){
                    return ;
                }
                this.value = 1;
            }else{
                if(this.value === 0){
                    return ;
                }
                this.value = 0;
            }
            this.onChange(this.value + '');
        }
    }

    /**
     * 输入
     *
     * @param {*} obj
     * @memberof AppToggle
    */
    public writeValue(obj: any): void {
        if (obj && !Object.is(obj, '')) {
            if (Object.is(obj, 1) || Object.is(obj, "1")) {
               setTimeout(() => {
                this.value = 1;
               }, 0);
            } else {
                this.value = 0;
            }
        }
    }

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

}