<template>
  <view class="user-sign-bg pb-60rpx">
    <view class="text-center">
      <image class="w-562rpx h-64rpx mx-auto mt-50rpx" src="/static/images/user/user_sign-title.png" />
    </view>
    <view class="px-base flex justify-between items-end mt-26rpx">
      <text class="month-u text-white text-3xl font-medium">{{m + 1}}</text>
      <!-- <image class="w-239rpx h-95rpx" src="/static/images/user/user_sign-rule.png" mode="widthFix" /> -->
    </view>
    <view class="px-base">
      <view class="bg-hex-ffffff bg-opacity-90 rounded-30rpx">
        <view class="grid grid-cols-7">
          <view class="text-center text-txBase text-md h-90rpx leading-90rpx" v-for="(item, index) in weekDay"
            :key="index">{{ item }}</view>
        </view>

        <view>
          <view class="grid grid-cols-7 gap-10rpx">
            <view class="text-txBase h-90rpx text-md flex items-center justify-center" v-for="(item, index) in dates"
              :key="index" :class="{ 'text-opacity-50': !item.lm }">
              <view class="h-56rpx w-56rpx flex items-center justify-center" @tap="selectOne(item, $event)"
                :class="{ sign: isSigned(item.year, item.month + 1, item.date) }">
                {{ item.date }}
              </view>
              <!-- <view class="sign" v-if="isSigned(item.year, item.month + 1, item.date)"></view> -->
            </view>
          </view>
        </view>
      </view>

      <view class="text-center">
        <!-- 点击签到 -->
        <image src="/static/images/user/user_sign-btn.png" @tap="onSign" mode="widthFix" class="mx-auto" />
      </view>

      <view class="px-base">
        <view class="bg-white rounded-30rpx bg-opacity-90 pb-25rpx">
          <view class="text-center">
            <image class="w-full" src="/static/images/user/user_sign-des-title.png" mode="widthFix" />
          </view>
          <view class="bg-icon bg-hex-F0FCF7 relative py-9rpx pl-60rpx mx-25rpx mb-38rpx">
            <view class="text-hex-073020 text-xl font-medium">积分获得方式</view>
            <view class="text-hex-073020 text-lg">可在商城中通过完成签到，观看健康知识小文章等获取专区积分</view>
          </view>
          <view class="bg-icon bg-hex-F0FCF7 relative py-9rpx pl-60rpx mx-25rpx mb-38rpx">
            <view class="text-hex-073020 text-xl font-medium">积分用途</view>
            <view class="text-hex-073020 text-lg">可使用积分在商城中去兑换丰富的产品</view>
          </view>
          <view class="bg-icon bg-hex-F0FCF7 relative py-9rpx pl-60rpx mx-25rpx mb-38rpx">
            <view class="text-hex-073020 text-xl font-medium">积分有效期</view>
            <view class="text-hex-073020 text-lg">以开通店铺当日时间作为有效期开始时间，有效期时间为6个月</view>
          </view>
        </view>
      </view>
    </view>

    <u-mask :show="show" @tap="show = false">
      <view class="flex items-center justify-center h-full flex-col">
        <image class="w-357rpx h-85rpx z-40" src="/static/images/user/user_sign-sucess.png" />
        <view class="w-511rpx border-4rpx border-primary rounded-15rpx h-303rpx bg-white -mt-42rpx pt-42rpx">
          <view class="h-full flex flex-col justify-center items-center text-primary">
            <view class="text-xl font-medium">今日签到获得<text class="text-warning">{{ points }}</text>积分</view>
            <!-- <view class="text-xl mt-27rpx">累积积分：320</view> -->
          </view>
        </view>
      </view>
    </u-mask>
  </view>
