<template>
  <template>
    <Container
      class="body-content"
      title="首页"
      bgColor="#F8F8F8"
      :showBack="false"
    >
      <view class="home">
        <!-- 倒计时 -->
        <view class="time" v-if="(splitDays != '') & (splitDays != null)">
          <view>距离2025年考试倒计时</view>
          <!-- 将天数拆分为单个数字显示 -->
          <view
            class="exam-countdown-tiem-item"
            v-for="(digit, index) in splitDays"
            :key="index"
            >{{ digit }}</view
          >
          <view>天</view>
        </view>
        <!-- 轮播图 -->
        <swiper
          class="swiper"
          :style="{
            height: imgHeight,
          }"
          circular
          autoplay
        >
          <swiper-item v-for="(item, index) in banner_list" :key="index">
            <view class="swiper-item"
              ><image
                class="swiper-item-image"
                :src="item.image_url"
                mode="aspectFill"
                @load="onImageLoad($event, item, index)"
                @click="goto_notice_list(item.link_url)"
              ></image
            ></view>
          </swiper-item>
        </swiper>
        <!-- 公告 -->
        <view class="notice" v-if="notice_list != '' && notice_list != null">
          <view class="title-lable">公告</view>
          <view class="notice-title">{{ notice_list[0]["title"] }}</view>
          <navigator url="/pages/notice/list">
            <view class="notice-more">{{ "更多 >" }}</view>
          </navigator>
        </view>
        <div class="qiandao">
          <div class="left">
            <span class="text-16" style="font-weight: bold">每日一练</span>
            <span class="text-12 text-t9"
              >今日已有<span class="text-primary">{{ total }}</span
              >人打卡</span
            >
          </div>
          <div
            class="bt"
            :style="{
              backgroundColor: !success ? '#FF6666' : '#3FCCFF',
            }"
            @click="onClickToPunch"
          >
            {{ !success ? "今日未打卡" : "今日已打卡" }}
          </div>
        </div>
        <!-- 2025新大纲 -->
        <view class="new_outline">
          <uni-section title="执业药师章节练习" type="line">
            <template v-for="(item, index) in list" :key="item.id">
              <view v-if="current === index" class="grid">
                <view
                  v-for="i in item?.children"
                  :key="i.id"
                  class="flex"
                  @click="clickClass(i)"
                >
                  <image :src="i.chapter_image_url" class="img_small"></image>
                  <view>{{ i.name }}</view>
                </view>
              </view>
            </template>
          </uni-section>
        </view>
        <div class="flex-box">
          <div
            class="children lishi"
            @click="
              router.push({
                url: '/pages/index/yearExam',
              })
            "
          >
            <div>往年真题</div>
            <div class="te">10年真题卷</div>
            <div class="cricle">{{ ">" }}</div>
          </div>
          <div
            class="children gaopin"
            @click="
              router.push({
                url: '/pages/index/highFire',
              })
            "
          >
            <div>高频考点</div>
            <div class="te">经典拿分题</div>
            <div class="cricle">{{ ">" }}</div>
          </div>
        </div>

        <!-- #ifdef  MP-WEIXIN -->
        <official-account @load="onload"></official-account>
        <!-- #endif -->
      </view>
    </Container>
    <view class="service">
      <CustomerService>联系客服</CustomerService>
    </view>
  </template>
  <Modal title="ces" :footer="false" v-model:open="showModal">
    <template #custom>
      <view class="mo">
        <uni-icons
          type="closeempty"
          class="icons"
          color="#fff"
          @click="showModal = false"
        ></uni-icons>
        <div class="bgt">
          <span>恭喜您获得7天会员</span>
          <span>可以免费学习所有课程以及练习题库</span>
          <span style="margin-top: 71rpx">戳下方还可以</span>
          <span>添加专属助教老师为您答疑解惑</span>
          <span>限时领取《药品速记口诀》</span>
          <span class="fixed" @click="receive"></span>
        </div>
      </view>
    </template>
  </Modal>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from "vue";

import Container from "../../components/Container/Container.vue";
import CustomerService from "../../components/CustomerService/CustomerService.vue";
import Modal from "../../components/Modal/Modal.vue";
import { router, getRoute } from "../../utils/router";
import { request } from "../../utils/request";
import { arrayToTree } from "../../utils";

const current = ref(0);
const list = ref([]);
const banner_list = ref([]);
const notice_list = ref([]);
const imgHeight = ref("auto"); // 初始高度
const showModal = ref(false);
const success = ref(false);

const onClickToPunch = () => {
  router.push({
    url: "/pages/learn/dayPractice",
    params: {
      title: "每日一练",
    },
  });
};
const days = ref("000"); // 默认值设为100，确保有3位数
let timer = null;
const exam_time = ref(""); //考试时间

