<template>
  <div>
    <div class="co-datebar-title">
      <span class="co-datebar-ym" @click="open('picker')">{{currentYM}}</span>
      <!-- <i class="coicon coicon-"></i> -->
    </div>
    <div class="content-block" style="margin: 0;padding: 0;overflow-y: scroll; width: 100vw" ref="wrapper">
      <ul class="co-component-progressbar" style="height: 90px;margin: 0;padding: 0;" :style="{width: 'calc(100vw / 7 * ' + rows.length +')'}">
        <li class="co-datebar-datedata" :class="[row.cls, row.active]" day="" state="true" v-for="row in rows" @click="clickFn(row, $event)">
          <span class="co-datebar-week">{{row.week}}</span>
          <span class="co-datebar-data">{{row.data}}</span>
        </li>
      </ul>
    </div>
    <co-datetime-picker
        ref="picker"
        type="yearmonth"
        v-model="pickerValue"
        :year-format="yearFormat"
        :month-format="monthFormat"
        @confirm="handleChange"
    >
    </co-datetime-picker>
  </div>
</template>

<script>
import datetime from 'CoUI/packages/datetime-picker/index';
if (process.env.NODE_ENV === 'component') {
  require('CoUI/packages/cell/style.css');
}

/**
 * co-datebar
 * @module components/datebar
 * @desc 头部日历
 * @param {string} value - 绑定值
 * @param {string} [cancel-text=取消] - 取消按钮文字
 * @param {string} [placeholder=取消] - 搜索框占位内容
 * @param {boolean} [autofocus=false] - 自动 focus
 * @param {boolean} [show=false] - 始终显示列表
 * @param {string[]} [result] - 结果列表
 * @param {slot} 结果列表
 *
 */
var sDate = window.Date;
var _Tdate;
export default {
  name: 'co-datebar',

  props: {
    yearMonth: String,
    day: String,
    yearFormat: {
      type: String,
      default: '{value} 年'
    },
    monthFormat: {
      type: String,
      default: '{value} 月'
    }
  },

  data() {
    return {
      rows: [],
      currentYM: this.yearMonth || new Date().getFullYear() + '-' + ('0' + (new Date().getMonth() + 1)).slice(-2),
      pickerValue: new Date()
    };
  },

  components: {
    'co-datetime-picker': datetime
  },

  methods: {
    init(args) {
      var _date = new Date();
      _Tdate = _date.getFullYear() + '-' + (_date.getMonth() + 1) + '-' + _date.getDate();// 获取当前日期
      var _TMonth = _date.getFullYear() + '-' + (_date.getMonth() + 1);// 获取当前月份;
      var componentData = args.componentData || {};
      var yearMonth = componentData.yearMonth || _TMonth;
      var beginData = componentData.beginData ? componentData.beginData : _Tdate;
      var endData = componentData.endData ? componentData.endData : (new Date(sDate.parse(beginData) + (86400000 * 60)));
      var ym = componentData.yearMonth || _date.getFullYear() + '-' + (_date.getMonth() + 1);
      var componentDay = componentData.day ? ym + '-' + componentData.day : '';// 获取选择的几号
      var selectDay = componentDay || '';
      var arrData = [];
      var i = 0;
      var defaultData = selectDay ? selectDay : _Tdate;// 如果不设置默认则选中的中当天

      // 设置一个月份格式YYYY-M (beginData和endData必须不存在的时候才生效)
      if (!componentData.beginData && !componentData.endData) {
        var _yearMonth = yearMonth.split('-');
        var _yDate = new Date();
        _yDate.setFullYear(_yearMonth[0], _yearMonth[1], '0');
        var yearMonthDate = _yDate.getDate();
        yearMonth = yearMonth.replace('-', '/');
        beginData = (yearMonth + '/' + 1);
        endData = (yearMonth + '/' + yearMonthDate);
      }
      var newBeginData = new Date(beginData);// 开始时间
      var newEndData = new Date(endData);// 结束时间
      var newTime = newEndData.getTime() - newBeginData.getTime();// 时间差的毫秒数
      var days = Math.floor(newTime / (24 * 3600 * 1000));// //计算出相差天数
      days = days > 61 ? 60 : days;// 时间跨度必须小于或者等于两个月

      function dateAdd(NumDay, dtDate) {
        var dtTmp = new Date(dtDate);
        var d;
        var _newData;
        var _arr = {};
        var x;
        if (isNaN(dtTmp)) {
          dtTmp = new Date();
        }
        _newData = new Date(sDate.parse(dtTmp) + (86400000 * NumDay));
        d = new Date(_newData);
        var xq = ['日', '一', '二', '三', '四', '五', '六'];
        x = xq[d.getDay()];
        _arr = {
          y: d.getFullYear(),
          m: d.getMonth() + 1,
          d: d.getDate(),
          w: x
        };
        return _arr;
      }
      var reg = new RegExp('-', 'g'); // 创建正则RegExp对象
      var bedate = _Tdate.replace(reg, '/');
      var afData = defaultData.replace(reg, '/');
      for (; i <= days ; i++) {
        var _data = dateAdd(i, beginData);
        var _y_m = _data.y + '/' + _data.m;
        var _w = _data.w;
        var _d = _data.d;
        var beforeData = (new Date(_y_m + '/' + _data.d)) >= (new Date(bedate));
        var afterData = ((_y_m + '/' + _data.d) === (afData));
        var cls = beforeData ? '' : 'Clsexpired';

        var active = (afterData) ? 'active' : '';
        arrData.push({
          year: _y_m,
          week: _w,
          data: _d,
          cls: cls,
          active: active
        });
      }
      return arrData;
    },
    repos() {
      this.$nextTick(() => {
        var $container = this.$refs.wrapper;
        var $item = $container.childNodes[0].childNodes[0];
        // 刷新组件选中位置
        if (this.day) {
          var getday = this.day - 3;
          $container.scrollLeft = getday * $item.scrollWidth;
        } else {
          var todays = _Tdate.split('-');
          var seldays = _Tdate.split('-');
          if (seldays.length === 1 || seldays[1] === todays[1]) $container.scrollLeft = (todays[2] - 4) * $item.scrollWidth;
        }
      });
    },
    reset: function() {// 清除选中样式
      var _data = this.rows;
      for (var i in _data) {
        _data[i].active = '';
      }
    },
    clickFn: function($this) {
      this.reset();
      $this.active = 'active';// 添加选中样式
      this.$emit('click', {$this});
    },
    open(picker) {
      this.$refs[picker].open();
    },
    // 切换月份
    handleChange(value) {
      let yearMonth = value.getFullYear() + '-' + (value.getMonth() + 1);
      this.currentYM = value.getFullYear() + '-' + ('0' + (value.getMonth() + 1)).slice(-2);
      this.$emit('changeYM', this.currentYM);
      console.log(this.day);
      this.rows = this.init({// 刷新组件日期
        componentData: {
          yearMonth: yearMonth,
          day: this.day
        }
      });
      this.repos();// 定位到当天
    }
  },

  mounted() {
    this.rows = this.init({
      componentData: {
        yearMonth: this.yearMonth,
        day: this.day
      }
    });
    var _yDate = new Date();
    if (this.yearMonth) {
      var _yearMonth = this.yearMonth.split('-');
      _yDate.setFullYear(_yearMonth[0], _yearMonth[1], '0');
    }
    this.pickerValue = _yDate;
    this.repos();// 定位到当天
  }
};

