<?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 blobt\helpers\DatetimeHelper;
use blobt\web\DaterangeBootstrapAsset;
use yii\helpers\Json;

/**
 * 
 * 
 * @author Blobt
 * @email 380255922@qq.com
 * @created Aug 13, 2019
 */
class DateRangePicker extends InputWidget {

    /**
     * @var boolean 是否需要把值做转义
     */
    public $encodeValue = true;

    /**
     * @var array input的html属性
     */
    public $options = [];

    /**
     * @var string label
     */
    public $label = "日期范围";

    /**
     * @var string 确定按钮显示内容
     */
    public $applyLabel = "确定";

    /**
     * @var string 关闭按钮显示内容
     */
    public $cancelLabel = "关闭";

    /**
     * @var string 自定义按钮显示内容
     */
    public $customRangeLabel = "自定义";

    /**
     * @var array 星期一到星期日的显示
     */
    public $daysOfWeek = ["日", "一", "二", "三", "四", "五", "六"];

    /**
     * @var array 12个月份的显示
     */
    public $monthNames = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"];

    /**
     * @var array 选择器的基础配置参数
     */
    protected $locale = [];

    /**
     * @var 快捷选择建
     */
    public $ranges = [];

    /**
     * @var string 选择器默认选中的开始日期
     */
    public $startDate;

    /**
     * @var string 选择器默认选中的结束日期
     */
    public $endDate;

    /**
     * @var string 左侧显示的图标
     */
    public $iconClass = "fa fa-calendar";

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

    /**
     * @var string 选择框打开的位置
     */
    public $opens = 'left';

    /**
     * @var bool 是否自动填入日期
     */
    public $autoFill = false;

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

        echo $this->renderInputHtml('text');
    }

    /**
     * @inheritdoc
     */
    public function init() {
        parent::init();
    }

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

        //初始化基础配置
        $this->locale = [
            'cancelLabel' => $this->cancelLabel,
            'applyLabel' => $this->applyLabel,
            "customRangeLabel" => $this->customRangeLabel,
            "daysOfWeek" => $this->daysOfWeek,
            "monthNames" => $this->monthNames,
            "format" => $this->format
        ];
        //初始化快捷键
        $this->initRange();

        //关闭自动提示
        $this->options = ArrayHelper::merge($this->options, [
                    "autocomplete" => "off",
                    "class" => "form-control",
                    "style" => "width:190px;"
        ]);
    }

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


        $options = [
            "opens" => $this->opens,
            "autoUpdateInput" => $this->autoFill,
            "locale" => $this->locale,
            "ranges" => $this->ranges
        ];

        if (!empty($this->startDate)) {
            $options["startDate"] = new JsExpression("moment('{$this->startDate}')");
        }
        if (!empty($this->endDate)) {
            $options["endDate"] = new JsExpression("moment('{$this->endDate}')");
        }


        $jsOptions = Json::encode($options);
        $js = <<< SCRIPT
        $('#{$this->options['id']}').daterangepicker({$jsOptions});
        $('#{$this->options['id']}').on('apply.daterangepicker', function(ev, picker) {
            $(this).val(picker.startDate.format('{$this->format}') + ' ~ ' + picker.endDate.format('{$this->format}'));
        });

        $('#{$this->options['id']}').on('cancel.daterangepicker', function(ev, picker) {
            $(this).val('');
        });
SCRIPT;
        $view->registerJs($js);
    }

    /**
     * 初始化快捷按键数组
     */
    protected function initRange() {
        $this->ranges = [
            '今天' => [new JsExpression("moment()"), new JsExpression("moment()")],
            '昨天' => [new JsExpression("moment().subtract(1, 'days')"), new JsExpression("moment().subtract(1, 'days')")],
            '最近7天' => [new JsExpression("moment().subtract(6, 'days')"), new JsExpression("moment()")],
            '最近30天' => [new JsExpression("moment().subtract(29, 'days')"), new JsExpression("moment()")],
            '本月' => [new JsExpression("moment().startOf('month')"), new JsExpression("moment().endOf('month')")],
            '上月' => [new JsExpression("moment().subtract(1, 'month').startOf('month')"), new JsExpression("moment().subtract(1, 'month').endOf('month')")]
        ];
    }

    /**
     * 转换php日期格式为Moment.js 日期格式
     * @param string $format PHP日期格式字符串
     * @return string
     */
    protected static function convertDateFormat($format) {
        $conversions = [
            // second (带有前导零)
            's' => 'ss',
            // minute (带有前导零)
            'i' => 'mm',
            // hour in 12-hour format (没带前导零)
            'g' => 'h',
            // hour in 12-hour format (带有前导零)
            'h' => 'hh',
            // hour in 24-hour format (没带前导零)
            'G' => 'H',
            // hour in 24-hour format (带有前导零)
            'H' => 'HH',
            //  day of the week locale
            'w' => 'e',
            //  day of the week ISO
            'W' => 'E',
            // day of month (没带前导零)
            'j' => 'D',
            // day of month (带有前导零)
            'd' => 'DD',
            // day name short
            'D' => 'DDD',
            // day name long
            'l' => 'DDDD',
            // month of year (没带前导零)
            'n' => 'M',
            // month of year (带有前导零)
            'm' => 'MM',
            // month name short
            'M' => 'MMM',
            // month name long
            'F' => 'MMMM',
            // year (2位年)
            'y' => 'YY',
            // year (4位年)
            'Y' => 'YYYY',
            // unix timestamp
            'U' => 'X',
        ];
        return strtr($format, $conversions);
    }

}