'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var normalizeComponent = require('./normalize-component-6fa50395.js');
var ThemeMixin = require('./ThemeMixin-a2f817cd.js');
require('./svg-atom-d2541b7d.js');
require('./icon-atom-65241b51.js');
require('./hover-atom-17a12a07.js');
require('./tooltip-atom-8f536df5.js');
var inputAtom = require('./input-atom-9431266a.js');
var errorAtom = require('./error-atom-2f5dc7b9.js');
var dayjs = _interopDefault(require('dayjs'));
var chunk = _interopDefault(require('lodash.chunk'));
var VSvgIcon = require('./VSvgIcon.js');
var closeByKeyAtom = require('./close-by-key-atom-6ca8a461.js');
var outsideClickAtom = require('./outside-click-atom-166b80f4.js');
var labelMolecule = require('./label-molecule-9793dd9f.js');

/**
 * @param {Dayjs} [target]
 * @property {number|string} [params.year]
 * @property {number|string} [params.month]
 * @returns {Array<CalendarDay[]>}
 */

var getFullCalendarMonth = function getFullCalendarMonth(target) {
  var days = [];
  var now = dayjs();
  var targetDate = target || dayjs();
  var targetMonth = targetDate.month();
  var startDay = targetDate.startOf('week');
  var endDay = targetDate.endOf('month').endOf('week');
  var currentDay = startDay.clone();

  while (!currentDay.isAfter(endDay)) {
    days.push(currentDay);
    currentDay = currentDay.add(1, 'day');
  }

  var formattedDays = days.map(function (day) {
    return {
      origin: day,
      date: day.toDate(),
      formatted: day.format(),
      inTargetMonth: day.month() === targetMonth,
      isToday: day.date() === now.date() && day.month() === now.month() && day.year() === now.year()
    };
  });
  return chunk(formattedDays, 7);
};