</script>

<style lang="css">
  @import "../../../src/style/var-ios9.css";
  ::-webkit-scrollbar {
      height: 0px;
      min-height: 0;
      width: 2px;
      min-width: 2px;
  }
  .co-datebar-title{
    position: relative;
    height: 1.5rem;
    line-height: 1.5rem;
    color: #4A4A4A;
    font-size: 12px;
    padding-left: 0.5rem;
  }
  .co-datebar-ym{
    display: inline-block;
    width: 3.4rem;
  }
  .co-datebar-ym:before{
    position: absolute;
    left: 3.5rem;
    top: -5px;
    bottom: 0;
    margin: auto;
    content: '';
    display: block;
    width: 0.35rem;
    height: 0.35rem;
    background: linear-gradient(45deg, transparent 46%, #9B9B9B 0);
    -webkit-transform: rotate(135deg);
    transform: rotate(135deg);
    -webkit-transition: transform .2s ease-in-out;
    transition: transform .2s ease-in-out;
  }
  .co-datebar-datedata {
      float: left;
      height: 86px;
      /* width: 64px; */
      width: calc(100vw / 7);
      /* border-left: 1px solid #C8C8C8; */
      text-align: center;
      font-size: 12px;
      color: #777;
      background: #fff;
      list-style-type: none;
  }
  .co-datebar-year, .co-datebar-week {
      display: block;
      height: 30px;
      line-height: 30px;
      text-align: center;
      color: #9B9B9B;
      border-left: 1px solid #fff;
  }
  .co-datebar-data {
      display: block;
      width: 100%;
      height: 56px;
      line-height: 56px;
      border-top: 1px solid #ddd;
      border-left: 1px solid #f1f1f1;
      font: 18px/56px '微软雅黑';
      color: #000;
  }
  .co-datebar-datedata:first-child .co-datebar-data, .co-datebar-datedata:first-child .co-datebar-week{
      border-left: none;
  }
  /* 过期时间 */
  .co-datebar-datedata.Clsexpired .co-datebar-data {
      color: #9e9e9e;
  }
  .co-datebar-datedata.active .co-datebar-data {
      color: #fff;
      background: radial-gradient(circle, $color-blue 38%, white 39%);
  }
</style>
