<template>
  <view
    style="display: flex; justify-content: space-between; align-items: center"
    @click="getVideo"
  >
    <view
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 20rpx 0;
        width: 100%;
      "
    >
      <view style="display: flex; align-items: center; flex: 1">
        <view class="tag tagColor1" v-if="menuItem.sectionType == 1">视频</view>
        <view class="tag tagColor2" v-if="menuItem.sectionType == 2">直播</view>
        <view class="tag tagColor3" v-if="menuItem.sectionType == 3">回放</view>
        <view class="t_content">
          <view
            v-if="menuItem.sectionType == 1"
            :class="{ color1: isActive }"
            >{{ menuItem.name || "" }}</view
          >
          <view
            v-if="menuItem.sectionType == 2"
            :class="{ color2: isActive }"
            >{{ menuItem.name || "" }}</view
          >
          <view
            v-if="menuItem.sectionType == 3"
            :class="{ color3: isActive }"
            >{{ menuItem.name || "" }}</view
          >
          <view
            style="font-size: 20rpx; color: #ff3b30"
            v-if="menuItem.sectionType == 2 && menuItem.liveStartTime"
          >
            <view v-if="menuItem.liveStartTime > nowTime || !isBuy">
              <text>{{
                $method.timestampToTime(menuItem.liveStartTime, (isDay = false))
              }}</text
              >-
              <text>{{
                $method.timestampToTime(menuItem.liveEndTime, (isDay = false))
              }}</text>
            </view>
            <template v-if="isLast()">
              <view v-if="liveLast.watchStatus == 'live'">
                <text>直播中</text>
              </view>
              <view v-if="liveLast.watchStatus == 'end'">
                <text>当前直播回放视频请稍后再查看</text>
              </view>
            </template>
          </view>
          <view
            style="font-size: 20rpx; color: #ff3b30"
            v-if="menuItem.sectionType == 3"
          >
            <view v-if="!menuItem.recordingUrl">
              <text>当前直播回放视频请稍后再查看</text>
            </view>
            <view v-else> 回放中 </view>
          </view>
        </view>
        <view v-if="menuItem.sectionType == null">{{
          menuItem.name || ""
        }}</view>
        <!-- 学习中 -->
        <view v-if="isActive" class="learnings">
          <image
            src="/pages3/static/imgs/learning_icon.gif"
            class="learning_icon"
          ></image>
        </view>
      </view>
      <view
        style="font-size: 20rpx; color: #ff3b30"
        v-if="menuItem.liveStartTime && menuItem.sectionType != 3 && isBuy"
      >
        <template v-if="!isLast() && !isLive">
          <view class="tagWillPlay" v-if="menuItem.liveStartTime > nowTime">
            <text>待开播</text>
          </view>
          <view
            class="tagPlaying"
            v-if="
              menuItem.liveStartTime <= nowTime &&
              menuItem.liveEndTime > nowTime
            "
          >
            <text>直播中</text>
          </view>
          <view class="tagPlayed" v-if="menuItem.liveEndTime < nowTime">
            <text>已结束</text>
          </view>
        </template>
      </view>
      <!-- 直播课程没有学习状态 -->
      <template v-if="!isLive">
        <view v-if="isRebuild || menuItem.rebuild > 0" class="tagRe"
          >待重修</view
        >
        <view v-else>
          <view v-if="menuItem.learning == 1" class="tagGreen">已学完</view>
        </view>
      </template>

      <view
        v-if="checkTest()"
        class="exercises"
        @click.stop="toDoSectionExam()"
      >
        <text class="exe_w">习题</text>
        <u-icon name="arrow-right" color="#498AFE" size="28"></u-icon>
      </view>
    </view>
    <view v-if="isTryListen" class="tryBox"> 试看 </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "courseSection",
  inject: ["paramsFn"],
  props: {
    isLive: false, //是否是直播课
    preItem: {
      default: undefined,
    },

    menuItem: {
      type: Object,
      default: {},
    },
    isBuy: {
      type: Boolean,
      default: false,
    },
    levelId: {
      type: String,
      default: "",
    },
    isRebuild: {
      type: Boolean,
      default: false,
    },

    nextMenuItem: {
      type: Object,
      default: () => {
        return {};
      },
    },
    sectionMaxNum: {
      default: undefined,
    },
    // 章->所有节试卷列表
    ChapterSectionExam: {
      type: Array,
      default: () => [],
    },
    // 区分是模块试卷还是章试卷，3是模块试卷
    testType: {
      type: Number,
      default: 0,
    },
  },
  watch: {
    menuItem(val) {
      console.log(val, "val");
    },
  },
  data() {
    return {
      nowTime: 0,
      playId: "",
      clickLock: false, //点击锁，防止连续点击多次
      moduleSectionExam: [], // 模块下的所有节试卷列表
      chapterExams: {},
      moduleExams: {},
      // newMenuAllList: [],
    };
  },
  onLoad() {},
  created() {
    if (this.testType == 3) {
      // 模块下的所有节试卷列表
      this.$api
        .reSectionExamList({
          chapterId: 0,
          courseId: this.courseId,
          gradeId: this.gradeId,
          orderGoodsId: this.orderGoodsId,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.moduleSectionExam = res.data.data || [];
          }
        });
    }
  },
  mounted() {
    this.nowTime = Number(new Date().getTime() / 1000).toFixed(0);

    this.isBuy &&
      uni.$on("playEnd", () => {
        console.log("结束了");
        if (this.isActive) {
          this.$emit("playEnd");
        }
      });
  },
  methods: {
    isLast() {
      if (this.liveLast) {
        let sectionASame =
          this.liveLast.sectionId ==
          (this.menuItem.sectionId || this.menuItem.menuId);
        let chapterSame =
          this.liveLast.chapterId == (this.menuItem.chapterId || 0);
        let moduleSame =
          this.liveLast.moduleId == (this.menuItem.moduleId || 0);
        return sectionASame && chapterSame && moduleSame;
      } else {
        return false;
      }
    },
    toDoSectionExam() {
      if (this.testType == 3) {
        this.ModuleExam();
      } else {
        this.ChapterExam();
      }
    },
    checkTest() {
      let data =
        this.testType == 3 ? this.moduleSectionExam : this.ChapterSectionExam;
      let id =
        this.testType == 3 ? this.menuItem.menuId : this.menuItem.sectionId;
      if (!data) {
        return false;
      }
      return data.some((e) => e.sectionId == id);
    },
    ChapterExam() {
      this.chapterExams = this.ChapterSectionExam.find(
        (e) => e.sectionId == this.menuItem.sectionId
      );
      let moduleId = this.chapterExams.moduleId || 0;
      let chapterId = this.chapterExams.chapterId || 0;
      let sectionId = this.chapterExams.sectionId || this.chapterExams.menuId;
      uni.navigateTo({
        url:
          "/pages2/class/questionBank?courseId=" +
          this.courseId +
          "&gradeId=" +
          this.gradeId +
          "&isFromVideo=1&id=" +
          this.chapterExams.typeId +
          "&goodsid=" +
          this.goodsId +
          "&moduleId=" +
          moduleId +
          "&chapterId=" +
          chapterId +
          "&sectionId=" +
          sectionId +
          "&orderGoodsId=" +
          this.orderGoodsId +
          "&type=2",
      });
    },
    ModuleExam() {
      let sectionId = this.menuItem.sectionId || this.menuItem.menuId;
      this.moduleExams = this.moduleSectionExam.find(
        (e) => e.sectionId == sectionId
      );
      let moduleId = this.moduleExams.moduleId || 0;
      let chapterId = this.moduleExams.chapterId || 0;

      uni.navigateTo({
        url:
          "/pages2/class/questionBank?courseId=" +
          this.courseId +
          "&gradeId=" +
          this.gradeId +
          "&isFromVideo=1&id=" +
          this.moduleExams.typeId +
          "&goodsid=" +
          this.goodsId +
          "&moduleId=" +
          moduleId +
          "&chapterId=" +
          chapterId +
          "&sectionId=" +
          sectionId +
          "&orderGoodsId=" +
          this.orderGoodsId +
          "&type=2",
      });
    },
    gradeCheckGoodsStudy() {
      return new Promise((resolve) => {
        this.$api
          .gradeCheckGoodsStudy({
            goodsId: this.goodsId,
            gradeId: this.gradeId,
            moduleId: this.menuItem.moduleId || 0,
            chapterId: this.menuItem.chapterId || 0,
            sectionId: this.menuItem.sectionId || this.menuItem.menuId,
            orderGoodsId: this.orderGoodsId,
          })
          .then((res) => {
            resolve(res.data.data);
          });
      });
    },
    goodsTodayStudySectionNum() {
      return new Promise((resolve) => {
        this.$api
          .goodsTodayStudySectionNum({
            goodsId: this.goodsId,
            gradeId: this.gradeId,
            orderGoodsId: this.orderGoodsId,
          })
          .then((res) => {
            if (res.data.code == 200) {
              resolve(res.data.data);
            }
          });
      });
    },
    getVideo() {
      if (this.clickLock) {
        return;
      }
      if (this.$method.isGoLogin()) {
        return;
      }
      if (this.menuItem.id == this.sectionId) {
        return;
      }
      this.clickLock = true;
      // && !this.menuItem.isRebuild
      if (this.learningOrder == 2 && !this.isLive) {
        //要按从头到尾顺序学习, 且不是重修课程
        if (this.preItem) {
          let rows = this.menuAllList;
          let newRows = [];
          for (let i = 0; i < rows.length; i++) {
            let moduleTrue =
              rows[i].moduleId == this.menuItem.moduleId ||
              rows[i].moduleId == 0;
            let chapterTrue =
              rows[i].chapterId == this.menuItem.chapterId ||
              rows[i].chapterId == 0;
            let sectionTrue =
              rows[i].sectionId == this.menuItem.sectionId ||
              rows[i].sectionId == this.menuItem.menuId;
            if (moduleTrue && chapterTrue && sectionTrue) {
              break;
            } else {
              if (rows[i].sectionType != 2) {
                newRows.push(rows[i]);
              }
            }
          }
          let isAllLearn = newRows.every((item) => {
            return item.studyStatus == 1;
          });
          if (isAllLearn) {
            this.playVideo();
          } else {
            uni.showToast({
              icon: "none",
              title: "请按顺序学习视频课程",
            });
          }
        } else {
          //第一章第一节
          this.playVideo();
        }
      } else {
        this.playVideo();
      }
      setTimeout(() => {
        this.clickLock = false;
      }, 3000);
    },
    studyRecordGetChannelBasicInfo(channelId) {
      return new Promise((resolve) => {
        this.$api
          .studyRecordGetChannelBasicInfo({
            channelId,
          })
          .then((res) => {
            resolve(res.data.data);
          });
      });
    },
    async playVideo() {
      if (!this.isBuy) {
        if (this.isTryListen) {
          uni.$emit("getSection", this.menuItem, this.isTryListen);
        }
        //非购买
        this.clickLock = false;
        return;
      }
      if (this.menuItem.sectionType == 1 || this.menuItem.sectionType == 3) {
        let learnNum = await this.goodsTodayStudySectionNum();
        let hasLearn = await this.gradeCheckGoodsStudy();

        if (this.sectionMaxNum > 0) {
          if (learnNum >= this.sectionMaxNum && !hasLearn) {
            uni.showToast({
              icon: "none",
              title: `每天最多学习${this.sectionMaxNum}节`,
            });
            this.clickLock = false;
            return;
          }
        }
        if (!this.menuItem.recordingUrl) {
          uni.showToast({
            title: "暂无播放地址数据",
            icon: "none",
          });
          this.clickLock = false;
          return;
        }
        // 回放
        if (this.menuItem.sectionType == 3) {
          let moduleId = this.menuItem.moduleId || 0;
          let chapterId = this.menuItem.chapterId || 0;
          let sectionId = this.menuItem.sectionId || this.menuItem.menuId;
          let uuid = new Date().valueOf() + "";
          // buyCourse 是否购买课程：1是 0否,type=vod是回放
          let encode = encodeURIComponent(
            this.config.hostLive +
              "/pages/live/index?token=" +
              uni.getStorageSync("token") +
              "&userInfo=" +
              JSON.stringify(this.userInfo) +
              "&channelId=" +
              this.menuItem.liveUrl +
              "&gradeId=" +
              this.gradeId +
              "&courseId=" +
              this.courseId +
              "&goodsId=" +
              this.goodsId +
              "&orderGoodsId=" +
              this.orderGoodsId +
              "&sectionId=" +
              sectionId +
              "&chapterId=" +
              chapterId +
              "&moduleId=" +
              moduleId +
              "&buyCourse=1" +
              "&ident=" +
              uuid +
              "&sectionType=3" +
              "&vid=" +
              this.menuItem.recordingUrl
          );
          uni.navigateTo({
            url: `../../pages/webview/index?url=` + encode,
          });
          return;
        }
        // console.log('===设置播放的节IDthis.menuItem,', this.menuItem, this.playId);
        //设置播放的节ID
        this.$store.commit("updatePlayNextId", this.playId);
        uni.$emit("getSection", this.menuItem);
        uni.$emit("isRebuild", this.isRebuild);
      }
      if (this.menuItem.sectionType == 2) {
        let learnNum = await this.goodsTodayStudySectionNum();
        let hasLearn = await this.gradeCheckGoodsStudy();

        if (this.sectionMaxNum > 0 && !this.isLive) {
          if (learnNum >= this.sectionMaxNum && !hasLearn) {
            uni.showToast({
              icon: "none",
              title: `每天最多学习${this.sectionMaxNum}节`,
            });
            this.clickLock = false;
            return;
          }
        }
        if (!this.menuItem.liveUrl) {
          uni.showToast({
            title: "暂无直播地址数据",
            icon: "error",
          });
          return;
        }

        let data = await this.studyRecordGetChannelBasicInfo(
          this.menuItem.liveUrl
        );
        let nowTime = +this.$method.timest();

        if (this.menuItem.liveStartTime > nowTime) {
          if (data.watchStatus == "end" || data.watchStatus == "playback") {
            this.clickLock = false;
            uni.showToast({
              title: "直播未开始",
              icon: "none",
            });
            return;
          }
        } else if (
          this.menuItem.liveStartTime < nowTime &&
          this.menuItem.liveEndTime > nowTime
        ) {
          if (data.watchStatus == "end" || data.watchStatus == "playback") {
            this.clickLock = false;
            uni.showToast({
              title: "暂无直播",
              icon: "none",
            });
            return;
          }
        } else if (this.menuItem.liveEndTime < nowTime) {
          if (!data) {
            uni.showToast({
              title: "直播已结束",
              icon: "none",
            });
            return;
          }
          if (data.watchStatus == "end" || data.watchStatus == "playback") {
            this.clickLock = false;
            uni.showToast({
              title: "直播已结束",
              icon: "none",
            });
            return;
          }
        }
        let moduleId = this.menuItem.moduleId || 0;
        let chapterId = this.menuItem.chapterId || 0;
        let sectionId = this.menuItem.sectionId || this.menuItem.menuId;
        let uuid = new Date().valueOf() + "";
        // buyCourse 是否购买课程：1是 0否
        let encode = encodeURIComponent(
          this.config.hostLive +
            "/pages/live/index?token=" +
            uni.getStorageSync("token") +
            "&userInfo=" +
            JSON.stringify(this.userInfo) +
            "&channelId=" +
            this.menuItem.liveUrl +
            "&gradeId=" +
            this.gradeId +
            "&courseId=" +
            this.courseId +
            "&goodsId=" +
            this.goodsId +
            "&orderGoodsId=" +
            this.orderGoodsId +
            "&sectionId=" +
            sectionId +
            "&chapterId=" +
            chapterId +
            "&moduleId=" +
            moduleId +
            "&buyCourse=1" +
            "&ident=" +
            uuid +
            "&sectionType=2"
        );
        uni.navigateTo({
          url: `../../pages/webview/index?url=` + encode,
        });

        return;
      }
    },
  },
  computed: {
    ...mapGetters(["userInfo", "liveLast", "config"]),
    isActive() {
      if (!this.isBuy || !this.sectionItem) {
        return false;
      }
      let moduleId = this.menuItem.moduleId || 0;
      let chapterId = this.menuItem.chapterId || 0;
      let sectionId = this.menuItem.sectionId || this.menuItem.menuId;
      let moduleId1 = this.sectionItem.moduleId || 0;
      let chapterId1 = this.sectionItem.chapterId || 0;
      let sectionId1 = this.sectionItem.sectionId || this.sectionItem.menuId;
      return (
        moduleId == moduleId1 &&
        chapterId == chapterId1 &&
        sectionId == sectionId1
      );
    },
    params() {
      return this.paramsFn([
        "orderGoodsId",
        "gradeId",
        "courseId",
        "sectionItem",
        "menuAllList",
        "orderNum",
        "goodsId",
        "sectionId",
        "listenConfigList",
      ]);
    },
    courseId() {
      return this.params.courseId;
    },
    gradeId() {
      return this.params.gradeId;
    },
    orderGoodsId() {
      return this.params.orderGoodsId;
    },
    sectionItem() {
      return this.params.sectionItem;
    },
    menuAllList() {
      return this.params.menuAllList;
    },
    goodsId() {
      return this.params.goodsId;
    },
    sectionId() {
      return this.params.sectionId;
    },
    isTryListen() {
      let { listenConfigList } = this.params;
      return (
        listenConfigList &&
        listenConfigList.find(
          (e) =>
            e.sectionId == this.menuItem.sectionId ||
            e.sectionId == this.menuItem.menuId
        )
      );
    },
  },
};
</script>

