<template>
  <view class="course-item-container">
    <u-card :show-head="false" margin="0">
      <template #body>
        <view>
          <view class="body">
            <view>
              <view class="course-header">
                {{ courseItem.courseName }}
              </view>
              <view class="item">
                <u-icon size="32" name="account" />
                <block v-for="(item, i) in courseItem.Teachs">
                  <text style="color: #04a7ff" @tap="toSeeMore"
                    >&nbsp;{{ item.teachName }}&nbsp;</text
                  >
                </block>
              </view>
              <view class="item">
                <u-icon size="34" name="map" />
                <text>&nbsp;{{ courseItem.classArea }}</text>
              </view>
              <view class="item">
                <u-icon size="34" name="clock" />
                <text
                  >&nbsp;{{
                    dayjs(courseItem.startDate).format("YYYY-MM-DD")
                  }}&nbsp;&nbsp;
                  {{
                    dateFormat(courseItem.startDate) +
                    "~" +
                    dateFormat(courseItem.endDate)
                  }}</text
                >
              </view>
            </view>
            <view class="courseware">
              <view>
                <u-badge
                  type="error"
                  size="mini"
                  :count="courseItem.FileCount"
                  :offset="[-4, -4]"
                ></u-badge>
                <u-icon
                  name="file-text-fill"
                  color="#05a8ff"
                  size="40"
                  class="courseware-icon"
                  @tap="openInfo"
                ></u-icon>
              </view>
              <view class="desc">课程资料</view>
            </view>
          </view>
        </view>
        <view
          v-show="current == 2 && isEnd"
          class="course-footer"
          style="margin-top: 32rpx"
        >
          <view>所属班级：{{ courseItem.Management[0]?.className }}</view>
          <view v-show="current == 2 && !courseItem.iEevaluate">
            <!-- <text v-show="current == 2" @tap="toEvaluate">{{
              props.courseItem.iEevaluate ? "查看评价" : "去评价"
            }}</text> -->
            <text @tap="toEvaluate" style="margin-right: 6rpx">去评价</text>
            <u-icon name="arrow-right-double" color="#04a7ff" size="24" />
          </view>
          <!-- <view @tap="toSeeMore">
            <text>查看更多</text>
            <u-icon name="arrow-right-double" color="#2979ff" size="24" />
          </view> -->
        </view>
      </template>
      <template #foot>
        <view class="course-footer">
          <view>所属班级：{{ courseItem.Management[0]?.className }}</view>
        </view>
        <u-collapse v-show="current == 2 && !isEnd">
          <u-collapse-item title="" @change="collapseChange">
            <template #title-all>
              <view class="collapse-item">
                <text :style="{ color: attendanceStatus?.color }">{{
                  attendanceStatus?.status
                }}</text>
                <view>
                  出勤情况
                  <!-- arrow-up -->
                  <u-icon name="arrow-down" size="24" />
                </view>
              </view>
            </template>
            <template #default>
              <view class="line">
                <view class="line-content">
                  <text>上课签到：</text>
                  <view style="margin-bottom: 20rpx">
                    <text>{{ singInStatus }}</text>
                  </view>
                </view>
                <view class="line-content">
                  <text>下课签退：</text>
                  <view style="margin-bottom: 20rpx">
                    <text>{{ singOutStatus }}</text>
                  </view>
                </view>
              </view>
            </template>
          </u-collapse-item>
        </u-collapse>
      </template>
    </u-card>

    <view v-if="!current || (current == 2 && isEnd)">
      <u-card
        :show-head="false"
        :show-foot="false"
        :border="false"
        margin="20rpx 0 0 0"
      >
        <template #body>
          <view class="signInInfo">
            <view class="header">
              <view class="time">
                <text>上课 {{ dateFormat(courseItem.startDate) }}</text>
                <text :style="{ color: infoState.classColor }">{{
                  infoState.classStatus
                }}</text>
              </view>
              <view class="time">
                <text>下课 {{ dateFormat(courseItem.endDate) }}</text>
                <text :style="{ color: infoState.endOfClassColor }">{{
                  infoState.endOfClassStatus
                }}</text>
              </view>
            </view>

            <view class="main">
              <view
                class="sign"
                :class="infoState.signClass"
                @tap="tapSignIn"
                >{{ signInStatus }}</view
              >
              <view v-if="isRange" class="addr">
                <text>已进入范围：{{ mapsInfo.addr }}</text>
                <u-image
                  width="32rpx"
                  height="32rpx"
                  src="../../../static/img/refresh.png"
                  @tap="initQqMaps"
                ></u-image>
              </view>
              <view v-else class="addr">
                <text style="color: #ff0606"
                  >不在签到范围：{{ mapsInfo.addr }}</text
                >
                <text @tap="initQqMaps">刷新</text>
              </view>
            </view>
          </view>
        </template>
      </u-card>

      <view class="class-teacher item">
        <text>班主任：</text>
        <view style="display: flex; flex-wrap: wrap; flex: 1">
          <u-button
            v-for="(item, index) in courseItem.Management"
            :key="index"
            size="mini"
            shape="circle"
            hover-class="background-color: #04a7ff; color: #ffffff"
            style="background-color: #04a7ff; color: #ffffff"
            @tap="callPhone($event, item.teachPhone)"
            ><u-icon name="phone" size="30" style="margin-right: 10rpx" />
            {{ item.mgtName }}</u-button
          >
        </view>
      </view>
      <view class="prompt">
        <u-icon name="info-circle" />
        提示:需要请假或补签请联系班主任
      </view>
    </view>
  </view>
  <infoPopup
    ref="infoRef"
    v-model:show="infoState.show"
    :courseNumber="props.courseItem.courseNumber"
  />
