<template>
  <home-container :customStyle="{ backgroundPositionY: '-50px' }">
    <view class="attendance-container">
      <!-- 顶部个人信息栏 -->
      <view class="user-header" v-if="currentUser">
        <view class="user-avatar">
          <image v-if="currentUser.avatar" :src="currentUser.avatar" class="cu-avatar xl round"></image>
        </view>
        <view class="user-info">
          <text class="user-name">{{ `${userInfoAndRoles.nickName} ${userInfoAndRoles.userName}` }}</text>
          <text v-if="userInfo.userInfo.stationName" class="position-item">{{ userInfo.userInfo.stationName }}</text>
          <text v-if="userInfo.userInfo.stationName && userInfo.userInfo.departmentName" class="separator">/</text>
          <text v-if="userInfo.userInfo.departmentName" class="position-item">{{
            userInfo.userInfo.departmentName }}</text>
          <text v-if="userInfo.userInfo.departmentName && userInfo.userInfo.teamsName" class="separator">/</text>
          <text v-if="userInfo.userInfo.teamsName" class="position-item">{{ userInfo.userInfo.teamsName }}</text>
        </view>
        <view class="stats-btn" @click="showStats">
          <uni-icons type="calendar" size="24" color="#666"></uni-icons>
          <text class="btn-text">打卡统计</text>
        </view>
      </view>

      <!-- 新界面打卡 -->
      <AttendanceControl :attendanceInfo="attendanceInfo" :checkInPosiInfo="checkInPosiInfo"
        @attendanceHandler="handleCheckIn" />
      <!-- 工作区域/班组成员 -->
      <MaintainAreaOrMemberModal ref="maintainAreaOrMemberModal" v-if="showMaintain" :userInfo="userInfoAndRoles"
        @update-member="updateMember" :attendanceInfo="attendanceInfo" />
      <!-- 新界面工作组状态 -->
      <WorkingGroup ref="workingGroup" style="margin: 16px 0 24px 0" :attendanceInfo="attendanceInfo"
        :loadUserInfoOver="loadUserInfoOver" :userInfo="userInfoAndRoles" :selectedMember="selectedMember" />
    </view>
  </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import AttendanceControl from './components/AttendanceControl'
import MaintainAreaOrMemberModal from './components/MaintainAreaOrMemberModal'
import WorkingGroup from './components/WorkingGroup'
import { addAttendance, areaList } from "@/api/attendance/attendance"
import { getInfo } from "@/api/login"
import { formatTime as formatTimehandler } from '@/utils/formatUtils'
import { getAttendanceList, queryClickAble } from "@/api/attendance/attendance"
import { isInRangeOptimized, wgs84ToGcj02 } from '@/utils/handler'

