<template>
  <view class="statistics-page">
    <!-- 不在时间范围 -->
    <view v-if="isNotInTime" class="isNotInTime">
      <view class="isNotInTime-title">
        <Icon name="icon-naoling" size="97" color="#ff7e00" />
        当前不在点名时段！
      </view>

      <view class="isNotInTime-content">
        <view class="isNotInTime-content-title">点名时段</view>
        <view v-for="item in NotInTime" class="isNotInTime-content-item">
          <view class="isNotInTime-content-item-icon">
            <Icon :name="item.icon" :size="item.iconSize" :color="item.iconColor" />
          </view>
          <view>
            <view>{{ item.title }}</view>
            <view>{{ item.range }}</view>
          </view>
        </view>
      </view>

    </view>

    <!-- Swiper 卡片容器 -->
    <swiper
      v-else
      class="grade-swiper"
      :current="currentIndex"
      :vertical="true"
      :previous-margin="currentIndex > 0 ? '30rpx' : '0'"
      :next-margin="currentIndex < njDataList.length - 1 ? '30rpx' : '0'"
      @change="handleSwiperChange"
    >
      <swiper-item
        v-for="(njData, index) in njDataList"
        :key="njData.njid"
        :class="{
          'first-item': index === 0,
          'last-item': index === njDataList.length - 1,
          'middle-item': index > 0 && index < njDataList.length - 1
        }"
      >
        <view class="statistics-card">
          <!-- Top 部分 -->
          <view class="statistics-top">
            <view class="statistics-date"> {{ toChineseDateMonth(allData?.jkssj) || '5月20日' }} {{ getDayPeriod(allData?.jkssj) || '上午' }} </view>
            <view class="statistics-class"> {{ njData?.mc || '一年级' }} </view>
            <!-- 圆形进度条 -->
            <view class="progress-container">
              <view class="progress-circle" :style="getProgressCircleStyle(njData)">
              </view>
            </view>
            <view class="progress-legend">
              <view class="legend-item">
                <view class="legend-dot completed"></view>
                <text>已点名</text>
              </view>
              <view class="legend-item">
                <view class="legend-dot pending"></view>
                <text>未点名</text>
              </view>
            </view>
          </view>

          <!-- Bottom 部分 -->
          <view class="statistics-bottom">
            <view class="statistics-penal">
              <!-- 已全部点名完成的提示 -->
              <view v-if="isGradeAllChecked(njData)" class="statistics-all-checked">
                <view class="statistics-all-checked-title">点名情况</view>
                <view class="stats-section">
                  <view class="stat-item">
                    <text class="stat-label">出勤:</text>
                    <text class="stat-value present">{{ (njData?.totalStudentCount || 0) - (ydmData.qjrs || 0) - (ydmData.kkrs || 0) }}人</text>
                  </view>
                  <view class="stat-item">
                    <text class="stat-label">缺勤:</text>
                    <text class="stat-value absent">{{ ydmData.kkrs || 0 }} 人</text>
                  </view>
                  <view class="stat-item">
                    <text class="stat-label">请假:</text>
                    <text class="stat-value absent">{{ ydmData.qjrs || 0 }} 人</text>
                  </view>
                </view>
              </view>

              <!-- 未点名班级列表 -->
              <view v-else style="height: 100%;">
                <view style="display: flex;justify-content: space-between;color: #000000;font-weight: bold;font-size: 34rpx;margin: 20rpx 0 40rpx 0;">
                  <view>未点名班级</view>
                  <view><text :style="{ color: getProgressPercentage(njData) === 100 ? '' : '#df5548' }">{{ getCheckedCount(njData) }}</text>/{{ njData?.bjList?.length || 0 }}</view>
                </view>
                <view class="statistics-uncheck-list">
                  <view v-for="item in getUnCheckedBjList(njData)" :key="item.bjid" class="list-item" @click="handleBjClick(item)">
                    <view class="list-item-title">
                      {{ item.mc }}
                    </view>
                    <view class="list-item-content">
                      <view>{{ item.xm }}</view>
                      <view>{{ item.grdh || '无' }}</view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, getCurrentInstance, defineExpose } from 'vue'