</template>

<script setup lang="ts">
import infoPopup from "./infoPopup.vue";
import dayjs from "dayjs";
import useQqMaps from "@/utils/QqMaps";
import { signInAndOut } from "@/api/course";
import { useCourseStore } from "@/stores/modules/courseStore";
import { useStudentStore } from "@/stores/modules/studentStore";
import { callPhone } from "@/utils/util";

const props = defineProps({
  courseItem: {
    type: Array,
    default: () => [] as any,
  } as any,
  current: {
    type: Number,
    default: 0,
  },
});

const isRange = ref(true);
const infoRef = ref();
const courseStore = useCourseStore();
const globalStore = useStudentStore();

const emits = defineEmits(["openInfo", "init"]);

const { initQqMaps, mapsInfo, calculateDistance } = useQqMaps();

const infoState = reactive({
  show: false,
  classStatus: "",
  endOfClassStatus: "",
  classColor: "",
  endOfClassColor: "",
  signClass: "primary-sign",
});

const collapseShow = ref(false);

// 出勤状态
const tagList = [
  { color: "#04A7FF", status: "正常出勤" },
  { color: "#FF0606", status: "缺勤" },
  { color: "#5363FF", status: "未签退" },
  { color: "#5363FF", status: "请假" },
  { color: "#5363FF", status: "请假" },
  { color: "#19be6b", status: "正常出勤" },
  { color: "#19be6b", status: "正常出勤" },
  // { color: "#5363FF", status: "未签到" },
];

const attendanceStatus = computed(() => {
  if (props.current !== 2) return;

  const { SingIn, SingInText, SingOut, SingOutText }: any = props.courseItem
    .State.length
    ? props.courseItem.State[0]?.Value[0]
    : {};

  const conditions: any = {
    "QD-QT": tagList[0],
    "QD-": tagList[2],
    "QDQJ-": tagList[3],
    "QD-QTQJ": tagList[4],
    "QDBQ-": tagList[1],
    "QD-QTBQ": tagList[6],
    "QDBQ-QTBQ": tagList[6],
    // "-QT": tagList[7],
  };

  const key = `${SingIn || ""}-${SingOut || ""}`;

  let data = conditions.hasOwnProperty(key) ? conditions[key] : tagList[1];
  data = { ...data, SingInText, SingOutText };
  return data;
});

const singInStatus = computed(() => {
  if (!props.courseItem.State.length) {
    return "未签到";
  }

  const singIn = props.courseItem.State[0].Value[0].SingIn;
  switch (singIn) {
    // case "QDBQ":
    //   return "已补签";
    case "QD":
    case "QDBQ":
      return "已签到";
    case "QDQJ":
      return "签到请假";
    default:
      return "未签到";
  }
});

const singOutStatus = computed(() => {
  if (!props.courseItem.State.length) {
    return "未签退";
  }

  // const singIn = props.courseItem.State[0].Value[0].SingIn;
  // if (singIn === "QDBQ") {
  //   return "已签退";
  //   // return "已补签";
  // }

  const singOut = props.courseItem.State[0].Value[0].SingOut;
  switch (singOut) {
    // case "QTBQ":
    //   return "已补签";
    case "QT":
    case "QTBQ":
      return "已签退";
    case "QTQJ":
      return "签退请假";
    default:
      return "未签退";
  }
});

// 判断时间间隔
const timeInterval = (startDate: any, currentDate: any) => {
  const minutesDifference = currentDate.diff(startDate, "minutes");
  return Math.abs(minutesDifference);
};

const currentDate = dayjs(); // 当前时间
const startDate = dayjs(props.courseItem.startDate); // 课程开始时间
const endDate = dayjs(props.courseItem.endDate); // 课程结束时间
const isSignOut = props.courseItem.isSignOut; // 是否开放签退
const timeUntilEnd = timeInterval(currentDate, endDate); // 当前时间距离课程结束时间（分钟）

