<template>
  <view class="card radius shadow-warp bg-white">
    <view
      @tap="$refs.calendar.open()"
      class="bg-white text-xl text-center padding solid-bottom text-black"
      hover-class="cc-active"
    >{{ date }}</view>
    <view class="menus-wrap">
      <button
        :class="[ menu === item ? 'bg-purple': 'line-gray' ]"
        :key="index"
        @tap="handleClickMenu(item)"
        class="cu-btn round"
        v-for="(item, index) in menus"
      >{{ item }}</button>
      <!-- <button class="cu-btn round lines-gray">{{item.title}}</button> -->
    </view>
    <uni-calendar
      :insert="false"
      :range="true"
      :show-month="true"
      @confirm="handleChange"
      ref="calendar"
    />
  </view>
</template>

<script>
const menus = ['昨天', '今天', '近7天', '近30天'];

export default {
  name: 'DateSelector',
  data() {
    const start = this.$moment().format('YYYY-MM-DD');
    const end = this.$moment().format('YYYY-MM-DD');
    return {
      start,
      end,
      menu: '今天',
      menus,
    };
  },

  computed: {
    date() {
      const { start, end } = this;
      return start === end ? start : `${start} - ${end}`;
    },
  },

  methods: {
    /**
     * 日历确认选择了时间段
     * @param {object} value 日历返回对象
     */
    handleChange(value) {
      const { before, after } = value.range;
      this.start = before;
      this.end = after;
      this.menu = '';
      this.$emit('change', before, after);
    },

    /**
     * 点选了快捷菜单
     * @param {string} menu 快捷时间菜单字符串
     */
    handleClickMenu(menu) {
      this.menu = menu;
      let start = this.$moment().format('YYYY-MM-DD');
      let end = this.$moment().format('YYYY-MM-DD');
      switch (menu) {
        case '昨天':
          start = this.$moment()
            .subtract(1, 'days')
            .format('YYYY-MM-DD');
          end = this.$moment()
            .subtract(1, 'days')
            .format('YYYY-MM-DD');
          break;
        case '近7天':
          start = this.$moment()
            .subtract(7, 'days')
            .format('YYYY-MM-DD');
          end = this.$moment()
            .subtract(1, 'days')
            .format('YYYY-MM-DD');
          break;
        case '近30天':
          start = this.$moment()
            .subtract(30, 'days')
            .format('YYYY-MM-DD');
          end = this.$moment()
            .subtract(1, 'days')
            .format('YYYY-MM-DD');
          break;
        default:
          break;
      }
      this.start = start;
      this.end = end;
      this.$emit('change', start, end);
    },
  },
};
</script>

<style lang="scss" scoped>
.menus-wrap {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 40rpx;
}
</style>