import { kqjlApi } from '@/api/kqjl'
import { formatDate, getDayPeriod, toChineseDateMonth } from '@/utils/date'
import Icon from '@/components/icon/index.vue';

const allData = ref() // 总数据（包含年级列表和班级列表）
const njDataList = ref([]) // 按年级拆分后的数据列表
const ydmData = ref() // 已经点名的年级数据
const ydmInterval = ref()
const isNotInTime = ref(false)

// 滑动相关变量
const currentIndex = ref(0) // 当前显示的年级索引
const NotInTime = ref([
    {
        icon: 'icon-shangwu',
        iconColor: '#1296db',
        iconSize: 97,
        title: '上午',
        range:'6:00~12:00'
    },
    {
        icon: 'icon-xiawu',
        iconColor: '#dd9900',
        iconSize: 97,
        title: '下午',
        range:'13:40~16:00'
    },
    {
        icon: 'icon-night',
        iconColor: '#333333',
        iconSize: 97,
        title: '晚上',
        range:'18:30~21:00'
    }
])

// 按年级拆分班级数据
function organizeDataByGrade() {
  if (!allData.value?.njList || !allData.value?.bjList) {
    njDataList.value = []
    return
  }

  njDataList.value = allData.value.njList.map(nj => {
    const bjList = allData.value.bjList.filter(bj => bj.njm === nj.njm)
    return {
      ...nj,
      bjList,
      totalStudentCount: bjList.reduce((sum, bj) => sum + (bj.rs || 0), 0)
    }
  })
}

// 计算指定年级未点名的班级列表
const getUnCheckedBjList = (njData) => {
  if (!njData?.bjList || !ydmData.value?.ydmBjList) {
    return njData?.bjList || []
  }

  // 已点名的班级ID数组
  const checkedBjIds = ydmData.value.ydmBjList.map(id => parseInt(id))

  // 筛选出未点名的班级
  return njData.bjList.filter(bj => !checkedBjIds.includes(bj.bjid))
}

// 获取指定年级已点名的班级数量
const getCheckedCount = (njData) => {
  if (!njData?.bjList || !ydmData.value?.ydmBjList) {
    return 0
  }
  const checkedBjIds = ydmData.value.ydmBjList.map(id => parseInt(id))
  return njData.bjList.filter(bj => checkedBjIds.includes(bj.bjid)).length
}

// 计算指定年级是否全部点名完成
const isGradeAllChecked = (njData) => {
  if (!njData?.bjList || !ydmData.value?.ydmBjList) {
    return false
  }
  const checkedCount = getCheckedCount(njData)
  // 只有当已点名班级数量大于0且等于该年级总班级数量时，才算全部完成
  return checkedCount > 0 && njData.bjList.length === checkedCount
}

// 计算指定年级的进度百分比
const getProgressPercentage = (njData) => {
  if (!njData?.bjList || njData.bjList.length === 0) {
    return 0
  }
  const checkedBjIds = ydmData.value?.ydmBjList?.map(id => parseInt(id)) || []
  const checkedCount = njData.bjList.filter(bj => checkedBjIds.includes(bj.bjid)).length
  return Math.round((checkedCount / njData.bjList.length) * 100)
}

// 计算指定年级的圆形进度条样式
const getProgressCircleStyle = (njData) => {
  const percentage = getProgressPercentage(njData)

  if (percentage === 0) {
    // 全红色
    return {
      background: '#df5548',
      color: '#333'
    }
  } else if (percentage === 100) {
    // 全绿色
    return {
      background: '#4db680',
      color: '#333'
    }
  } else {
    // 部分完成，在红绿交界处两边各添加透明边框
    const degrees = percentage * 3.6
    const borderWidth = 0.5 // 每侧透明边框宽度（角度）

    // 绿色区域的结束角度（减去边框）
    const greenEndDegree = degrees - borderWidth
    // 红色区域的开始角度（加上边框）
    const redStartDegree = degrees + borderWidth

    return {
      background: `conic-gradient(
        transparent 0deg ${borderWidth}deg,
        #4db680 ${borderWidth}deg ${greenEndDegree}deg,
        transparent ${greenEndDegree}deg ${redStartDegree}deg,
        #df5548 ${redStartDegree}deg ${360 - borderWidth}deg,
        transparent ${360 - borderWidth}deg 360deg
      )`,
      color: '#333'
    }
  }
}