var MIN_DATE = '1940-01-01';
var MAX_DATE = '2100-01-01';
var script = {
  name: 'VDateInput',
  props: {
    value: {
      type: [String, Date],
      default: ''
    },
    minDate: {
      type: [String, Date],
      default: MIN_DATE
    },
    maxDate: {
      type: [String, Date],
      default: MAX_DATE
    },
    label: {
      type: String,
      default: ''
    },
    tooltipLabel: {
      type: String,
      default: ''
    },
    error: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data: function data() {
    return {
      innerMonth: null,
      innerYear: null,
      isCalendarVisible: false
    };
  },
  computed: {
    vDateInputCssClass: function vDateInputCssClass() {
      return ThemeMixin._objectSpread2(ThemeMixin._objectSpread2({}, this.themeCssClass), {}, {
        'v-date-input': true
      });
    },
    minYear: function minYear() {
      return dayjs(this.minDate).year();
    },
    maxYear: function maxYear() {
      return dayjs(this.maxDate).year();
    },
    isError: function isError() {
      return !!this.error;
    },
    date: function date() {
      if (!this.value) return null;
      return dayjs(this.value);
    },
    formattedInnerMonth: function formattedInnerMonth() {
      return dayjs().month(this.innerMonth).format('MMMM');
    },
    currentCalendar: function currentCalendar() {
      if (!this.isCalendarVisible) return [];
      var calendarNativeDate = new Date(this.innerYear, this.innerMonth);
      var calendarDate = dayjs(calendarNativeDate);
      return getFullCalendarMonth(calendarDate);
    },
    formattedValue: function formattedValue() {
      if (!this.date) return '';
      return this.date.format('YYYY/MM/DD');
    }
  },
  watch: {
    value: function value(val, oldVal) {
      if (!val) {
        this.setDefaultInnerDate();
        return;
      }

      var oldDate = dayjs(oldVal);
      var newDate = dayjs(val);
      var newDateMonth = newDate.month();
      var newDateYear = newDate.year();

      if (newDateMonth !== oldDate.month() || newDateYear !== oldDate.year()) {
        this.innerMonth = newDateMonth;
        this.innerYear = newDateYear;
      }
    }
  },
  methods: {
    setDefaultInnerDate: function setDefaultInnerDate() {
      var now = new Date();
      this.innerYear = now.getFullYear();
      this.innerMonth = now.getMonth();
    },
    isDayInRange: function isDayInRange(date) {
      var currentDate = dayjs(date);
      return currentDate.isAfter(this.minDate) && currentDate.isBefore(this.maxDate);
    },
    isSelectedDay: function isSelectedDay(_ref) {
      var origin = _ref.origin;
      if (!this.date) return false;
      return this.date.date() === origin.date() && this.date.month() === origin.month() && this.date.year() === origin.year();
    },
    isClickInside: function isClickInside(target, currentNode) {
      while (currentNode) {
        // eslint-disable-next-line no-param-reassign
        currentNode = currentNode.parentNode;

        if (target === currentNode) {
          return true;
        }

        if (!currentNode) {
          break;
        }
      }

      return false;
    },
    onBlurInput: function onBlurInput(e) {
      if (this.isClickInside(this.$refs.root, e.relatedTarget)) {
        return;
      }

      this.handleSubmit(e);
    },
    handleSubmit: function handleSubmit(e) {
      var valueDate = dayjs(e.target.value);

      if (valueDate.isValid()) {
        this.handleChange(valueDate.toDate());
        this.hideCalendar();
      }
    },
    onFocusInput: function onFocusInput() {
      this.isCalendarVisible = true;
    },
    hideCalendar: function hideCalendar() {
      this.isCalendarVisible = false;
    },
    onClickPreviousMonth: function onClickPreviousMonth() {
      if (this.innerMonth === 0) {
        this.innerMonth = 11;
        this.innerYear -= 1;
      } else {
        this.innerMonth -= 1;
      }
    },
    onClickNextMonth: function onClickNextMonth() {
      if (this.innerMonth === 11) {
        this.innerMonth = 0;
        this.innerYear += 1;
      } else {
        this.innerMonth += 1;
      }
    },
    handleChange: function handleChange(newValue) {
      if (!this.isDayInRange(dayjs(newValue))) {
        return;
      }

      var oldTime = dayjs(this.value).toDate().getTime();

      if (oldTime !== newValue.getTime()) {
        this.$emit('change', newValue);
      }
    },
    onClickDay: function onClickDay(_ref2) {
      var origin = _ref2.origin;
      var newDate = origin.toDate();
      this.handleChange(newDate);
      this.hideCalendar();
    },
    onCalendarCloseByESC: function onCalendarCloseByESC() {
      this.hideCalendar();
    },
    onClickOutside: function onClickOutside() {
      this.hideCalendar();
    }
  },
  mounted: function mounted() {
    if (!this.date) {
      this.setDefaultInnerDate();
    } else {
      this.innerYear = this.date.year();
      this.innerMonth = this.date.month();
    }
  },
  mixins: [ThemeMixin.ThemeMixin],
  components: {
    LabelMolecule: labelMolecule.LabelMolecule,
    VSvgIcon: VSvgIcon.default,
    InputAtom: inputAtom.InputAtom,
    ErrorAtom: errorAtom.ErrorAtom,
    CloseByKeyAtom: closeByKeyAtom.CloseByKeyAtom,
    OutsideClickAtom: outsideClickAtom.OutsideClickAtom
  },
  model: {
    event: 'change',
    prop: 'value'
  }
};

/* script */
const __vue_script__ = script;

/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('outside-click-atom',{on:{"click":_vm.onClickOutside}},[_c('div',{ref:"root",class:_vm.vDateInputCssClass},[_c('div',{staticClass:"v-date-input-field"},[(_vm.label)?_c('label-molecule',{attrs:{"label":_vm.label,"tooltip-label":_vm.tooltipLabel,"disabled":_vm.disabled}}):_vm._e(),_vm._v(" "),_c('div',{staticClass:"v-date-input-field-inner"},[_c('input-atom',_vm._b({attrs:{"disabled":_vm.disabled,"value":_vm.formattedValue,"is-error":_vm.isError},on:{"focus":_vm.onFocusInput,"blur":_vm.onBlurInput},nativeOn:{"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }return _vm.handleSubmit($event)}}},'input-atom',_vm.$attrs,false)),_vm._v(" "),_c('div',{staticClass:"v-date-input-field-icon"},[_c('v-svg-icon',{attrs:{"name":"calendar"}})],1)],1),_vm._v(" "),(_vm.isError)?_c('error-atom',{attrs:{"error":_vm.error}}):_vm._e()],1),_vm._v(" "),(_vm.isCalendarVisible)?_c('div',{staticClass:"v-date-input-calendar",attrs:{"tabindex":"-1"}},[_c('close-by-key-atom',{on:{"close":_vm.onCalendarCloseByESC}},[_c('section',{staticClass:"v-date-input-controls"},[_c('button',{staticClass:"v-date-input-control",attrs:{"type":"button"},on:{"click":_vm.onClickPreviousMonth}},[_c('v-svg-icon',{attrs:{"name":"chevron-left"}})],1),_vm._v(" "),_c('div',{staticClass:"v-date-input-now"},[_c('span',[_vm._v("\n              "+_vm._s(_vm.formattedInnerMonth)+"\n            ")]),_vm._v(" "),_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.innerYear),expression:"innerYear"}],attrs:{"min":_vm.minYear,"max":_vm.maxYear,"type":"number"},domProps:{"value":(_vm.innerYear)},on:{"input":function($event){if($event.target.composing){ return; }_vm.innerYear=$event.target.value;}}})]),_vm._v(" "),_c('button',{staticClass:"v-date-input-control",attrs:{"type":"button"},on:{"click":_vm.onClickNextMonth}},[_c('v-svg-icon',{attrs:{"name":"chevron-right"}})],1)]),_vm._v(" "),_c('table',{staticClass:"v-date-input-dates"},[_c('tr',[_c('td',{staticClass:"v-date-input-day"},[_vm._v("\n              S\n            ")]),_vm._v(" "),_c('td',{staticClass:"v-date-input-day"},[_vm._v("\n              M\n            ")]),_vm._v(" "),_c('td',{staticClass:"v-date-input-day"},[_vm._v("\n              T\n            ")]),_vm._v(" "),_c('td',{staticClass:"v-date-input-day"},[_vm._v("\n              W\n            ")]),_vm._v(" "),_c('td',{staticClass:"v-date-input-day"},[_vm._v("\n              T\n            ")]),_vm._v(" "),_c('td',{staticClass:"v-date-input-day"},[_vm._v("\n              F\n            ")]),_vm._v(" "),_c('td',{staticClass:"v-date-input-day"},[_vm._v("\n              S\n            ")])]),_vm._v(" "),_vm._l((_vm.currentCalendar),function(week,i){return _c('tr',{key:(_vm.innerYear + "-" + i)},_vm._l((week),function(day){return _c('td',{key:day.date.toString()},[_c('button',{class:{
                  'v-date-input-day': true,
                  'v-date-input-control': true,
                  'is-today': day.isToday,
                  'is-not-mine-month': !day.inTargetMonth,
                  'is-selected': _vm.isSelectedDay(day),
                },attrs:{"disabled":!_vm.isDayInRange(day.origin),"type":"button"},on:{"click":function($event){return _vm.onClickDay(day)}}},[_vm._v("\n                "+_vm._s(day.origin.date())+"\n              ")])])}),0)})],2)])],1):_vm._e()])])};
var __vue_staticRenderFns__ = [];

  /* style */
  const __vue_inject_styles__ = undefined;
  /* scoped */
  const __vue_scope_id__ = undefined;
  /* module identifier */
  const __vue_module_identifier__ = undefined;
  /* functional template */
  const __vue_is_functional_template__ = false;
  /* style inject */
  
  /* style inject SSR */
  

  
  var VDateInput = normalizeComponent.__vue_normalize__(
    { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
    __vue_inject_styles__,
    __vue_script__,
    __vue_scope_id__,
    __vue_is_functional_template__,
    __vue_module_identifier__,
    undefined,
    undefined
  );

exports.default = VDateInput;