export default {
  components: { HomeContainer, AttendanceControl, WorkingGroup, MaintainAreaOrMemberModal },

  computed: {
    currentUser() {
      return this.$store.state.user;
    },
    userInfoAndRoles() {
      return {
        ...this.userInfo.userInfo,
        roles: this.userInfo.roles
      }
    },
    showMaintain() {
      return this.userInfo.roles.includes('banzuzhang')
    }
  },
  data() {
    return {
      yesterday: false,
      checkInType: 'morning', // morning/afternoon
      isCheckedIn: false,
      checkInBtnText: '打卡',
      currentTime: this.formatTime(new Date()),
      locationIndex: 0,

      locations: [
        '民航机场',
        '东方雨虹新材料装备研发总部基地',
        '北京阳光汇点数码总部',
        '海淀区研发中心'
      ],
      groupIndex: 0,
      groups: [
        '技术部',
        '产品部',
        '运营部',
        '市场部'
      ],
      records: [],          // 今日真实打卡列表
      yesterdayRecords: [], // 昨天真实打卡列表
      userInfo: {
        userInfo: {},
        roles: []
      },
      checkInPosiInfo: [],
      attendanceInfo: {
        attendanceDate: '', // 当前日期
        checkInTime: '', //上班打卡时间
        checkOutTime: '', //下班打卡时间
        items: [], // 打开记录 第一条为最早上班打卡时间 最后一条为最晚下班打卡时间
      },
      loadUserInfoOver: false,
      selectedMember: [],
      result: null
    }
  },
  mounted() {
    this.updateCurrentTime();
    this.checkCheckInStatus();

    // app 在前台时获取位置信息
    uni.onLocationChange((res) => {
      this.result = { latitude: res.latitude, longitude: res.longitude }
    });
  },
  async onLoad() {
    this.loadUserInfoOver = false
    areaList().then(res => {
      this.checkInPosiInfo = res.data.map(item => {
        return {
          longitude: item.longitude,
          latitude: item.latitude,
          radius: item.radius,
          address: item.address
        }
      })
    })
    const userInfo = await getInfo()
    this.userInfo = userInfo || {}

    this.loadUserInfoOver = true
    this.$nextTick(() => {
      this.$refs.workingGroup.invokerGetPostRecordList()
    })
    // await this.loadYesterdayRecord();  // 1. 先查昨天
    // this.updateCurrentTime();          // 2. 再开始计时
    await this.loadTodayRecord();      // 3. 查今天

  },
  methods: {

    updateMember(member) {
      this.selectedMember = member
    },
    async loadYesterdayRecord() {
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      const start = this.formatDate(yesterday);

      const { data } = await getAttendanceList({ type: 1, checkInDate: start, userId: this.$store.state.user.id });
      this.yesterdayRecords = data?.[0]?.items || [];
      // this.yesterdayRecords = data[0].items || [];

      // 逻辑：昨天缺下班 && 距上班 ≤ 20 小时
      const lastMorning = this.yesterdayRecords.find(r => r.checkInType == 'CLOCK_IN'); // 1-上班
      const lastEvening = this.yesterdayRecords.find(r => r.checkInType == 'CLOCK_OUT'); // 2-下班

      if (lastMorning && !lastEvening) {
        // 确保时间字符串格式正确
        const checkInTime = new Date(lastMorning.checkInTime);
        if (isNaN(checkInTime.getTime())) {
          console.error('无效的时间格式');
          return;
        }

        // 计算时间差（毫秒）
        // const gap = Date.now() - checkInTime.getTime();
        const gap = Date.now() - new Date(lastMorning.checkInTime).getTime();
        if (gap <= 12 * 60 * 60 * 1000) {
          this.yesterday = true;
          // 12 小时内
          this.checkInType = 'afternoon';
          this.checkInBtnText = '下班打卡';

          this.records = this.yesterdayRecords.map(it => ({
            type: it.checkInType === 'CLOCK_IN' ? '上班打卡' : '下班打卡',
            time: it.checkInTime,   // 取 HH:mm:ss
            location: it.checkInPosition || '--',
            status: '正常',                  // 如需迟到逻辑，可在此判断
            checkInDate: it.checkInDate
          }));
          if (this.yesterdayRecords.length > 0) {
            this.checkInType = 'afternoon'
          }

          // 刷新按钮状态
          this.checkCheckInStatus();
        }
      }
    },
    async loadTodayRecord() {
      if (this.yesterday) {
        return;
      }
      const today = this.formatDate(new Date());
      const { data } = await getAttendanceList({
        type: 1,
        checkInDate: today,
        userId: this.$store.state.user.id
      });
      let res = await queryClickAble()
      let checkAbleType = res.data;
   
      // new
      if (Array.isArray(data) && data.length) {
        const items = data[0]
        const firstCheckOnTime = items.items.filter(item => item.checkInType === 'CLOCK_IN' && item.checkInTime).sort((a, b) => {
          return new Date(a.checkInTime).getTime() - new Date(b.checkInTime)
        })[0] || {}
        const latestCheckOutTime = items.items.filter(item => item.checkInType === 'CLOCK_OUT').sort((a, b) => {
          return new Date(b.checkInTime) - new Date(a.checkInTime).getTime()
        })[0] || {}
        console.log(firstCheckOnTime,"firstCheckOnTime")

        this.attendanceInfo = {
          ...items,
          ...(checkAbleType == '1'? {checkInTime: '', checkOutTime: ''}: {}),
          ...(checkAbleType == '2'? {checkInTime: formatTimehandler(firstCheckOnTime.checkInTime, 'hh:mm:ss', { defaultResult: '' }), checkOutTime: ''}:{}),
          // checkInTime: checkAbleType == 1 ? '' : formatTimehandler(firstCheckOnTime.checkInTime, 'hh:mm:ss', { defaultResult: '' }),
          // checkOutTime: checkAbleType == 1 ? '' : formatTimehandler(latestCheckOutTime.checkInTime, 'hh:mm:ss', { defaultResult: '' })
        }
        console.log(this.attendanceInfo,"this.attendanceInfo")
        
      }

      // 接口 data 可能是多条（按天），我们取第一条里的 items
      const todayData = data && data.length ? data[0] : null;
      const items = todayData ? todayData.items : [];

      // 映射成页面需要的格式
      this.records = items.map(it => ({
        type: it.checkInType === 'CLOCK_IN' ? '上班打卡' : '下班打卡',
        time: it.checkInTime,   // 取 HH:mm:ss
        location: it.checkInPosition || '--',
        status: '正常',
        checkInDate: it.checkInDate

      }));
      if (items.length > 0) {
        this.checkInType = 'afternoon'
      }

      // 刷新按钮状态
      this.checkCheckInStatus();
    },

    // 通用时间格式化
    formatTime(date) {
      const h = String(date.getHours()).padStart(2, '0');
      const m = String(date.getMinutes()).padStart(2, '0');
      const s = String(date.getSeconds()).padStart(2, '0');
      return `${h}:${m}:${s}`;
    },

    // 日期格式化（昨天、今天查询用）
    formatDate(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    },
    updateCurrentTime() {
      setInterval(() => {
        this.currentTime = this.formatTime(new Date());

        // 自动切换上下班打卡类型
        // const hours = new Date().getHours();
        // this.checkInType = hours < 12 ? 'morning' : 'afternoon';
        this.checkInBtnText = this.isCheckedIn ? '已打卡' : '打卡';
      }, 1000);
    },
    checkCheckInStatus() {
      const now = new Date();
      const type = now.getHours() < 12 ? 1 : 2;
      this.isCheckedIn = this.records.some(r => r.type === type);
      this.checkInBtnText = this.isCheckedIn ? '已打卡' : '打卡';
    },
    changeGroup(e) {
      this.groupIndex = e.detail.value;
    },
    async handleCheckIn(type, checkInPosition) {
      if (this.isCheckedIn) return;
      // if (this.attendanceInfo.checkInTime) { // 上班有卡 没下通道禁止打卡
      //   if (this.$refs.workingGroup.isCheckOutJobs()) {
      //     return uni.showToast({ title: '请先下岗位再下班打卡！', icon: 'none' });
      //   }
      // } 这个限制 业务不要
      uni.showLoading({ title: '打卡中...' });
      try {
        await addAttendance({
          userId: this.$store.state.user.id,
          checkInDate: this.formatDate(new Date()),
          checkInType: type, // 1 上班 2 下班
          remark: '',
          checkInPosition: checkInPosition.address,
          longitude: checkInPosition.longitude,
          latitude: checkInPosition.latitude,
        });

        await this.loadTodayRecord(); // 重新拉取今日
        uni.showToast({ title: '打卡成功', icon: 'success' });
      } finally {
        uni.hideLoading();
      }
    },
    showStats() {
      uni.navigateTo({ url: '/pages/attendance/stats' });
    }
  }

}
</script>

<style lang="scss" scoped>
.attendance-container {
  padding: 5px;
  padding-top: 60px;
  min-height: 100vh;
}

/* 顶部个人信息 */
.user-header {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 15px;
  margin-bottom: 20px;
  height: 96px;
  background: #FFFFFF;
  box-shadow: 0px 4px 16px 0px rgba(0, 0, 0, 0.06);
  border-radius: 16px 16px 16px 16px;

  .user-avatar {
    width: 50px;
    height: 50px;
    border-radius: 25px;
    overflow: hidden;
    margin-right: 12px;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .user-info {
    flex: 1;

    .user-name {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      display: block;
      margin-bottom: 8px;
    }

    .user-position {
      font-size: 14px;
      color: #666;
    }
  }

  .stats-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;

    .btn-text {
      margin-top: 4px;
      font-size: 12px;
      color: #666;
    }
  }
}
</style>