<template>
  <view>
    <view class="title" @click="openChapter(menuItem)">
      <view>
        <u-icon name="arrow-down" color="#999" size="24" v-if="!down"></u-icon>
        <u-icon name="arrow-right" color="#999" size="24" v-if="down"></u-icon>
        <text class="menu_name">{{ menuItem.name }}</text>
      </view>

      <view class="fl">
        <view class="title_status gre" v-if="menuItem.commonSign == 1"
          >公共章</view
        >
        <view
          class="title_status"
          :class="['grey', 'blue', 'gre'][learnStatus + 1]"
        >
          {{ ["待学习", "学习中", "已学完"][learnStatus + 1] }}
        </view>
      </view>
    </view>
    <view v-show="!down">
      <view v-for="(itemM, indexM) in list" :key="indexM">
        <view v-if="itemM.type != 2">
          <courseSection
            ref="ChapterSection"
            :isLive="isLive"
            :sectionMaxNum="sectionMaxNum"
            :preItem="list[indexM - 1] || preItem"
            @playEnd="getSectionList"
            :isBuy="isBuy"
            :nextMenuItem="findNextSection(indexM)"
            :isRebuild="isRebuild"
            :menuItem="itemM"
            :levelId="levelId + '-' + itemM.sectionId"
            :testType="2"
            :ChapterSectionExam="sectionExam"
          ></courseSection>
          <!-- @togoBack='togoBack()' -->
          <u-line v-if="indexM < list.length - 1"></u-line>
        </view>
        <!-- 章卷 -->
        <view v-if="itemM.type == 2">
          <u-line></u-line>
          <view
            class="examBox"
            @click="
              toDo(
                itemM.typeId,
                goodsId,
                itemM.moduleId,
                itemM.chapterId,
                itemM,
                indexM
              )
            "
          >
            <view class="exam">
              <view class="eTag">
                {{ itemM.doType == 1 ? "练习" : "考试" }}
              </view>
              <view style="margin-left: 15rpx; flex: 1">{{ itemM.name }}</view>
            </view>
            <view v-if="isRebuild || itemM.rebuild > 0" class="tagRe"
              >待重修</view
            >
            <view v-else>
              <view
                :class="{
                  tagGreen: itemM.learning == 1,
                  tagRe: itemM.learning == 0 || itemM.rebuild > 0,
                }"
              >
                <text v-if="itemM.rebuild > 0">待重测</text>
                <text v-else-if="itemM.learning == 1">合格</text>
                <text v-else-if="itemM.learning == 0">不及格(需重考)</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapMutations } from "vuex";
