<template>
  <view class="wrap">
    <div class="button_wrap">
      <div v-for="obj in attTimeKeyList" class="btn_item" :class="{ 'active': !obj.timeOut && !obj.ready }"
        @click="attendanceClickFn(obj)">
        <!-- 动画层 -->
        <div :class="{ 'ani': !obj.timeOut && !obj.ready }"></div>
        <!-- 内容层 -->
        <div class="content" :class="(obj.timeOut || obj.ready) ? 'workbtn_disabled' : obj.class">
          <span>{{ obj.title }}</span>
          <span v-if="obj.timeOut && !obj.ready" class="over">请补卡</span>
          <span v-if="obj.ready" class="right">已打卡</span>
          <span v-if="!obj.timeOut && !obj.ready">{{ obj.beginValue }}</span>
        </div>
      </div>
    </div>
    <uni-list class="list_wrap">
      <uni-list-item v-for="item in attendanceList">
        <template v-slot:header>
          <span>{{ parseTime(item.time, '{y}-{m}-{d} 星期{a}') }}</span>
        </template>
        <!-- 自定义 body -->
        <template v-slot:body>
          <div class="item_body">
            <div class="item" v-for="obj in item.kqTimeList">
              <text class="time">{{ obj.kqTime ? parseTime(obj.kqTime, '{h}:{i}:{s}') : '暂未打卡' }}</text>
              <text class="title">{{ attendanceDict[obj.kqType] }}打卡</text>
            </div>
          </div>
        </template>
      </uni-list-item>
      <uni-list-item v-if="attendanceList.length === 0">
        <template v-slot:body>
          <view class="empty-box">
            <text class="empty-text">暂无打卡记录</text>
          </view>
        </template>
      </uni-list-item>
    </uni-list>

  </view>
</template>

<script>