<style scoped lang="scss">
.tagGreen {
  width: 80rpx;
  height: 28rpx;
  background: #34c759;
  border-radius: 8rpx;
  font-size: 20rpx;
  color: #ffffff;
  text-align: center;
}

.tagWillPlay {
  width: 80rpx;
  height: 28rpx;
  background: #ebf4ff;
  border-radius: 8rpx;
  font-size: 20rpx;
  color: #007aff;
  text-align: center;
}

.tagPlaying {
  width: 80rpx;
  height: 28rpx;
  background: #fff7eb;
  border-radius: 8rpx;
  font-size: 20rpx;
  color: #ff9500;
  text-align: center;
}

.tagPlayed {
  width: 80rpx;
  height: 28rpx;
  background: #eeeeee;
  border-radius: 8rpx;
  font-size: 20rpx;
  color: #666666;
  text-align: center;
}

.tagRe {
  width: 80rpx;
  height: 28rpx;
  background: #ff3b30;
  border-radius: 8rpx;
  font-size: 20rpx;
  color: #ffffff;
  text-align: center;
}

.tryBox {
  width: 103rpx;
  height: 48rpx;
  background: #fff;
  border-radius: 24rpx;
  color: #3577e8;
  font-size: 24rpx;
  line-height: 48rpx;
  text-align: center;
  border: 1rpx solid #3577e8;
}

.icon_up {
  width: 24rpx;
  height: 24rpx;
}

.t_content3 {
  color: #007aff;
}

.t_content2 {
  color: #007aff;
}

.t_content1 {
  color: #007aff;
}

.t_content {
  font-size: 30rpx;
  margin-left: 10rpx;
  color: #666666;
  flex: 1;
}

.tagColor3 {
  border: 2rpx solid #ff9500;
  color: #ff9500;
}

.tagColor2 {
  border: 2rpx solid #ff3b30;
  color: #ff3b30;
}

.tagColor1 {
  border: 2rpx solid #007aff;
  color: #007aff;
}

.color3 {
  color: #ff9500;
}

.color2 {
  color: #ff3b30;
}

.color1 {
  color: #007aff;
}

.tag {
  border-radius: 8rpx;
  font-size: 20rpx;
  padding: 4rpx 10rpx;
}

.exercises {
  margin-left: 10rpx;
  font-size: 26rpx;
  color: #498afe;

  > text {
    margin-right: 6rpx;
  }
}

.learnings {
  margin-right: 8rpx;

  .learning_icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 4rpx;
  }
}
</style>