function handleBjClick(bj) {
  console.log('点击了班级：', bj)
  if (bj.grdh) {
    uni.makePhoneCall({
      phoneNumber: bj.grdh,
      success: () => {
        console.log('拨号成功')
      },
      fail: (err) => {
        console.log('拨号失败', err)
      }
    })
  }
}

// Swiper 切换事件处理
function handleSwiperChange(e) {
  currentIndex.value = e.detail.current
}

async function init() {
  const res = await kqjlApi.mp_njdmHomep_load()
  if (res.data.msg && res.data.msg.includes("不在点名时段")) {
    isNotInTime.value = true
    NotInTime.value[0].range = res.data.swsjd;
    NotInTime.value[1].range = res.data.xwsjd;
    NotInTime.value[2].range = res.data.wssjd;
    return
  }
  allData.value = res.data
  isNotInTime.value = false

  // 按年级拆分数据
  organizeDataByGrade()

  refreshLoad()
  // 先清理已存在的定时器，防止重复创建
  if (ydmInterval.value) {
    clearInterval(ydmInterval.value)
    ydmInterval.value = null
  }
  // 定时刷新
  ydmInterval.value = setInterval(() => {
    refreshLoad()
  }, 15000)
}
async function refreshLoad() {
  const res = await kqjlApi.mp_njdmHomep_refreshLoad({
    njmStr: allData.value.njmStr,
    jkssj: formatDate(allData.value.jkssj, 'yyyy-MM-dd HH:mm:ss'),
    jjssj: formatDate(allData.value.jjssj, 'yyyy-MM-dd HH:mm:ss')
  })
  ydmData.value = res.data

  // Mock 数据：模拟其中一个班级已经点名
  // ydmData.value.ydmBjList = ['40211', '40212'] // 模拟A班已点名

  console.log('已点名数据:', ydmData.value)
  // console.log('未点名班级:', unCheckedBjList.value)
}

// ============== 暴露给主容器的生命周期（供 pages/main/index.vue 调用） ==============

function onLoad() {
    init()
}

function onShow() {
  console.log('统计图onShow')
  init()
}

function onHide() {
  // 可按需做暂存处理
  console.log('统计图onHide')
  if (ydmInterval.value) {
    clearInterval(ydmInterval.value)
    ydmInterval.value = null
  }
}

function onUnload() {
  // 可按需做清理处理
  console.log('onUnload')
  if (ydmInterval.value) {
    clearInterval(ydmInterval.value)
    ydmInterval.value = null
  }
}

defineExpose({ onLoad, onShow, onHide, onUnload })
</script>

<style scoped lang="less">
.statistics-page {
  height: 100%;
  background: #f5f5f5;
  padding:0 20rpx;
  position: relative;
  box-sizing: border-box;
}

.grade-container {
  position: relative;
  height: 100vh;
  width: 100%;
  overflow: hidden;
}

.grade-content {
  position: relative;
  height: 100%;
  transition: transform 0.3s ease;
}


// Swiper 样式
.grade-swiper {
  width: 100%;
  height: 100%;
  box-sizing: border-box;

  // swiper-item 控制间距
  swiper-item {
    box-sizing: border-box;
    display: flex;
    align-items: center;

    // 第一个 item：只有下内边距
    &.first-item {
      padding: 0 0 10rpx 0;
    }

    // 最后一个 item：只有上内边距
    &.last-item {
      padding: 10rpx 0 0 0;
    }

    // 中间 item：上下都有内边距
    &.middle-item {
      padding: 10rpx 0;
    }

    // 只有一个 item
    &.first-item.last-item {
      padding: 0;
    }
  }
}