// 是否为已下课
const isEnd = computed(() => {
  return timeUntilEnd <= 30 || (isSignOut && endDate.isAfter(currentDate));
});

// 签到按钮的显示状态
const signInStatus = computed(() => {
  if (props.current === 1) return;
  let signInStr = "";
  let signClass = "info-sign";

  // 签到
  const minutesDifference = timeInterval(startDate, currentDate);
  // 表示 Day.js 对象是否在另一个提供的日期时间之后
  if (startDate.isAfter(currentDate)) {
    // 当前时间早于上课时间
    if (minutesDifference <= 30) {
      signInStr = "点击签到";
      signClass = "success-sign";
    } else {
      signInStr = `${minutesDifference}分钟后签到`;
    }
  } else {
    // 当前时间晚于上课时间 超出30分钟时间停止签到
    if (minutesDifference <= 30) {
      signInStr = "点击签到";
      signClass = "success-sign";
    } else {
      infoState.classStatus = "未签到";
      infoState.classColor = "#f29100";
      signInStr = "未签到";
    }
  }

  if (props.courseItem.State[0]?.Value[0].SingIn == "QD") {
    signInStr = "签到成功";
    signClass = "primary-sign";
    infoState.classStatus = "已签到";
    infoState.classColor = "#18b566";
  }

  // 签退
  // let endOfClassStatus: any = calculateEndOfClassStatus(endDate, currentDate);
  // 这表示 Day.js 对象是否在另一个提供的日期时间之前
  const minutesDifference1 = timeInterval(endDate, currentDate);

  // if (minutesDifference1 <= 30 && signInStr !== "未签到") {
  if (
    (minutesDifference1 <= 30 || props.courseItem?.isSignOut) &&
    signInStr !== "未签到"
  ) {
    signInStr = "点击签退";
    signClass = "success-sign";
  }
  if (props.courseItem.State[0]?.Value[0].SingOut == "QT") {
    infoState.endOfClassStatus = "已签退";
    infoState.endOfClassColor = "#18b566";
    signInStr = "签退成功";
    signClass = "primary-sign";
  }

  const Longitude = props.courseItem.Longitude.split(",");
  // 计算打卡地址与自己位置的距离
  const distance = calculateDistance(
    Longitude[0],
    Longitude[1],
    mapsInfo.lat,
    mapsInfo.lng
  );

  if (distance > Number(props.courseItem.Scope.split("米")[0])) {
    isRange.value = false;
    infoState.endOfClassColor = "#7d8286";
    signClass = "info-sign";
  } else isRange.value = true;
  infoState.signClass = signClass;
  return signInStr;
});

const toEvaluate = () => {
  uni.navigateTo({
    url:
      "/pages/course/evaluate?courseNumber=" +
      props.courseItem.courseNumber +
      "&classNumber=" +
      props.courseItem.classNumber +
      "&iEvaluate=" +
      props.courseItem.iEevaluate +
      "&courseId=" +
      props.courseItem.courseId +
      "&ItemNumber=" +
      props.courseItem.ItemNumber,
  });
};

// 判断课程状态
const calculateEndOfClassStatus = (endDate: any, currentDate: any) => {
  let endOfClassStatus = "";
  if (
    endDate.isAfter(currentDate) &&
    timeInterval(endDate, currentDate) <= 30
  ) {
    endOfClassStatus = "点击签退";
  } else if (
    endDate.isBefore(currentDate) &&
    timeInterval(endDate, currentDate) >= 10
  ) {
    endOfClassStatus = "未签退";
  }
  return endOfClassStatus;
};

const dateFormat = (dateStr: string) => {
  // 创建一个日期对象，传入特定日期和时间
  const date = new Date(dateStr);
  // 获取小时和分钟
  const hours = ("0" + date.getHours()).slice(-2);
  const minutes = ("0" + date.getMinutes()).slice(-2);

  // 构建时间字符串
  const time = hours + ":" + minutes;
  return time;
};

// 点击签到签退
const tapSignIn = async () => {
  if (infoState.signClass == "info-sign") return;
  if (signInStatus.value == "点击签到" || signInStatus.value == "点击签退") {
    let data = {
      parmeters: {
        NeedReturnFields: ["FID"],
        IsDeleteEntry: "false",
        Model: {
          FCourseId: {
            FNUMBER: props.courseItem.courseNumber, //课程编码
          },
          FClassId: {
            FNUMBER: props.courseItem.classNumber, //班级编码
          },
          FStudentId: {
            FNUMBER: globalStore.infoData.FNUMBER, //学员编码
          },
          FDate: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"), //打卡时间
          FLocation: mapsInfo.addr, //打卡地点
          FLocationDetails: mapsInfo.lng + "," + mapsInfo.lat, //经纬度
          FCockinType: "QD", //打卡类型 QD:签到,QT:签退:BK:补卡
        },
      },
    };
    if (signInStatus.value == "点击签到")
      data.parmeters.Model.FCockinType = "QD";
    else data.parmeters.Model.FCockinType = "QT";
    const { data: res }: any = await signInAndOut(data);
    if (res.code == 200) {
      // console.log(res)
      emits("init", props.current);
    }
  }
};

