import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'app-date-picker',
    templateUrl: './app-date-picker.html',
    styleUrls: ['./app-date-picker.less']
})
export class AppDatePicker implements OnInit {

    /**
     * 值项
     *
     * @memberof AppDatePicker
     */
    @Input() public value: any;

    /**
     * 提示语
     *
     * @type {string}
     * @memberof AppDatePicker
     */
    @Input() public placeholder: string = '请选择';

    /**
     * 是否禁用
     *
     * @type {boolean}
     * @memberof AppDatePicker
     */
    @Input() public disabled: boolean;

    /**
     * 宽度
     *
     * @type {*}
     * @memberof AppDatePicker
     */
    @Input() public width: any;

    /**
     * 值格式
     *
     * @type {string}
     * @memberof AppDatePicker
     */
    @Input()
    set format(val: string) {
        this.valFormat = val;
        if (this.valFormat.indexOf('HH') > 0) {
            this.isShowTime = true;
        }
    }

    /**
     * 显示值格式
     *
     * @type {string}
     * @memberof AppDatePicker
     */
    public valFormat: string = 'yyyy-MM-dd';

    /**
     * 是否可选择时间
     *
     * @type {boolean}
     * @memberof AppDatePicker
     */
    public isShowTime: boolean = false;

    /**
     * 表单项之变化事件
     *
     * @memberof AppDatePicker
     */
    @Output() public onFormItemValueChange: EventEmitter<any> = new EventEmitter<any>();

    /**
     * 生命周期
     *
     * @memberof AppDatePicker
     */
    public ngOnInit(): void {

    }

    /**
     * 值变化
     *
     * @param {*} $event
     * @memberof AppDatePicker
     */
    public onValueChange($event: any) {
        let val = this.formatValue($event);
        this.onFormItemValueChange.emit(val);
    }

    /**
     * 处理值
     *
     * @param {Date} date
     * @memberof AppDatePicker
     */
    public formatValue(date: Date) {
        if (!date) {
            return null;
        }
        let data: string = this.valFormat;
        let obj: any = {
            yyyy: date.getFullYear(),
            MM: this.AppendVal(date.getMonth() + 1),
            dd: this.AppendVal(date.getDate()),
            HH: this.AppendVal(date.getHours()),
            mm: this.AppendVal(date.getMinutes()),
            ss: this.AppendVal(date.getSeconds())
        };
        let keys = Object.keys(obj);
        keys.forEach(key => {
            let val = obj[key];
            data = data.replace(key, val);
        });
        return data;
    }

    /**
     * 值追加
     *
     * @param {number} val
     * @returns
     * @memberof AppDatePicker
     */
    public AppendVal(val: number) {
        return (val < 10 ? '0' + val : val);
    }
}
