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

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

    /**
     * 值项
     *
     * @memberof AppTimePicker
     */
    @Input()
    set value(val) {
        if (!val) {
            this.itemValue = null;
            return;
        }
        let data = 'HH:mm:ss';
        data = data.replace(this.format, val).replace('HH', '12').replace('mm', '32').replace('ss', '15');
        let date = '2019/09/01 ' + data;
        this.itemValue = new Date(date);
    }

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

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

    /**
     * 值格式
     *
     * @type {string}
     * @memberof AppTimePicker
     */
    @Input() public format: string = 'HH:mm:ss';

    /**
     * 值项
     *
     * @type {Date}
     * @memberof AppTimePicker
     */
    public itemValue: Date = null;

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

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

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

    }

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

    /**
     * 处理值
     *
     * @param {Date} date
     * @memberof AppTimePicker
     */
    public formatValue(date: Date) {
        if (!date) {
            return null;
        }
        let data: string = this.format;
        let obj: any = {
            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 AppTimePicker
     */
    public AppendVal(val: number) {
        return (val < 10 ? '0' + val : val);
    }
}