.statistics-card {
  background: #fff;
  width: 100%;
  height: 100%;
  border-radius: 4rpx;
  padding: 20rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.statistics-top {
  flex: 4;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
}

.statistics-bottom {
  flex: 6;
  display: flex;
  flex-direction: column;
  // padding: 0 0 20rpx;
  overflow: hidden;
}

.statistics-penal {
  background: #f9fafb;
  border-radius: 4rpx;
  width: 100%;
  height: 100%;
  padding: 32rpx;
  box-sizing: border-box;

}

.statistics-date {
  color: #333;
  font-weight: 500;
  font-size: 38rpx;
  text-align: center;
  margin-bottom: 10rpx;
}

.statistics-class {
  color: #333;
  font-size: 32rpx;
  font-weight: 500;
  text-align: center;
}



// 进度条样式
.progress-container {
  display: flex;
  justify-content: center;
  margin: 20rpx 0 0;
}

.progress-circle {
  width: 350rpx;
  height: 350rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  transition: all 0.3s ease;

  // 创建环形效果（中间透明）
  &::before {
    content: '';
    position: absolute;
    top: 60rpx;
    left: 60rpx;
    width: 230rpx;
    height: 230rpx;
    border-radius: 50%;
    background: #fff;
    z-index: 1;
  }
}

.progress-text {
  font-size: 32rpx;
  font-weight: bold;
  z-index: 2;
  position: relative;
}

.progress-legend {
  display: flex;
  justify-content: center;
  gap: 40rpx;
  margin: 20rpx 0;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  color: #333;
  font-size: 28rpx;
}

.legend-dot {
  width: 50rpx;
  height: 20rpx;
  border-radius: 20rpx;

  &.completed {
    background: #4db680;
  }

  &.pending {
    background: #df5548;
  }
}

.statistics-uncheck-list {
  width: 100%;
  height: calc(100% - 94rpx);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 24rpx;

  .list-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    background: #ffffff;
    border-radius: 4rpx;
    border: 2rpx solid #edeef0;
    box-sizing: border-box;
    padding: 14rpx 32rpx;

    .list-item-title {
      font-size: 34rpx;
      font-weight: 500;
      color: #333333;
      margin-left: 10rpx;
    }

    .list-item-content {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      font-size: 30rpx;
      font-weight: 500;
      color: #333333;
      gap: 5rpx;
    }
  }
}

.statistics-all-checked {
  text-align: center;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .statistics-all-checked-title {
    font-size: 38rpx;
    width: 80%;
    margin: 0 auto;
    border-bottom: 2rpx solid #e6e6e6;
    padding-bottom: 20rpx;
  }

  // 统计信息样式
  .stats-section {
    padding: 40rpx;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    width: 100%;

    .stat-item {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #333;

      .stat-label {

        text-align: right;
        flex: 1;
        margin-right: 20rpx;
      }

      .stat-value {
        flex: 1;
        text-align: left;

      }
    }
  }
}

.isNotInTime {
  width: calc(100% - 40rpx);
  height: calc(100% - 40rpx);
  background: #fff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 4rpx;
  border: 2rpx solid #ebecec;
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  box-sizing: border-box;

  .isNotInTime-title {
    color: #333;
    font-weight: 500;
    font-size: 38rpx;
    text-align: center;
    flex: 3;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 30rpx;
  }

  .isNotInTime-content {
    flex: 7;
    border-radius: 4rpx;
    background: #f9fafb;
    padding: 0 30rpx;

    .isNotInTime-content-title {
      font-size: 36rpx;
      color: #333333;
      font-weight: 400;
      margin: 30rpx 0;

    }

    .isNotInTime-content-item {
      font-size: 36rpx;
      color: #333333;
      font-weight: 400;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      background: #fff;
      padding: 20rpx 30rpx;
      box-sizing: border-box;
      border-radius: 4rpx;
      margin-bottom: 30rpx;
      gap: 30rpx;

      .isNotInTime-content-item-icon {
        width: 120rpx;
        text-align: center;
      }
    }
  }
}
</style>