<template>
  <page-meta
    :page-font-size="$baseFontSize() + 'px'"
    :root-font-size="$baseFontSize() + 'px'"
  ></page-meta>
  <view class="container commonPageBox commonDetailPage">
    <!-- 公共组件-每个页面必须引入 -->
    <public-module></public-module>
    <z-nav-bar title="课程设置" bgColor="#3AB3AE" fontColor="#fff"></z-nav-bar>

    <common-anchor-link
      style="width: 100%"
      ref="commonAnchorLink"
      baseHeight="40"
      :defaultShowTabs="true"
      :allDataList="allDataList"
      titleKey="title"
      :slotName="currentCateIndex == 0 ? '' : 'detail'"
      :dataListKey="currentCateIndex == 0 ? 'courseList' : 'content'"
      :titleStyle="{
        'font-size': '30px',
        'text-align': 'center',
      }"
      :tabStyle="{
        background: '#f3faf3',
      }"
    >
      <template slot="tabs" slot-scope="slotProps">
        <common-sticky
          label="title"
          itemStyle="width:50%;padding-left: 15px; padding-right: 15px; height: 68rpx;"
          :list="cateList"
          :currentCateIndex="currentCateIndex"
          @handleselectCate="handleselectCate"
        ></common-sticky>
      </template>
      <template slot="label" slot-scope="slotProps">
        <view
          class="content_title"
          :style="`margin-top: ${
            slotProps.dataIndex == 0 ? 10 : 30
          }px; margin-bottom: 20px;`"
          >{{ slotProps.title }}</view
        >
      </template>
      <template slot="contentList" slot-scope="slotProps">
        <common-list
          style="margin-bottom: 40px"
          v-if="currentCateIndex == 0"
          noDataIcon="data"
          :isCondition="true"
          :isNoIcon="true"
          :dataList="slotProps.dataList"
          label="title"
          @hancleClick="gotoDetail"
        >
          <template slot="labelSlot" slot-scope="slotProps">
            <image
              v-if="slotProps.row.image"
              :src="slotProps.row.image"
              mode="aspectFil"
              class="book_image"
            ></image>
            <image
              v-else
              src="@/static/icon/videoIcon.png"
              mode="aspectFil"
              class="book_image"
            ></image>

            <view class="related_courses_name">
              <view class="" style="font-weight: bold">
                {{ slotProps.row.title }}
              </view>

              <view style="margin-top: 10rpx">
                <view
                  v-for="item in slotProps.row.courseCatalogueEntityList"
                  style="float: left; margin-right: 20rpx"
                >
                  {{
                    slotProps.row.courseCatalogueEntityList.length > 1
                      ? item.title
                      : "整部"
                  }}：

                  <text v-if="item.halfFee == 0 && item.fee == 0">免费</text>
                  <text v-else-if="item.halfFee == 0 || item.fee == 0">
                    {{ item.halfFee != 0 ? item.halfFee : "免费" }}/{{
                      item.fee != 0 ? item.fee : "免费"
                    }}</text
                  >
                  <text v-else-if="item.halfFee != 0 || item.fee != 0">
                    {{ item.halfFee }}/{{ item.fee }}</text
                  >
                </view>
              </view>
            </view>
          </template>
        </common-list>
      </template>
      <template slot="detail_buyRecord" slot-scope="slotProps">
        <view style="padding: 20rpx">
          <rich-text
            :nodes="slotProps.dataList | formatRichText"
            @click.stop="showPreview"
            :data-nodes="slotProps.dataList"
          ></rich-text>
        </view>
      </template>
      <template slot="detail_useRecord" slot-scope="slotProps">
        <view style="padding: 20rpx">
          <rich-text
            :nodes="slotProps.dataList | formatRichText"
            @click.stop="showPreview"
            :data-nodes="slotProps.dataList"
          ></rich-text>
        </view>
      </template>
      <template slot="detail_studyRecord" slot-scope="slotProps">
        <view style="padding: 20rpx">
          <rich-text
            :nodes="slotProps.dataList | formatRichText"
            @click.stop="showPreview"
            :data-nodes="slotProps.dataList"
          ></rich-text>
        </view>
      </template>
      <template slot="detail_vipRecord" slot-scope="slotProps">
        <view style="padding: 20rpx">
          <rich-text
            :nodes="slotProps.dataList | formatRichText"
            @click.stop="showPreview"
            :data-nodes="slotProps.dataList"
          ></rich-text>
        </view>
      </template>
    </common-anchor-link>
  </view>
</template>

<script>
import courseDescription from "../price/courseDescription.vue";
import price from "../price/index.vue";
import purchaseNotice from "../purchaseNotice/index.vue";
import instructionsForUse from "../instructionsForUse/index.vue";
import $http from "@/config/requestConfig.js";
import { mapState } from "vuex";
export default {
  components: {
    courseDescription, //课程说明
    price, //课程价格
    instructionsForUse, //使用须知
    purchaseNotice, //使用须知
  },
  data() {
    return {
      currentTab: "",
      dataInfo: {},
      allDataList: [],
      playData: {},
      searchValue: "",
      cateList: [
        {
          title: "课程价格(半年/一年)",
          type: "price",
          apiUrl: "/sociology/course/getCoursePrice",
        },
        {
          title: "课程说明",
          type: "courseDescription",
          apiUrl: "/sociology/course/getSociologyCourseRecord",
        },
      ], // 一级分类标题1
      twoCateList: [], // 二级分类标题
      dataList: [], // 方剂标题
      currentCateIndex: 0, // 当前选中的一级分类
      curTwoCateIndex: 0, // 当前选中的二级分类
      searchList: [], // 搜索结果数组
      showSearchList: false,
      userMes: {}, // 用户信息
      searchDisable: false, // 搜索不可用
      limitShow: false,
      limitTitle: "提示",
      limitContent: "",
      scrollViewHeight: 0,
      detailDataList: [
        {
          title: "购买须知",
          valueName: "buyRecord",
        },
        {
          title: "使用须知",
          valueName: "useRecord",
        },
        {
          title: "学习次序",
          valueName: "studyRecord",
        },
        {
          title: "超v",
          valueName: "vipRecord",
        },
      ],
    };
  },
  // 监听页面滚动
  onPageScroll(event) {
    // if (this.currentCateIndex == 0) {
    this.$refs.commonAnchorLink.pageScroll(event);
    // }
  },
  async onLoad() {
    await this.handleselectCate({ ...this.cateList[0], index: 0 }, 0);
  },
  onHide() {
    // this.showSearchList = false
    // this.searchList = []
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  methods: {
    formatRichText(html) {
      //控制小程序中图片大小
      let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        match = match
          .replace(/style="[^"]+"/gi, "")
          .replace(/style='[^']+'/gi, "");
        match = match
          .replace(/width="[^"]+"/gi, "")
          .replace(/width='[^']+'/gi, "");
        match = match
          .replace(/height="[^"]+"/gi, "")
          .replace(/height='[^']+'/gi, "");
        return match;
      });
      newContent = newContent.replace(
        /style="[^"]+"/gi,
        function (match, capture) {
          match = match
            .replace(/width:[^;]+;/gi, "max-width:100%;")
            .replace(/width:[^;]+;/gi, "max-width:100%;");
          return match;
        },
      );
      newContent = newContent.replace(/<br[^>]*\/>/gi, "");
      newContent = newContent.replace(
        /\<img/gi,
        '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"',
      );
      return newContent;
    },
    gotoDetail(v) {
      console.log(v);
      uni.navigateTo({
        // url: '../bookShop/commodityDetail?id=' + item.id
        url: `/pages/curriculum/order/curriculum/index?navTitle=${v.title}&title=${v.title}&id=${v.id}`,
      });
    },
    goCourseDescription(v) {
      console.log(v);
      uni.navigateTo({
        // url: '../bookShop/commodityDetail?id=' + item.id
        url: `/pages/courseInformation/courseDescription/index?navTitle=${v.nameCN}&title=${v.nameCN}&oid=${v.oid}`,
      });
    },

    getPriceData() {
      var that = this;
      setTimeout(() => {
        that.$nextTick(() => {
          that.$refs.priceDetail.getData();
        });
      }, 100);
    },
    // 检查是有权限使用搜索功能
    checkDisable() {
      console.log("点击了");
    },
    // 显示无权限弹窗
    // showNoRights() {
    // 	let that = this
    // 	uni.showModal({
    // 		content: "",
    // 		confirmText: '好的',
    // 		showCancel: false,
    // 		success: function(res) {
    // 			if (res.confirm) {
    // 				// console.log('用户点击确定');
    // 				that.clear()
    // 			}
    // 		}
    // 	})
    // },
    // 获取用户详情
    getUserInfo() {
      // 用户详情
      if (this.userInfo.id != undefined) {
        this.$http.post("book/user/info/" + this.userInfo.id).then((res) => {
          this.userMes = res.user;
          this.getCateList();
          console.log(this.userMes, "呼呼");
        });
      }
    },
    // 详情
    gotoDetail(item) {
      console.log("111", item);
      console.log("this.currentCateIndex", this.currentCateIndex);
      console.log("this.curTwoCateIndex", this.curTwoCateIndex);
      if (this.currentCateIndex == 0) {
        uni.navigateTo({
          // url: '../bookShop/commodityDetail?id=' + item.id
          url: "./xueshugongxianDetail?id=" + item.id,
        });
        return;
      }
      if (this.currentCateIndex == 1) {
        uni.navigateTo({
          url: "./medicaldesDetail?id=" + item.id,
        });
        return;
      }
      if (this.currentCateIndex == 2) {
        console.log("111", item);
        uni.navigateTo({
          url: "./video?title=" + item.name + "&src=" + item.url,
        });
        return;
      }
      if (this.currentCateIndex == 3) {
        console.log("111", item);
        uni.navigateTo({
          url: "./recordDetail?id=" + item.id,
        });
        return;
      }
    },
    // 获取名称
    getTitles(dictType) {
      console.log("dictType", dictType);
      if (this.currentCateIndex == 0) {
        if (dictType == 2) {
          uni.navigateTo({
            url: "./zhuanzhuchuban",
          });
          return;
        }
        $http
          .request({
            url: "book/generalArticle/articleByPage",
            method: "POST",
            data: {
              // loadAnimate: 'none', // 请求加载动画
              type: dictType == 1 ? "1" : "2",
              limit: 1000,
              current: 1,
            },
            header: {
              //默认 无 说明：请求头
              "Content-Type": "application/json",
            },
          })
          .then((res) => {
            console.log(res, "内容获取成功");
            if (res.code == 0 && res.result && res.result.records.length > 0) {
              this.dataList = res.result.records;
            } else {
              this.dataList = [];
            }
          })
          .catch((e) => {
            this.dataList = [];
            console.log(e);
          });
      }
      if (this.currentCateIndex == 1) {
        $http
          .request({
            url: "book/medicaldes/inheritListByPage",
            method: "POST",
            data: {
              // loadAnimate: 'none', // 请求加载动画
              dictType: dictType,
              limit: 1000,
              current: 1,
            },
            header: {
              //默认 无 说明：请求头
              "Content-Type": "application/json",
            },
          })
          .then((res) => {
            console.log(res, "内容获取成功");
            if (res.code == 0 && res.result.records.length > 0) {
              this.dataList = res.result.records;
              for (let i = 0; i < this.dataList.length; i++) {
                this.dataList[i].imageslist = [];
                this.dataList[i].imageslist = this.dataList[i].img.split(";");
              }
            } else {
              this.dataList = [];
            }
          })
          .catch((e) => {
            this.dataList = [];
            console.log(e);
          });
      }
      if (this.currentCateIndex == 2) {
        $http
          .request({
            url: "book/medicaldes/lightListByType?type=" + dictType,
            method: "POST",
            data: {
              // loadAnimate: 'none', // 请求加载动画
              limit: 1000,
              page: 1,
            },
            header: {
              //默认 无 说明：请求头
              "Content-Type": "application/json",
            },
          })
          .then((res) => {
            console.log(res, "内容获取成功");
            if (res.code == 0 && res.result.length > 0) {
              this.dataList = res.result;
            } else {
              this.dataList = [];
            }
          })
          .catch((e) => {
            this.dataList = [];
            console.log(e);
          });
      }
      if (this.currentCateIndex == 3) {
        $http
          .request({
            url: "book/medicaldes/recordByType?type=" + dictType,
            method: "POST",
            data: {
              // loadAnimate: 'none', // 请求加载动画
              limit: 1000,
              page: 1,
            },
            header: {
              //默认 无 说明：请求头
              "Content-Type": "application/json",
            },
          })
          .then((res) => {
            console.log(res, "内容获取成功");
            if (res.code == 0 && res.result.length > 0) {
              this.dataList = res.result;
            } else {
              this.dataList = [];
            }
          })
          .catch((e) => {
            this.dataList = [];
            console.log(e);
          });
      }
    },
    setTwoCateIndex(item, index) {
      let dictType = item.dictType;
      this.curTwoCateIndex = index;
      this.getTitles(dictType);
    },
    getCourseDescriptionData() {
      this.allDataList = [];

      var data = {};

      var that = this;

      this.$http
        .request({
          url: this.cateList[this.currentCateIndex].apiUrl,
          method: "POST",
          data: data,
          header: {
            //默认 无 说明：请求头
            "Content-Type": "application/json",
          },
        })

        .then(async (res) => {
          console.log(res, "88888");
          if (this.currentCateIndex == 0) {
            that.allDataList = res.list.map((e) => {
              return {
                ...e.sociology,
                courseList: e.courseList,
              };
            });
          } else {
            that.dataInfo = { ...res.result };
            that.allDataList = that.detailDataList.map((e) => {
              return {
                ...e,
                content: res.result[e.valueName],
                slotName: e.valueName,
              };
            });

            console.log("this.allDataList at line 405:", this.allDataList);
          }

          // if (this.currentCateIndex == 0) {
          setTimeout(() => {
            this.$refs.commonAnchorLink.getDistanceArr();
          }, 200);
          // }
          // this.indexList = this.allDataList.map((e) => {
          //   return e.title;
          // });
        });
    },
    async handleselectCate(item, index) {
      this.allDataList = [];
      this.dataList = [];
      var data = [];

      var that = this;
      this.$nextTick(async () => {
        this.currentCateIndex = item.index;

        await this.getCourseDescriptionData();
      });
      console.log(this.allDataList, this.dataList, "1688");

      return data;
    },

    transformData(inputData) {
      const result = {};
      inputData.forEach((item) => {
        const { letter } = item;
        if (!result[letter]) {
          result[letter] = [];
        }
        result[letter].push(item);
      });
      // const finalResult = Object.keys(result).map(key => ({ [key]: result[key] }));
      return result;
    },
    // getJFList(id) {
    // 	$http.request({
    // 		url: "book/prescript/prescriptListForJF",
    // 		method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
    // 		data: {
    // 			loadAnimate: 'none', // 请求加载动画
    // 			'categoryId': id
    // 		},
    // 		header: { //默认 无 说明：请求头
    // 			'Content-Type': 'application/json'
    // 		},
    // 	}).then(res => {
    // 		if (res.code == 0 && res.list.length > 0) {
    // 			this.twoCateList = []
    // 			this.dataList = this.transformData(res.list)
    // 			console.log('JF经方', this.dataList)
    // 		} else {
    // 			this.twoCateList = []
    // 			this.dataList = []
    // 		}
    // 	}).catch(e => {
    // 		this.twoCateList = []
    // 		this.dataList = []
    // 		console.log(e)
    // 	})
    // },
    getCateList(id) {
      id ? "" : (id = 0);
      this.twoCateList = [];
      this.curTwoCateIndex = 0;
      // 0为获取顶级分类，其他为搜索下级分类，目前的逻辑，顶级是写死的，所以可能只会涉及到搜索第二级
      // $http.request({
      // 	url: "book/prescript/prescriptCategoryList",
      // 	method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
      // 	data: {
      // 		loadAnimate: 'none', // 请求加载动画
      // 		'categoryId': id
      // 	},
      // 	header: { //默认 无 说明：请求头
      // 		'Content-Type': 'application/json'
      // 	},
      // }).then(res => {
      // console.log(res, '脉穴分类获取成功')
      // if (res.code == 0 && res.list.length > 0) {
      // this.cateList = res.list
      this.getTowCateList(this.cateList[0].type);
      // } else {
      // 	this.cateList = []
      // }
      // }).catch(e => {
      // 	this.cateList = []
      // 	console.log(e)
      // })
    },

    // 放大图片
    previewImage(url) {
      console.log(url);
      uni.previewImage({
        urls: [url],
        longPressActions: {
          itemList: ["很抱歉，暂不支持保存图片到本地"],
          success: function (res) {
            // console.log(res,'+++++')
          },
        },
      });
    },
    // getSearch() {
    // 	$http.request({
    // 		url: "book/prescript/searchPrescript",
    // 		method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
    // 		data: {
    // 			loadAnimate: 'none', // 请求加载动画
    // 			'keywords': this.searchValue,
    // 			type: this.currentCateIndex + 1
    // 		},
    // 		header: { //默认 无 说明：请求头
    // 			'Content-Type': 'application/json'
    // 		},
    // 	}).then(res => {
    // 		console.log(res, '搜索结果')
    // 		if (res.code == 0 && res.list.length >= 0) {
    // 			this.showSearchList = true
    // 			this.searchList = res.list
    // 		} else {
    // 			this.searchList = []
    // 		}
    // 	}).catch(e => {
    // 		// this.dataList = []
    // 		this.searchList = []
    // 		console.log(e)
    // 	})
    // },
    // search(res) {
    // 	console.log(res, 'res')
    // 	// uni.showToast({
    // 	// 	title: '搜索：' + res,
    // 	// 	icon: 'none'
    // 	// })
    // 	if (res == '') {
    // 		this.showSearchList = false
    // 		this.searchList = []
    // 	} else {
    // 		this.getSearch()
    // 	}

    // },
    // input(res) {
    // 	console.log('----input:', res)
    // 	if (res == '') {
    // 		this.searchList = []
    // 	} else {
    // 		this.getSearch()
    // 	}
    // },
    // clear(res) {
    // 	console.log('----clear:', res)
    // 	// uni.showToast({
    // 	// 	title: 'clear事件，清除值为：',
    // 	// 	icon: 'none'
    // 	// })
    // 	this.searchValue = ''
    // 	this.showSearchList = false
    // },
    // blur(res) {
    // 	// console.log('----blur:', res)
    // 	// if (res == '') {
    // 	// 	this.showSearchList = false
    // 	// 	this.searchList = []
    // 	// } else {
    // 	// 	this.getSearch()
    // 	// }
    // },
    // focus(e) {
    // 	console.log('----focus:')
    // 	// uni.showToast({
    // 	// 	title: 'focus事件，输出值为：' + e.value,
    // 	// 	icon: 'none'
    // 	// })
    // 	// 等于1 就是有权限
    // 	// this.showSearchList = true

    // },
    // cancel(res) {
    // 	uni.showToast({
    // 		title: '点击取消，输入值为：' + res.value,
    // 		icon: 'none'
    // 	})
    // }
  },
  onBackPress() {
    // #ifdef APP-PLUS
    plus.key.hideSoftKeybord();
    // #endif
  },
};
</script>

<style lang="scss" scoped>
@import "@/style/common.scss";
.u-grid-list {
  // height: 40rpx;
}

.searchList {
  .item {
    font-size: 28rpx;
    padding: 20rpx;
    border-bottom: 1px solid #dadbde;
  }
}

.scroll-view_H {
  background-color: #fff;
  white-space: nowrap;
  padding: 10rpx;
}

.contentBox {
  // height: calc(100% - 50px);
}
.cateList {
  padding: 10rpx;
  box-sizing: border-box;
  justify-content: space-between;

  text {
    text-align: center;
    display: inline-block;
    width: 49%;
    padding: 20rpx 0;
    font-size: 34rpx;
    // border-radius: 10rpx;
  }

  .cur {
    // background-color: #3AB3AE;
    color: rgb(58, 179, 174);
    border-bottom: 2px solid rgb(58, 179, 174);
    // box-shadow: 0 2px 12px 0 rgba(58, 179, 174, .5);
  }
}

.twoCateList {
  font-size: 28rpx;
  margin-top: 20rpx;

  .grid-text {
    padding: 10rpx 0rpx;
    text-align: center;
  }

  .cur {
    color: #3ab3ae;
    font-weight: 600 !important;
  }

  // .u-grid-list{border: 0.5px solid #dadbde;}
}

.dataList {
  font-size: 26rpx;
  // margin-top: 20rpx;
  // padding: 32rpx 0rpx;
  border-radius: 10rpx;
  background-color: #f8f9fa;
  box-sizing: border-box;

  .JFtitleItem {
    background-color: #ffffff;
    padding: 20rpx 10rpx;
    width: 100%;
    border-bottom: 0.5px solid #f8f9fa;
  }

  .wmzhimg {
    width: 220rpx;
    height: 220rpx;
  }
}

.search_box {
  margin: 0 auto;
  overflow: hidden;
  align-items: center;
  width: calc(100% - 10px);
  margin-top: 20rpx;
  margin-bottom: 20rpx;

  .search {
    height: 56upx;
    display: flex;
    width: 86%;
    margin: 0 auto;
    align-items: center;
    padding: 0upx 40upx;
    background-color: #fff;
    border-radius: 20upx;
    box-shadow: 0 0px 10px 1px #3ab3ae33;
  }

  .prompt {
    color: #838383;
    font-size: 24rpx;
  }

  .icon_search {
    background-image: url("@/static/icon/map_ic_search.png");
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    width: 36upx;
    height: 36upx;
    margin-right: 20upx;
  }
}

.flexbox {
  display: flex;
}

.uni-modal .uni-modal__bd {
  text-align: left;
}

.limiTy {
  font-size: 28rpx;
  line-height: 46rpx;
}

.chImage {
  height: 100rpx;
}

.scroll-Y {
  height: 100%;
}

.scroll-view_H {
  white-space: nowrap;
  width: 100%;
}

.scroll-view-item {
  // height: 300rpx;
  // line-height: 300rpx;
  // text-align: center;
  // font-size: 36rpx;
}

.scroll-view-item_H {
  display: inline-block;
  width: 100%;
  // height: 300rpx;
  // line-height: 300rpx;
  // text-align: center;
  // font-size: 36rpx;
}

.dataList {
  height: 100%;
}

.titleList2 {
  height: calc(100% - 170rpx);
}

.priceDetail {
  height: calc(100% - 100rpx) !important;
  padding: 0rpx 0;
  box-sizing: border-box;
}

.componentPage {
  height: calc(100% - 90rpx) !important;
}

.book_image {
  width: 60rpx;
  height: 40rpx;
  float: left;
  margin-right: 10rpx;
}
/deep/.list_item {
  padding: 12rpx 20rpx;
  display: flex;
  align-items: center;
  border-color: #efeef4 !important;
  //   .rightArrow {
  //     margin-top: 10rpx !important;
  //   }
}
.section .top .title {
  &::before {
    display: none !important;
  }
}

.content_title {
  width: 100%;
  text-align: center;
  font-size: 30px;
}

// .commonDetailPage{
//   background-color: $themeBgColor;
// }
/deep/.wrapper {
  background-color: $themeBgColor;
  .content_list {
    padding: 20rpx 0;
    background-color: rgba(255, 255, 255, 0.8) !important;
  }
}
</style>
