import Dom from '../../libs/dom'
import Widget from '../widget'
import Calendar from '../../libs/calendar'
import util from '../../libs/util'

function formatDate(dateStr, fmt) {
  let now = new Date(dateStr)
  var o = {
    'M+': now.getMonth() + 1, //月份
    'd+': now.getDate() //日
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (now.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
  return fmt
}

class DatePicker extends Widget {
  constructor(layer, screen) {
    super(layer, screen)
    this.events = ['date'] // 事件
    this.container = Dom.createElement('div', 'date-container comp', this.el)
  }

  setPaint() {
    this.setListener()
    let newPaint = this._mergePaint()
    this.container.innerHTML = ''
    let calendarWrap = document.querySelector('.calendar-wrap')
    if (calendarWrap) {
      calendarWrap.remove()
    }
    Dom.css(this.container, {
      border: `${newPaint.borderWidth}px ${newPaint.borderType} ${newPaint.borderColor}`,
      borderRadius: `${newPaint.borderRadius[0]}px ${newPaint.borderRadius[1]}px ${newPaint.borderRadius[2]}px ${newPaint.borderRadius[3]}px`,
      color: newPaint.fontColor,
      fontSize: newPaint.fontSize + 'px'
    })
    let className = util.generateId()
    let dateTrigger = Dom.createElement('div', className, this.container)
    dateTrigger.textContent = formatDate(
      this.layer.events[this.events[0]].default,
      newPaint.format
    )
    new Calendar({
      classN: className,
      callBack: this._click.bind(this)
    })
    this.fire('render', this)
  }

  _click(bindElem, dateObj) {
    let newPaint = this._mergePaint()
    let currentValue =
      dateObj.year + '-' + dateObj.month + '-' + dateObj.date
    bindElem.textContent = formatDate(currentValue, newPaint.format)
    let events = this.layer.events // 绑定的事件
    this.events.forEach(eventName => {
      let alias =
        events && events[eventName] ? events[eventName].alias : eventName
      this._screen.store.patchState(alias, currentValue)
    })
  }
}

export default DatePicker
