<script setup lang="ts" name="clockinCalendar">
import { ref, reactive, computed, onMounted, getCurrentInstance, type ComponentInternalInstance } from 'vue'
import { storeToRefs } from 'pinia'
import topBgImg from '@/static/image/check/topBg.png'
import Calendar from '../../components/calendar/calendar.vue'
import useUserStore from '@/store/modules/user'
// import { useRouter, useRoute } from 'vue-router'
import { useDict } from '../../common/utils/dict'
import { parseTime } from '../../common/utils/ruoyi'
import UserCard from '../../components/UserCard.vue'

import { attCalendar, getTAttRecordItemByDay } from '@/api/clockIn'

const { att_status, audit_status } = useDict('att_status', 'audit_status')

// const router = useRouter()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const calendarRef = ref<InstanceType<typeof Calendar>>()

const today = new Date()
const yearMonth = ref(parseTime(today, '{y}-{m}'))
const classesData = ref(null) as any // 考勤班次
const dayList = ref([])
const currentTime = reactive({
  year: 0,
  month: 0,
  day: 0
})

const getAttCalendar = () => {
  return new Promise((resolve, reject) => {
    attCalendar({
      yearMonth: yearMonth.value,
      employeesCode: userInfo.value.userCode
    }).then((res) => {
      const data = res.data
      dayList.value = data.dayStatus?.map(item => {
        return { days: parseTime(new Date(data.attYear, data.attMonth - 1, item.day), '{y}-{m}-{d}'), status: item.status }
      })
      resolve(res)
    }).catch((err) => reject(err))
  })
}

const getYearMonthDay = (dateString: string|number|Date) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = date.getMonth() + 1 // 月份是从0开始的
  const day = date.getDate()
  return { year, month, day }
}

// 初始化日历
const initChange = (val: any) => {
  const { year, month, day } = getYearMonthDay(val.day)
  currentTime.year = year
  currentTime.month = month
  currentTime.day = day
  // console.log(val, currentTime)
  yearMonth.value = parseTime(val.start, '{y}-{m}')
  getAttCalendar()
  getTAttRecordItemByDayEvent(val.day)
}

// 日历选择
const selectedChange = (val: any) => {
  const { year, month, day } = getYearMonthDay(val.fullDate)
  currentTime.year = year
  currentTime.month = month
  currentTime.day = day
  getTAttRecordItemByDayEvent(val.fullDate)
}

// 每日明细
const getTAttRecordItemByDayEvent = (time: string) => {
  getTAttRecordItemByDay({ attendanceDate: time, employeesCode: userStore.userInfo.userCode }).then(res => {
    classesData.value = res.data
  })
}

// 回今日
const todayClick = () => {
  calendarRef.value?.goback()
}

// 签卡状态
const cardSigning = (item) => {
  // if (userInfo.value.companyId !== '18') return false
  const state = item.attStatus
  const auditStatus = item.auditStatus
  // 已签卡申请，存在审核状态，不允许签卡
  if (auditStatus) return false
  if (!state || state === '2' || state === '3' || state === '4' || state === '7') {
    return true
  }
  return false
}

// 状态icon
const stateIcon = (state: string) => {
  if (!state || state === '7') {
    return 'warning'
  }
  return 'checked'
}

// 状态色值
const stateColor = (state: string) => {
  if (state === '1') {
    return 'rgba(71, 115, 252, 1)'
  }
  return 'rgba(255, 189, 81, 1)'
}

// 去签卡
const signCardClick = ({ recordItemDurationId, time, checkType, oriSignTime }: { recordItemDurationId: any; time: any; checkType: any; oriSignTime: any }, index: number) => {
  let signTime = `${currentTime.year}-${String(currentTime.month).padStart(2, '0')}-${String(currentTime.day).padStart(2, '0')} ${time}`
  if (index > 0) {
    if (time <= classesData.value.checkList[0].time) {
      signTime = parseTime(new Date(signTime.replace(/-/g, '/')).getTime() + 1000 * 3600 * 24, '{y}-{m}-{d} {h}:{i}')
    }
  }
  const data = {
    recordItemDurationId: recordItemDurationId,
    checkType: checkType,
    signTime: signTime,
    signReason: '',
    oriSignTime: oriSignTime
  }
  const dataText = JSON.stringify(data)
  // router.push({
  //   path: '/attendance/cardSign/add',
  //   query: { type: 1, data: dataText }
  // })
  uni.navigateTo({
    url:'/attendance/cardSign/add?type=' + 1 + '&data=' + dataText
  })
}

