import { Component, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { DatePipe } from '@angular/common';
import * as moment from 'moment';

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

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

    /**
     * 时间编辑器格式
     *
     * @type {string}
     * @memberof AppDateTime
     */
    @Input()
    datefmt: string;

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

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

    /**
     * Creates an instance of AppDateTime.
     * 创建 AppDateTime 实例
     * 
     * @param {DatePipe} datePipe
     * @memberof AppDateTime
     */
    constructor(private datePipe: DatePipe) { }

    /**
     * 数据发生改变
     *
     * @param {*} val
     * @memberof AppDateTime
    */
    public onValueChange(val): void {
        if (this.datefmt.indexOf('YYYY') > 0 || this.datefmt.indexOf('MM') > 0 || this.datefmt.indexOf('DD') > 0) {
            this.value = this.datePipe.transform(val, this.datefmt.replace('YYYY', 'yyyy').replace('DD', 'dd'));
        } else {
            this.value = moment(val).format(this.datefmt);
        }
        this.onChange(this.value);
    }

    /**
    * 输入
    *
    * @param {*} obj
    * @memberof AppDateTime
    */
    public writeValue(obj: any): void {
        this.value = obj;
    }

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

}