</template>
<script>
  import {
    formatDate,
    _pad
  } from '@/utils/filters';
  export default {
    data() {
      return {
        points: 0,
        show: false,
        weekstart: 7,
        open: true,
        text: {
          year: '年',
          month: '月',
          week: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          today: '今',
        },
        y: new Date().getFullYear(), // 年
        m: new Date().getMonth(), // 月
        dates: [], // 当前月日期集合
        positionTop: 0,
        monthOpen: true,
        choose: '',
        signeddates: [],
      };
    },
    computed: {
      // 顶部星期栏目
      weekDay() {
        return this.text.week.slice(this.weekstart - 1).concat(this.text.week.slice(0, this.weekstart - 1));
      },
      height() {
        return (this.dates.length / 7) * 80 + 'upx';
      },
    },
    onLoad() {
      this.dates = this.monthDay(this.y, this.m);
      !this.open && this.trgWeek();
      this.getSignDetail();
    },
    onShow() {
      let date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth();
      let d = date.getDate();
      this.choose = `${y}-${m + 1}-${d}`;
    },
    methods: {
      //获取签到
      async getSignDetail() {
        // console.log(this.dates.length);
        // console.log(this.formatDate(this.dates[0]), this.dates[34])

        const resData = await this.$api.get('/v1/click', {
          params: {
            start_at: this.formatDate(this.dates[0]),
            end_at: this.formatDate(this.dates[this.dates.length - 1]),
          },
        });
        this.signeddates = resData;
      },
      //签到
      async onSign() {
        const {
          points
        } = await this.$api.post('/v1/click');
        this.getSignDetail();
        this.points = points;
        this.show = true;
        this.$store.dispatch('user/getUserInfo');
      },

      // 获取当前月份天数
      monthDay(y, m) {
        let firstDayOfMonth = new Date(y, m, 1).getDay(); // 当月第一天星期几
        let lastDateOfMonth = new Date(y, m + 1, 0).getDate(); // 当月最后一天
        let lastDayOfLastMonth = new Date(y, m , 0).getDate(); // 上一月的最后一天

        let dates = []; // 所有渲染日历
        let weekstart = this.weekstart == 7 ? 0 : this.weekstart; // 方便进行日期计算，默认星期从0开始
        let startDay = (() => {
          // 周初有几天是上个月的
          if (firstDayOfMonth == weekstart) {
            return 0;
          } else if (firstDayOfMonth > weekstart) {
            return firstDayOfMonth - weekstart;
          } else {
            return 7 - weekstart + firstDayOfMonth;
          }
        })();
        let endDay = 7 - ((startDay + lastDateOfMonth) % 7); // 结束还有几天是下个月的
        for (let i = 1; i <= startDay; i++) {
          dates.push({
            date: lastDayOfLastMonth - startDay + i,
            day: weekstart + i - 1 || 7,
            month: m - 1 >= 0 ? m - 1 : 11,
            year: m - 1 >= 0 ? y : y - 1,
          });
        }
        for (let j = 1; j <= lastDateOfMonth; j++) {
          dates.push({
            date: j,
            day: (j % 7) + firstDayOfMonth - 1 || 7,
            month: m,
            year: y,
            lm: true,
          });

        }
        for (let k = 1; k <= endDay; k++) {
          dates.push({
            date: k,
            day: (lastDateOfMonth + startDay + weekstart + k - 1) % 7 || 7,
            month: m + 1 <= 11 ? m + 1 : 0,
            year: m + 1 <= 11 ? y : y + 1,
          });
        }
        return dates;
      },
      formatDate({
        year,
        month,
        date
      }) {
        let dy = `${year}-${_pad(month+1)}-${_pad(date)}`;
        return formatDate(dy, 'yyyy-MM-dd');
      },
      // 已经签到处理
      isSigned(y, m, d) {
        let flag = false;
        for (let i = 0; i < this.signeddates.length; i++) {
          let dy = `${y}-${_pad(m)}-${_pad(d)}`;

          if (this.signeddates[i] == formatDate(dy, 'yyyy-MM-dd')) {
            flag = true;
            break;
          }
        }
        return flag;
      },
      isToday(y, m, d) {
        let date = new Date();
        return y == date.getFullYear() && m == date.getMonth() && d == date.getDate();
      },
      // 切换成周模式
      trgWeek() {
        this.monthOpen = !this.monthOpen;
        if (this.monthOpen) {
          this.positionTop = 0;
        } else {
          let index = -1;
          this.dates.forEach((i, x) => {
            this.isToday(i.year, i.month, i.date) && (index = x);
          });
          this.positionTop = -((Math.ceil((index + 1) / 7) || 1) - 1) * 80;
        }
      },
      // 点击回调
      selectOne(i, event) {
        let date = `${i.year}-${i.month + 1}-${i.date}`;
        let selectD = new Date(date);
        if (selectD.getMonth() != this.m) {
          // console.log('不在可选范围内');
          return false;
        }
        this.choose = date;
        this.$emit('on-click', date);
      },
      // 上个月，下个月
      turning(_action) {
        if (_action === 'next') {
          if (this.m + 1 == 12) {
            this.m = 0;
            this.y = this.y + 1;
          } else {
            this.m = this.m + 1;
          }
        } else {
          if (this.m + 1 == 1) {
            this.m = 11;
            this.y = this.y - 1;
          } else {
            this.m = this.m - 1;
          }
        }

        this.dates = this.monthDay(this.y, this.m);
      },
    },
  };
</script>
<style lang="scss" scoped>
  .user-sign-bg {
    background: url('/static/images/user/user_sign-bg.png') no-repeat;
    background-size: 100% auto;
  }

  .month-u {
    &::after {
      content: '月';
      font-size: 70%;
    }
  }

  .sign {
    background: linear-gradient(180deg, rgba(255, 195, 0, 1) 0%, rgba(255, 91, 41, 1) 100%);
    border-radius: 50%;
    color: white;
    position: relative;

    &::after {
      content: '';
      background: url('/static/images/user/user_sign-sign-icon.png') no-repeat;
      background-size: 24rpx 24rpx;
      position: absolute;
      width: 24rpx;
      height: 24rpx;
      bottom: -26rpx;
    }
  }

  .bg-icon {
    &::before {
      content: '';
      position: absolute;
      left: -10rpx;
      top: -10rpx;
      background: url('/static/images/user/user_sign-des-icon.png') no-repeat;
      background-size: 100% 100%;
      width: 50rpx;
      height: 50rpx;
      display: block;
    }
  }
</style>