const getHourMinute = (datetimeStr: string|number|Date) => {
  return parseTime(datetimeStr, '{h}:{i}')
}

onMounted(async () => {
  getAttCalendar().then(() => {
    getTAttRecordItemByDayEvent(parseTime(today, '{y}-{m}-{d}'))
  })
})
</script>

<template>
  <div class="container">
    <UserCard />
    <div class="contentBox">
      <div class="topTime">
        <div class="timeBox" v-if="currentTime">
          <span>{{ currentTime.year }}</span>
          <div class="line" />
          <span>{{ currentTime.month < 10 ? `0${currentTime.month}` : currentTime.month }}.{{ currentTime.day < 10 ? `0${currentTime.day}` : currentTime.day }}</span>
        </div>
        <div class="today" @click="todayClick">回今日</div>
      </div>
      <div class="tipeBox">
        <!-- <div class="tipeLi">
          <div class="icon icon1" />
          <span>全天考勤正常</span>
        </div> -->
        <div class="tipeLi">
          <div class="icon icon2-4" />
          <span>当天存在异常：迟到、早退、缺卡</span>
        </div>
        <div class="tipeLi">
          <div class="topTime">
            <div class="icon icon8-17" />
            <span>当天提交过：请假</span>
          </div>
        </div>
        <div class="tipeLi">
          <div class="topTime">
            <div class="icon icon5" />
            <span>当天提交过：当日外出/出差</span>
          </div>
        </div>
        <div class="tipeLi">
          <div class="topTime">
            <div class="icon icon7" />
            <span>当天提交过：补卡申请</span>
          </div>
        </div>
        <!-- <div class="tipeLi">
          <div class="topTime">
            <div class="icon icon18" />
            <span>当天：国假</span>
          </div>
        </div> -->
        <div class="tipeLi">
          <div class="topTime">
            <div class="icon icon-weekend" />
            <span>休息</span>
          </div>
        </div>
      </div>
      <div class="calendarBox">
        <Calendar
          ref="calendarRef"
          :dotList="dayList"
          @days-change="initChange"
          @selected-change="selectedChange"/>
      </div>
      <div class="statistics" v-if="classesData">出勤统计：今日打卡{{ classesData.statisc.counts }}次，共计工时{{ classesData.statisc.attHours }}小时</div>
      <div class="detailsList" v-if="classesData">
        <div class="detailsLi" v-for="(item,index) in classesData.checkList" :key="index">
          <div class="titleBox">
            <van-icon
              :name="stateIcon(item.attStatus)"
              size="16"
              class="icon"
              :color="stateColor(item.attStatus)" />
            <div class="time">{{ item.oriSignTime ? `${getHourMinute(item.oriSignTime)} 已打卡` : '未打卡' }}</div>
            <div class="state" :class="`state${item.attStatus}`" v-if="item.attStatus !== '1'">
              <!-- {{ item.attStatus ? getDictName(getAttStatusList(), 'dictValue', 'dictLabel', item.attStatus) : '签卡' }} -->
              <DictTag :options="att_status" :value="item.attStatus" />
              <DictTag
                v-if="item.auditStatus"
                :options="audit_status"
                :value="item.auditStatus"
                style="margin-left: 0.4rem;" />
            </div>
          </div>
          <div class="content">
            <div class="line" :class="`${(index === classesData.checkList.length - 1) ? 'lineHide' : ''}`"/>
            <div class="info">
              <div class="text">
                {{ item.checkType === '1' ? '上班' : '下班' }}时间 {{ item.time }}
              </div>
              <div class="text">{{ item.addrName }}</div>
              <div class="cardSigning" v-if="cardSigning(item)" @click="signCardClick(item, index)">去签卡</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.container {
  position: relative;
  background: #f9f9f9;
  .topBg {
    position: absolute;
    top: -140rpx;
    left: 0;
    width: 100%;
    height: 286rpx;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .top {
    position: relative;
    margin: 20rpx auto 16rpx auto;
    padding: 0 28rpx;
    width: calc(684rpx - 28rpx - 28rpx);
    height: 142rpx;
    background-color: rgba(255, 255, 255, 1);
    box-shadow: 0 4rpx 40rpx rgba(64, 103, 251, 0.14);
    border-radius: 24rpx;
    display: flex;
    align-items: center;
    .icon {
      margin-right: 20rpx;
      width: 84rpx;
      height: 84rpx;
      background: rgba(64, 158, 255, 1);
      border-radius: 12rpx;
      font-size: 28rpx;
      text-align: center;
      line-height: 84rpx;
      color: #fff;
    }
    .info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      .name {
        margin-bottom: 8rpx;
        font-size: 32rpx;
        font-weight: 500;
        color: rgba(37, 37, 37, 1);
      }
      .position {
        font-size: 24rpx;
        letter-spacing: 12rpx;
        color: rgba(37, 37, 37, 1);
      }
    }
  }
  .contentBox {
    position: relative;
    flex: 1;
    margin: 24rpx 0 0;
    padding: 32rpx 32rpx 40rpx 32rpx;
    background-color: rgba(255, 255, 255, 1);
    box-shadow: 0 4rpx 40rpx rgba(0, 0, 0, 0.14);
    border-radius: 20rpx;
    .topTime {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .timeBox {
        display: flex;
        font-size: 36rpx;
        font-weight: 700;
        letter-spacing: 18rpx;
        line-height: 36rpx;
        color: rgba(37, 37, 37, 1);
        .line {
          margin: 0 14rpx;
          width: 2rpx;
          height: 28rpx;
          background: rgba(151, 151, 151, 0.2);
        }
      }
      .today {
        font-size: 28rpx;
        letter-spacing: 14rpx;
        line-height: 28rpx;
        color: rgba(62, 174, 255, 1);
      }
    }
    .tipeBox {
      margin-top: 24rpx;
      padding: 20rpx 18rpx;
      width: calc(100% - 18rpx - 18rpx);
      background: rgba(216, 216, 216, 0.1);
      border-radius: 16rpx;
      .tipeLi {
        margin-bottom: 12rpx;
        display: flex;
        align-items: center;
        font-size: 24rpx;
        letter-spacing: 12rpx;
        line-height: 24rpx;
        color: rgba(37, 37, 37, 0.65);
        .icon {
          margin-right: 16rpx;
          width: 8rpx;
          height: 8rpx;
          border-radius: 50%;
        }
        .icon2-4 {
          background: #ff0000;
        }
        .icon5 {
          background: #ffc9a8;
        }
        .icon7 {
          background: #ffff00;
        }
        .icon8-17 {
          background: #00b3f6;
        }
        .icon18 {
          background: #00b342;
        }
        .icon-weekend {
          background: #00b342;
        }
      }
      .tipeLi:last-child {
        margin-bottom: 0;
      }
    }
  }
  .calendarBox {
    margin-top: 56rpx;
    width: 100%;
  }
  .statistics {
    font-size: 24rpx;
    letter-spacing: 12rpx;
    line-height: 24rpx;
    color: rgba(37, 37, 37, 0.65);
  }
  .detailsList {
    margin-top: 40rpx;
    display: flex;
    flex-direction: column;
    .detailsLi {
      display: flex;
      flex-direction: column;
      .icon {
        margin-right: 40rpx;
      }
      .titleBox{
        display: flex;
        align-items: center;
        .time{
          font-size: 30rpx;
          letter-spacing: 15rpx;
          line-height: 32rpx;
          color: rgba(37, 37, 37, 1);
        }
        .state {
          display: flex;
          align-items: center;
          margin-left: 16rpx;
        }
      }
      .content{
        display: flex;
        overflow: hidden;
        .line{
          margin: 0 57rpx 0 13rpx;
          width: 0;
          border-left: 4rpx dashed rgba(216, 216, 216, 1);
        }
        .lineHide{opacity: 0;}
        .info{
          padding: 20rpx 0 28rpx 0;
          .text{
            display: flex;
            align-items: center;
            margin-bottom: 14rpx;
            font-size: 24rpx;
            font-weight: 400;
            letter-spacing: 12rpx;
            line-height: 28.12rpx;
            color: rgba(37, 37, 37, .35);
          }
          .cardSigning{
            margin-top: 20rpx;
            width: 144rpx;
            height: 48rpx;
            border-radius: 8rpx;
            background: rgba(232, 242, 255, 1);
            text-align: center;
            line-height: 48rpx;
            color: rgba(55, 108, 220, 1);
            font-size: 24rpx;
          }
        }
      }
    }
  }
}
</style>