const isLogin = () => {
  const userInfo = uni.getStorageSync("userLogin");
  return !!userInfo?.is_register;
};
const receive = () => {
  if (!isLogin()) {
    router.push("/pages/login/index");
    return;
  }
  showModal.value = false;
  setTimeout(() => {
    router.push("/pages/contant/sub");
  }, 0);
};
// 将天数拆分为单个数字数组
const splitDays = computed(() => {
  // 将数字转为字符串，然后拆分为字符数组
  const str = days.value.toString();
  // 如果不足3位数，前面补0（例如5变成["0","0","5"]）
  return str.padStart(3, "0").split("");
});
const onload = (e) => {
  console.log(e);
};

const calculateDays = () => {
  // const targetDate = new Date('2025-12-31');
  const targetDate = new Date(Number(exam_time.value * 1000));
  const currentDate = new Date();
  const diffTime = targetDate - currentDate;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  days.value = diffDays > 0 ? diffDays : 0;
};

const clickClass = ({ id, name }) => {
  router.push({
    url: "/pages/regulations/index",
    params: {
      id,
      title: name,
    },
  });
};

const onImageLoad = (e, item, index) => {
  const { width, height } = e.detail;
  const ratio = height / width;
  const systemInfo = uni.getSystemInfoSync();
  const imgHeightValue = systemInfo.windowWidth * ratio;
  imgHeight.value = imgHeightValue + "px";
};

onBeforeUnmount(() => {
  if (timer) clearInterval(timer);
});

const goto_notice_list = (link_url) => {
  uni.navigateTo({
    url: link_url,
  });
};

const total = ref(0);

onMounted(async () => {
  const params = getRoute().params;
  if (params.scene) {
    const p = params.scene.split("=");
    const value = p[1];
    uni.setStorageSync("share_uid", value);
  }
  const res = await request(
    "api/question_bank/question_reception/chapter/get",
    {},
    "POST"
  );
  list.value = arrayToTree({
    list: res.data,
  });
  // 首页轮播
  const banner_res = await request(
    "api/question_bank/question_reception/banner/list",
    { page: 1, limit: 10 },
    "POST"
  );
  banner_list.value = banner_res.data.data;
  //系统公告
  const notice_res = await request(
    "api/question_bank/question_reception/notice/list",
    { page: 1, limit: 1 },
    "POST"
  );
  notice_list.value = notice_res.data.data;
  //获取考试倒计时
  const examination_res = await request(
    "api/question_bank/question_reception/common_config/detail",
    { content_code: "examination_countdown" },
    "POST"
  );
  exam_time.value =
    examination_res != "" ? examination_res.data.content_detail : "";

  if (!isLogin()) {
    showModal.value = true;
  }

  request(
    "api/question_bank/question_reception/check_in/get_check_in_total"
  ).then((res) => {
    total.value = res.data.total;
  });

  request(
    "api/question_bank/question_reception/check_in/get_user_check_info"
  ).then((res) => {
    success.value = res.data.current_day_is_check;
  });

  calculateDays();
  timer = setInterval(() => {
    calculateDays();
  }, 24 * 60 * 60 * 1000);
  return {
    days,
    splitDays,
  };
});
</script>

<style scoped lang="scss">
// https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/06/kPFuCa2RDyoUXbiCzj0MOwcCm7XowJcWqNqs18oB.png 往年真题
// https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/06/WsEF9w5bs7Gknnf3vUV3EMR0WxqleESpYSVxZtkn.png 高频考点
@import "@/uni.scss";