import { getAttendanceDetailAPI, addAttendanceAPI, getAttendanceListAPI } from '@/api'
import { checkStartLessEndTime, parseTime, isSameDay, zeroTo24, checkTimeIsBetween } from '@/utils/common'
export default {
  data() {
    return {
      attTimeKeyList: [], // 循环按钮配置列表
      attendanceList: [], // 近 7 天考勤列表
      attendanceDict: { // 考勤字典
        1: '上班',
        2: '午班',
        3: '下班'
      },
      currently: '' // 服务器当前时间（格式：时:分:秒.毫秒）
    }
  },
  created() {
    this.getRuleInfoFn()
  },
  methods: {
    parseTime,
    // 获取考勤规则详情
    async getRuleInfoFn() {
      const list = [{ // 需要考勤列表
        beginKey: 'firBegintime',
        beginValue: '',
        endKey: 'firEndtime',
        endValue: '',
        class: 'go_work',
        title: '上班打卡',
        timeOut: false, // 是否过了打卡时间
        ready: false, // 是否已经打过卡了
        type: 1, // 考勤类型
      },
      {
        beginKey: 'secBegintime',
        beginValue: '',
        endKey: 'secEndtime',
        endValue: '',
        class: 'after_work',
        title: '午班打卡',
        timeOut: false,
        ready: false,
        type: 2,
      },
      {
        beginKey: 'thiBegintime',
        beginValue: '',
        endKey: 'thiEndtime',
        endValue: '',
        class: 'off_work',
        title: '下班打卡',
        timeOut: false,
        ready: false,
        type: 3,
      }]
      // 需要提取打卡的时间
      const { data } = await getAttendanceDetailAPI(this.$store.getters.user.ruleId)
      for (let i = 0; i < list.length; i++) {
        const obj = list[i]
        if (!data[obj.beginKey]) {
          // 如果打卡开始时间是空的（例如：有的人没有午班打卡，则删除数据结构中的一项）
          list.splice(i, 1)
          i--
          continue
        }
        obj['beginValue'] = data[obj.beginKey]
        obj['endValue'] = data[obj.endKey]
        // 判断服务器时间
        obj['timeOut'] = checkStartLessEndTime(zeroTo24(data[obj.endKey]), data.currently)
      }
      this.attTimeKeyList = list

      // 保存服务器时间
      this.currently = data.currently.split(".")[0]
      // 考勤打卡记录
      this.getAttendanceListFn()
    },
    // 考勤打卡
    async attendanceClickFn(attObj) {
      const { addressComponent, location } = this.$store.getters.location
      const { lng, lat } = location
      const { province, city, district, street } = addressComponent
      if (attObj.timeOut) {
        // 超过打卡时间
        return this.$modal.msgError('超过了打卡时间')
      }
      // 判断它打卡时间范围是否合法（在开始之后，结束之前）
      if (checkTimeIsBetween(attObj.beginValue, attObj.endValue, this.currently)) {
        await addAttendanceAPI({
          "kqLocal": [
            lng,
            lat
          ],
          "kqProvinc": province,
          "kqCity": city,
          "kqCounty": district,
          "kqAddress": street,
          "kqPicurl": "https://www.baidu.com",
          "kqType": attObj.type
        })
        this.$modal.msgSuccess('打卡成功')
        // 考勤打卡记录
        this.getAttendanceListFn()
      } else {
        this.$modal.msgError('打卡还未开始')
      }


    },
    // 获取考勤列表
    async getAttendanceListFn() {
      const { data: { current, data } } = await getAttendanceListAPI()
      const list = []
      // 如果有打卡时间，则转换后台的结构数据
      if (Object.keys(data).length > 0) {
        Object.entries(data).forEach(([key, value]) => {
          const attTime = [] // 打卡时间
          value.forEach(obj => {
            attTime.push({
              kqTime: obj.kqTime,
              kqType: obj.kqType
            })
          })
          list.push({
            time: key,
            kqTimeList: attTime
          })
        })
        // 考勤记录
        this.attendanceList = list

        // 默认第 0 条就是今日打卡的记录，判断是否打卡
        this.attTimeKeyList.forEach((obj, index) => {
          // 从按钮数组里去已打卡时间数组里取出，打卡时间对象
          const readyObj = this.attendanceList[0].kqTimeList[index]
          if (readyObj.kqTime) {
            // 如果找到了打卡时间，证明已经打过卡了
            obj.ready = true
          }
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.wrap {
  background-color: #f0f1f3;
  height: 100vh;
  display: flex;
  flex-direction: column;

  .button_wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 50rpx;
    padding: 50rpx 0;
    flex: 1;

    .btn_item {
      width: 250rpx;
      height: 250rpx;
      position: relative;
      transition: all 0.1s linear;

      .ani,
      .content {
        width: 100%;
        height: 100%;
        position: absolute;
        border-radius: 50%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        gap: 0 !important;
        align-items: center;
        color: white;

      }

      .content {
        .over {
          font-size: 28rpx;
          color: #d9322c;
          margin-top: 10rpx;
        }

        .right {
          font-size: 28rpx;
          color: #32cdbf;
          margin-top: 10rpx;
        }

        &.workbtn_disabled {
          background-color: #c7c8c8;
          color: rgb(160, 156, 156);
        }

        &.go_work {
          background-color: #32cdbf;
        }

        &.after_work {
          background-color: #e0bd47;
        }

        &.off_work {
          background-color: #5dabed;

        }

      }

      .ani {

        &:before,
        &:after {
          content: '';
          width: 100%;
          height: 100%;
          border-radius: 50%;
          position: absolute;
          animation: eff68 1.4s linear infinite;
          // animation: eff68 5s linear infinite;
        }

        &:after {
          animation-delay: .7s;
          // animation-delay: 2.5s;
        }

        @keyframes eff68 {
          0% {
            // box-shadow: 0 0 0 0px #0093E9;
            background-color: rgba(0, 147, 233, 0.2);
            transform: scale(1);
            // opacity: 0.2;
          }

          100% {
            // box-shadow: 0 0 0 20px #0093E9;
            background-color: rgba(0, 147, 233, 0);
            transform: scale(1.4);
            // opacity: 0;
          }
        }
      }

      // 打卡按钮动画
      &.active:active {
        transform: scale(0.8);
      }

    }
  }

  .list_wrap {
    height: 700rpx;
    overflow-y: scroll;

    ::v-deep .uni-list-item__container {
      display: block !important;
    }

    .item_body {
      display: flex;
      justify-content: space-between;
      padding-top: 24rpx;

      .item {
        display: flex;
        flex-direction: column;

        .time {
          color: #d9572c;
        }

        .title {
          font-size: 24rpx;
        }
      }
    }
  }
}
</style>