import courseSection from "@/components/course/courseSection.vue";
export default {
  name: "courseChapter",
  inject: ["paramsFn"],
  props: {
    isLive: false,

    preItem: {
      default: undefined,
    },

    needOpen: {
      //是否默认展开
      type: Boolean,
      default: false,
    },
    menuItem: {
      type: Object,
      default: {},
    },
    isBuy: {
      type: Boolean,
      default: false,
    },
    levelId: {
      type: String,
      default: "",
    },
    isRebuild: {
      type: Boolean,
      default: false,
    },

    sectionMaxNum: {
      default: undefined,
    },
    // 商品类型 1视频2题库 3补考 4前培 5虚拟赠送题库 6直播
    goodsType: {
      type: [Number, String],
      default: 0,
    },
  },
  components: {
    courseSection,
  },
  data() {
    return {
      down: true,
      list: [],
      canLearn: false, //是否全部视频看完才可以练习、测试
      sectionExam: [],
    };
  },
  methods: {
    ...mapMutations(["updateChapterOpen"]),
    // 调用节的方法
    // togoBack(value) {
    //   this.$refs.ChapterSection[0].ChapterExam()
    // },
    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);
            }
          });
      });
    },
    findNextSection(index) {
      for (let i = index + 1; i < this.list.length; i++) {
        return this.list[i];
      }
      return {};
    },
    gradeCheckGoodsStudy(id) {
      return new Promise((resolve) => {
        this.$api
          .gradeCheckGoodsStudy({
            goodsId: this.goodsId,
            gradeId: this.gradeId,
            moduleId: this.menuItem.moduleId || 0,
            chapterId: this.menuItem.chapterId || 0,
            examId: id,
            orderGoodsId: this.orderGoodsId,
          })
          .then((res) => {
            resolve(res.data.data);
          });
      });
    },
    // 新增用户视频学习日志
    studyLog() {
      this.$http({
        url: "/user/study/log",
        method: "post",
        data: {
          goodsId: this.goodsId,
          courseId: this.courseId,
          moduleId: this.menuItem.moduleId || 0,
          chapterId: this.menuItem.chapterId || 0,
          sectionId: this.menuItem.sectionId || this.menuItem.menuId,
          fromPlat: 1, //来源平台 1小程序 2PC网站
          goodsType: this.goodsType, // 商品类型 1视频2题库 3补考 4前培 5虚拟赠送题库 6直播
          orderGoodsId: this.orderGoodsId,
        },
      }).then((res) => {
        console.log("考试的用户学习日志:", res);
      });
    },
    /**
     * 去做题
     */
    async toDo(id, goodsId = 0, moduleId = 0, chapterId = 0, item, index) {
      if (item.doType === 2 && item.learning == 1) {
        return;
      }
      // 查询用户商品今天学习节数- /goods/todayStudySectionNum
      let learnNum = await this.goodsTodayStudySectionNum();
      // 检查用户是否学习过节 - /grade/grade/checkGoodsStudy
      let hasLearn = await this.gradeCheckGoodsStudy(id);

      if (this.sectionMaxNum > 0) {
        if (learnNum >= this.sectionMaxNum && !hasLearn) {
          uni.showToast({
            icon: "none",
            title: `每天最多学习${this.sectionMaxNum}节`,
          });
          return;
        }
      }
      if (this.params.orderNum == 1) {
        if (this.canLearn) {
          let num = await this.bankRecordDoNum(item.typeId);
          //有次数限制
          if (item.answerNum - num > 0 && item.answerNum > 0) {
            // this.$set(this.list[index],'doNum',(item.doNum+1))
            // console.log(this.list[index]);
            uni.navigateTo({
              url:
                "/pages2/class/questionBank?courseId=" +
                this.courseId +
                "&gradeId=" +
                this.gradeId +
                "&isFromVideo=1&id=" +
                id +
                "&goodsid=" +
                goodsId +
                "&moduleId=" +
                moduleId +
                "&chapterId=" +
                chapterId +
                "&orderGoodsId=" +
                this.orderGoodsId +
                "&type=1" +
                "&learning=" +
                item.learning +
                "&isBackVideo=" +
                1,
            });
            this.studyLog();
            //没有答题次数限制
          } else if (item.answerNum == 0) {
            uni.navigateTo({
              url:
                "/pages2/class/questionBank?courseId=" +
                this.courseId +
                "&gradeId=" +
                this.gradeId +
                "&isFromVideo=1&id=" +
                id +
                "&goodsid=" +
                goodsId +
                "&moduleId=" +
                moduleId +
                "&chapterId=" +
                chapterId +
                "&orderGoodsId=" +
                this.orderGoodsId +
                "&type=1" +
                "&learning=" +
                item.learning +
                "&isBackVideo=" +
                1,
            });
            this.studyLog();
          } else {
            uni.showToast({
              icon: "none",
              title: "该试卷只能答题" + item.answerNum + "次",
            });

            return;
          }
        } else {
          uni.showToast({
            icon: "none",
            title: "请按顺序学完视频课程再进行练习和测试",
          });
        }
      } else if (this.params.orderNum == 2) {
        //  !item.rebuild
        let rows = this.menuAllList;
        const index = this.menuAllList.findIndex((e) => {
          let i_sectionId = e.sectionId || 0;
          let i_chapterId = e.chapterId || 0;
          let i_moduleId = e.moduleId || 0;
          return (
            i_sectionId == item.sectionId &&
            i_chapterId == item.chapterId &&
            i_moduleId == item.moduleId
          );
        });
        let isStop = false;
        let newRows = [];
        for (let i = 0; i < index; i++) {
          let moduleTrue = rows[i].moduleId == moduleId;
          let chapterTrue = rows[i].chapterId == chapterId;
          if (moduleTrue && chapterTrue) {
            isStop = true;
            if (rows[i].sectionType != 2) {
              //忽略直播
              newRows.push(rows[i]);
            }
          } else {
            if (!isStop) {
              if (rows[i].sectionType != 2) {
                //忽略直播
                newRows.push(rows[i]);
              }
            } else {
              break;
            }
          }
        }
        let isAllLearn = newRows.every((item) => {
          return item.studyStatus == 1;
        });
        if (isAllLearn) {
          //之前的都学完了

          // if(canLearn) { //视频的上一节学完

          let num = await this.bankRecordDoNum(item.typeId);
          //有次数限制
          if (item.answerNum - num > 0 && item.answerNum > 0) {
            // this.$set(this.list[index],'doNum',(item.doNum+1))
            // console.log(this.list[index]);
            uni.navigateTo({
              url:
                "/pages2/class/questionBank?courseId=" +
                this.courseId +
                "&gradeId=" +
                this.gradeId +
                "&isFromVideo=1&id=" +
                id +
                "&goodsid=" +
                goodsId +
                "&moduleId=" +
                moduleId +
                "&chapterId=" +
                chapterId +
                "&orderGoodsId=" +
                this.orderGoodsId +
                "&type=1" +
                "&learning=" +
                item.learning +
                "&isBackVideo=" +
                1,
            });
            this.studyLog();
            //没有答题次数限制
          } else if (item.answerNum == 0) {
            uni.navigateTo({
              url:
                "/pages2/class/questionBank?courseId=" +
                this.courseId +
                "&gradeId=" +
                this.gradeId +
                "&isFromVideo=1&id=" +
                id +
                "&goodsid=" +
                goodsId +
                "&moduleId=" +
                moduleId +
                "&chapterId=" +
                chapterId +
                "&orderGoodsId=" +
                this.orderGoodsId +
                "&type=1" +
                "&learning=" +
                item.learning +
                "&isBackVideo=" +
                1,
            });
            this.studyLog();
          } else {
            uni.showToast({
              icon: "none",
              title: "该试卷只能答题" + item.answerNum + "次",
            });

            return;
          }
        } else {
          uni.showToast({
            icon: "none",
            title: "请学完视频课程再进行练习和测试",
          });
        }
      } else {
        let num = await this.bankRecordDoNum(item.typeId);
        //有次数限制
        if (item.answerNum - item.doNum > 0 && item.answerNum > 0) {
          // this.$set(this.list[index],'doNum',(item.doNum+1))
          // console.log(this.list[index]);
          uni.navigateTo({
            url:
              "/pages2/class/questionBank?courseId=" +
              this.courseId +
              "&gradeId=" +
              this.gradeId +
              "&isFromVideo=1&id=" +
              id +
              "&goodsid=" +
              goodsId +
              "&moduleId=" +
              moduleId +
              "&chapterId=" +
              chapterId +
              "&orderGoodsId=" +
              this.orderGoodsId +
              "&type=1" +
              "&learning=" +
              item.learning +
              "&isBackVideo=" +
              1,
          });
          this.studyLog();
          //没有答题次数限制
        } else if (item.answerNum == 0) {
          uni.navigateTo({
            url:
              "/pages2/class/questionBank?courseId=" +
              this.courseId +
              "&gradeId=" +
              this.gradeId +
              "&isFromVideo=1&id=" +
              id +
              "&goodsid=" +
              goodsId +
              "&moduleId=" +
              moduleId +
              "&chapterId=" +
              chapterId +
              "&orderGoodsId=" +
              this.orderGoodsId +
              "&type=1" +
              "&learning=" +
              item.learning +
              "&isBackVideo=" +
              1,
          });
          this.studyLog();
        } else {
          uni.showToast({
            icon: "none",
            title: "该试卷只能答题" + item.answerNum + "次",
          });

          return;
        }
      }
    },
    bankRecordDoNum(examId) {
      return new Promise((resolve) => {
        this.$api
          .bankRecordDoNum({
            goodsId: this.goodsId,
            gradeId: this.gradeId,
            chapterId: this.menuItem.id,
            courseId: this.courseId,
            moduleId: 0,
            examId: examId,
            orderGoodsId: this.orderGoodsId,
          })
          .then((res) => {
            resolve(res.data.data);
          });
      });
    },
    async openChapter(item) {
      this.down = !this.down;
      if (!this.down && this.list.length == 0) {
        //获取章下面所有节试卷列表-course/sectionExamList
        this.$method.isLogin() &&
          (await this.$api
            .reSectionExamList({
              chapterId: item.chapterId || item.menuId,
              courseId: item.courseId,
              gradeId: item.gradeId,
              orderGoodsId: this.orderGoodsId,
            })
            .then((res) => {
              if (res.data.code == 200) {
                this.sectionExam = res.data.data || [];
              }
            }));
        this.getSectionList();
      }
    },
    getSectionList() {
      const fn = this.isBuy ? "reSectionList" : "sectionList";
      let chapterId = this.menuItem.chapterId || this.menuItem.menuId;
      this.$api[fn](
        this.isBuy
          ? {
              chapterId,
              gradeId: this.gradeId,
              courseId: this.courseId,
              moduleId: this.menuItem.moduleId || 0,
              orderGoodsId: this.orderGoodsId,
              rebuild: +this.isRebuild,
            }
          : chapterId
      ).then((res) => {
        if (res.data.code == 200) {
          for (let i = 0; i < res.data.data.length; i++) {
            let item = res.data.data[i];
            item.courseId = this.courseId;
            item.id = item.sectionId;
            item.menuType = 3;
          }
          let newArr = res.data.data.filter((item) => {
            return item.type != 2;
          });
          this.canLearn = newArr.every((item) => item.learning == 1);
          this.list = res.data.data;
        }
      });
    },
  },
  computed: {
    learnStatus() {
      if (!this.isBuy || !this.sectionItem) {
        return;
      }
      if (!this.sectionItem) {
        return;
      }
      let { id, courseId, moduleId } = this.menuItem;
      if (
        this.sectionItem.courseId == courseId &&
        this.sectionItem.moduleId == (moduleId || 0) &&
        this.sectionItem.chapterId == id
      ) {
        return 0;
      }
      const list = this.menuAllList.filter(
        (e) =>
          e.courseId == courseId &&
          e.moduleId == (moduleId || 0) &&
          e.chapterId == id
      );
      const isAllLearn = list.every((item) => {
        return item.studyStatus == 1;
      });
      return isAllLearn ? 1 : -1;
    },
    params() {
      return this.paramsFn([
        "orderGoodsId",
        "gradeId",
        "courseId",
        "sectionItem",
        "menuAllList",
        "orderNum",
        "goodsId",
      ]);
    },
    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;
    },
  },
  watch: {
    // courseId: {
    //   handler(val) {
    //     if (this.needOpen) {
    //       this.down = true;
    //       this.list = [];
    //       this.updateChapterOpen(false);
    //       this.openChapter(this.menuItem);
    //     }
    //   },
    //   immediate: true,
    // },
	sectionItem: {
	  handler(val) {
	    if (this.needOpen) {
			console.log(this.list,'list')
			if(this.list.length == 0){
	      this.down = true;
          this.list = [];
          this.openChapter(this.menuItem);
			}else{
				this.down = false;
			}
	    }
	  },
	  immediate: true,
	},
	
  },
};
</script>

<style lang="scss" scoped>
.tagRe {
  // width: 80rpx;
  line-height: 28rpx;
  padding: 0 8rpx;
  height: 28rpx;
  background: #ff3b30;
  border-radius: 8rpx;
  font-size: 20rpx;
  color: #ffffff;
  text-align: center;
}

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

.eTag {
  width: 64rpx;
  height: 36rpx;
  text-align: center;
  line-height: 36rpx;
  font-size: 20rpx;
  background: #007aff;
  border-radius: 8rpx;
  color: #ffffff;
}

.examBox {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.exam {
  font-size: 30rpx;
  display: flex;
  align-items: center;
  margin: 20rpx 0;
}

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

.title {
  // margin-bottom: 30rpx;
  height: 78rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #eeeeee;

  .menu_name {
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: bold;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-left: 8rpx;
  }

  .title_status {
    padding: 2rpx 8rpx;
    border-radius: 8rpx;
    font-size: 20rpx;
    color: #ffffff;
    text-align: center;
    margin-left: 4rpx;
  }

  .gre {
    background: #34c759;
  }

  .blue {
    background: #409eff;
  }

  .grey {
    background: #909399;
  }
}
</style>