.flex-box {
  display: flex;
  align-items: center;
  gap: 10rpx;
  .children {
    flex: 1;
    height: 173rpx;
    width: 100%;
    padding: 24rpx 12rpx;
    box-sizing: border-box;
    color: #333333;
  }

  @mixin text($bg) {
    .te {
      color: $bg;
      font-weight: 400;
      font-size: 24rpx;
    }

    .cricle {
      width: 32rpx;
      height: 32rpx;
      background: $bg;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      border-radius: 50%;
      font-size: 20rpx;
      margin: 14rpx 0 0 8rpx;
    }
  }

  .lishi {
    background: url(https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/06/kPFuCa2RDyoUXbiCzj0MOwcCm7XowJcWqNqs18oB.png);
    background-size: 100% 100%;
    @include text(#00a3ff);
  }
  .gaopin {
    background: url(https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/06/WsEF9w5bs7Gknnf3vUV3EMR0WxqleESpYSVxZtkn.png);
    background-size: 100% 100%;
    @include text(#ff6a00);
  }
}
.qiandao {
  background: url(https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/06/hASs5yhNTWUMTAGdod21hDIcibFNFSDTbiGpEMd0.png)
    no-repeat;
  background-size: 100% 100%;
  width: 100%;
  height: 104rpx;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 10rpx 16rpx;
  align-items: center;
  .left {
    display: flex;
    flex-direction: column;
    gap: 4rpx;
  }

  .bt {
    width: 188rpx;
    height: 55rpx;
    background: #ff6666;
    border-radius: 200rpx 200rpx 200rpx 200rpx;
    font-weight: 400;
    font-size: 28rpx;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.mo {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  width: 658rpx;

  .icons {
    background: #8a8a8b;
    width: 48rpx;
    height: 48rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .bgt {
    width: 658rpx;
    height: 766rpx;
    position: relative;
    background: url(https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/06/p3qrAPK10tNFOfwy27yryTtwEOsE8x40V0wFvbOW.png);
    background-size: 100% 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-weight: 600;
    font-size: 32rpx;
    color: #8b3700;
    gap: 16rpx;
    box-sizing: border-box;
    padding-top: 161rpx;
  }

  .fixed {
    position: absolute;
    width: 348rpx;
    height: 86rpx;
    bottom: 30rpx;
  }
}
.service {
  position: absolute;
  bottom: 20%;
  right: 5%;
  color: $uni-primary;
  font-size: 28rpx;
  margin-bottom: 40rpx;
  text-align: right;
}
.img_small {
  width: 112rpx;
  height: 112rpx;
}
.body-content {
  background: #f8f8f8;
  border-radius: 0rpx 0rpx 0rpx 0rpx;
}
.exam-countdown-tiem-item {
  width: 24rpx;
  height: 34rpx;
  background: #ff3c3c;
  border-radius: 2rpx 2rpx 2rpx 2rpx;
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  font-size: 24rpx;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.home {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  .time {
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 24rpx;
    color: #333333;
    gap: 8rpx;

    .tiem-item {
      width: 24rpx;
      height: 34rpx;
      background: #ff3c3c;
      border-radius: 2rpx 2rpx 2rpx 2rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 24rpx;
      color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .swiper {
    width: 100%;
    /* 关键修复样式 */
    overflow: hidden;
    transform-style: preserve-3d;

    .swiper-item {
      width: 100%;
      height: 100%;
      overflow: hidden;
      border-radius: 30rpx;
      /* 确保变换不影响子元素 */
      transform: translateZ(0);

      .swiper-item-image {
        width: 100%;
        height: 100%;
        display: block;
        border-radius: 30rpx;
        /* 防止图片变形 */
        object-fit: cover;
        /* 确保层级 */
        position: relative;
      }
    }
  }

  .notice {
    display: flex;
    align-items: center;
    gap: 20rpx;
    padding-left: 26rpx;
    height: 72rpx;
    background: #ffffff;
    border-radius: 500rpx 500rpx 500rpx 500rpx;
    border: 1rpx solid #f8f8f8;
    .title-lable {
      padding: 5rpx 15rpx;
      border-radius: 8rpx 8rpx 8rpx 8rpx;
      border: 1rpx solid #3f75ff;
      font-weight: 500;
      font-size: 26rpx;
      color: #3f75ff;
      line-height: 32rpx;
      text-align: center;
      font-style: normal;
      text-transform: none;
    }
    .notice-title {
      width: calc(100% - 225rpx);
      color: #333;
      font-size: 26rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 1;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .notice-more {
      font-size: 26rpx;
    }
  }
}

.title {
  font-family: "PingFang SC, PingFang SC";
  font-weight: 700;
  font-size: 32rpx;
  color: #000000;
}

.p-20 {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  background-color: #ffffff;
  padding: 24rpx;
  gap: 16rpx;
  border-radius: 16rpx;
}

.grid-3 {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  background-color: #ffffff;
  padding: 24rpx;
  gap: 16rpx;
  border-radius: 16rpx;
  height: 100%;
  margin-bottom: 20rpx;
}

.flex {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  align-items: center;
  justify-content: center;
}

.bg-red {
  width: 191.07rpx;
  height: 179.61rpx;
  background: url("https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/05/WmhlbORF2q8A62Ytg1RVac8AYSGPkf7F2pEY6jQP.png")
    no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;

  .text {
    font-family: jiangxizhuokai, jiangxizhuokai;
    font-weight: bold;
    font-size: 27rpx;
    color: #3f75ff;
    text-shadow: 0px 2px 4px #bdcfff;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-top: 16rpx;
    width: 95rpx;
    height: 70rpx;
  }
}
</style>