// 查看更多
const toSeeMore = () => {
  courseStore.setTeachs(props.courseItem.Teachs);
  setTimeout(() => {
    uni.navigateTo({
      url: "/pages/course/seeMore",
    });
  }, 300);
};

const openInfo = () => {
  infoState.show = true;
  infoRef.value.init();
};

const collapseChange = (e: any) => {
  if (e.show) collapseShow.value = true;
  else collapseShow.value = false;
};
</script>

<style lang="scss" scoped>
.course-item-container {
  margin-top: 32rpx;

  :deep(.u-card__body) {
    padding: 40rpx 32rpx 34rpx !important;
  }
  :deep(.u-card__foot) {
    padding: 30rpx 32rpx 40rpx !important;
  }
  .body {
    position: relative;
    display: flex;
    justify-content: space-between;
  }

  h3 {
    margin-bottom: 32rpx;
  }

  .course-header {
    margin: 0 0 0 8rpx;
    font-size: 34rpx;
    font-weight: 500;
    color: #222222;
  }

  .item {
    margin: 24rpx 0;
    text {
      font-size: 28rpx;
      font-weight: 400;
      color: rgba(34, 34, 34, 0.9);
    }
  }

  & .item:last-child {
    margin-bottom: 0;
  }

  .course-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 24rpx;

    text {
      width: 72rpx;
      height: 34rpx;
      font-weight: 400;
      color: #04a7ff;
    }
  }

  .u-collapse-item {
    background-color: #ddf3ff;
    border-radius: 24rpx;

    :deep(.u-collapse-head) {
      padding: 0;
      margin-top: 30rpx;
    }

    :deep(.u-collapse-content) {
      padding: 20rpx;
    }

    .collapse-item {
      display: flex;
      justify-content: space-between;
      width: 100%;
      padding: 32rpx;
      background-color: #ddf3ff;
      border-radius: 24rpx;

      view {
        color: #2979ff;
        font-size: 24rpx;
      }
    }
    .line {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .line-content {
        display: flex;
        text {
          font-size: 28rpx;
          font-weight: 400;
          color: rgba(34, 34, 34, 0.8);
        }
      }
    }
  }

  .signInInfo {
    margin-bottom: 20rpx;

    .header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 100rpx;

      .time {
        display: flex;
        align-items: center;
        padding: 10rpx;
        font-size: 28rpx;
        width: 47%;
        height: 90rpx;
        color: #000;
        background: #efefef;
        border-radius: 8rpx;

        text {
          display: block;
        }

        text:nth-child(2) {
          color: $u-type-success;
          font-size: 24rpx;
          margin-left: 20rpx;
        }
      }
    }

    .main {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;

      .sign {
        width: 292rpx;
        height: 292rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 40rpx;
        cursor: pointer;
        margin-bottom: 48rpx;
        font-size: 34rpx;
        font-weight: 500;
        color: #ffffff;
      }

      .info-sign {
        background: linear-gradient(
          180deg,
          rgba(226, 226, 226, 0.85) 0%,
          #adadaf 100%
        );
        box-shadow: 0rpx 8rpx 12rpx 0rpx rgba(0, 0, 0, 0.04);
      }

      .success-sign {
        background: linear-gradient(180deg, #ddffd8 0%, #53af28 100%);
        box-shadow: 0rpx 8rpx 12rpx 0rpx rgba(109, 162, 84, 0.1);
      }

      .primary-sign {
        background: linear-gradient(180deg, #ddf1ff 0%, #04a7ff 100%);
        box-shadow: 0rpx 8rpx 12rpx 0rpx rgba(4, 153, 235, 0.2);
      }

      .addr {
        font-size: 24rpx;
        display: flex;

        .u-image {
          margin-top: 3rpx;
        }
        text {
          margin-right: 10rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: rgba(34, 34, 34, 0.5);
        }

        text:nth-child(2) {
          color: #1890ff;
        }
      }
    }
  }

  .class-teacher {
    display: flex;
    align-items: flex-start;
    text {
      width: 140rpx;
    }
    .u-tag {
      margin-right: 20rpx;
    }
  }

  .prompt {
    font-size: 24rpx;
    color: $u-type-info-dark;
  }
}
</style>
