<?php

/*
 * The MIT License
 *
 * Copyright 2019 Blobt.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

namespace blobt\widgets;

use yii\widgets\InputWidget;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\web\JsExpression;
use yii\helpers\Json;
use blobt\web\DatetimepickBootstrapAsset;
use blobt\helpers\DatetimeHelper;

/**
 * 这是一个Bootstrap的DatetimePicker 参考https://www.malot.fr/bootstrap-datetimepicker/
 * 
 * @author Blobt
 * @email 380255922@qq.com
 * @created Aug 21, 2019
 */
class DatetimePicker extends InputWidget {

    /**
     * @var string 时间日期显示格式
     */
    public $format = "Y-m-d h:i";

    /**
     * @var string datetimepicker的日期显示input框的id,只用做显示
     */
    public $pickerInputId;

    /**
     * @var boll 是否自动填充当天日期
     */
    public $autoFill = false;

    /**
     * @inheritdoc
     * @throws InvalidConfigException
     * @throws \ReflectionException
     */
    public function run() {
        $this->initSetting();
        echo $this->renderHiddenInput();
        echo $this->renderDatetimePickerInput();
        $this->registerAsset();
    }

    /**
     * 初始化小物件的配置
     */
    protected function initSetting() {
        //初始化日期格式
        if (empty($this->format)) {
            $this->format = Yii::$app->formatter->dateFormat;
        }

        //关闭自动完成
        $this->options["autocomplete"] = "off";

        //生成一个picker input的 id
        $this->pickerInputId = $this->options['id'] . "_" . Yii::$app->security->generateRandomString(4);
    }

    /**
     * 注册js和css
     */
    protected function registerAsset() {
        $view = $this->getView();
        DatetimepickBootstrapAsset::register($view);

        $options = [
            "format" => $this->convertDateFormat($this->format),
            "language" => "zh-CN"
        ];
        $jsOptions = Json::encode($options);


        $js = <<< SCRIPT
            $('#{$this->pickerInputId}').datetimepicker({$jsOptions}).on('changeDate', function(e) {
            $('#{$this->options['id']}').val(String(e.date.getTime()).substring(0,10));
        });;
SCRIPT;
        $view->registerJs($js);
    }

    /**
     * 渲染一个用作保存Datepicker Unix时间错的hidden input
     * @return string
     */
    protected function renderHiddenInput() {
        if ($this->hasModel()) {
            return Html::activeInput('hidden', $this->model, $this->attribute, $this->options);
        }
        return Html::input('hidden', $this->name, $this->value, $this->options);
    }

    /**
     * TODO:自动填充了今天为默认日期
     * 渲染一个用作显示日期的字符格式 text input
     * @return string
     */
    protected function renderDatetimepickerInput() {
        $value = '';
        $options = $this->options;
        $options['id'] = $this->pickerInputId;

        if ($this->hasModel()) {
            $timestamp = ArrayHelper::getValue($this->model, $this->attribute);
            if (!empty($timestamp)) {
                $value = date($this->format, $timestamp);
            }
        }

        if (empty($timestamp) && $this->autoFill) {
            $timestamp = time();
            $value = date($this->format, $timestamp);
        }

        return Html::input('text', $this->name, $value, $options);
    }

    /**
     * 转换php日期格式为bootstrap日期格式
     * 
     * TODO:没有弄清所有格式的转换,后续添加
     * 
     * @param string $format PHP日期格式字符串
     * @return string
     */
    protected static function convertDateFormat($format) {
        $conversions = [
            'd' => 'dd',
            'm' => 'mm',
            'Y' => 'yyyy',
            'h' => 'hh',
            'i' => 'ii'
        ];
        return strtr($format, $conversions);
    }

}