<template>
	<uni-popup ref="popupRef" :animation="false" :is-mask-click="false"
		mask-background-color="rgba(255, 255, 255, 0.6);" :is-shadow="false">
		<scroll-view :scroll-y="true" :scroll-top="scrollTop" class="ezy-catalogue-dialog"
      >
      <!--                 :style="{backgroundImage: 'url(' + catalogueBjFun() + ')'}">-->
      <uni-icons @click="handleClose" class="catalogue-close-btn"></uni-icons>
			<!-- 当前上下册只针对数学 -->
			<view v-if="subjectId == 1" class="catalogue-nianji-title">{{ jieTexts ? jieTexts[0]: ''}}</view>
			<!-- 目录区域 -->
			<uni-collapse v-model="activeCollapse" class="ezy-catalogue-collapse"
				:class="{ 'ezy-catalogue-collapse-vip': AuthCode === 'VIP'}" accordion>
				<template v-for="(item,index) in list">
					<!-- 当前上下册只针对数学 -->
					<view v-if="subjectId == 1 && index == shuxueShangxia" class="catalogue-nianji-title catalogue-mt">
						{{jieTexts ? jieTexts[1]: ''}}</view>
					<uni-collapse-item title-border="none" :border="false" :name="index+''" class="collapse-item-box"
						:class="{ 'collapse-active': activeCollapse === index+''}">
						<template v-slot:title>
							<view @click.stop="handleSelectZhang(item,index)" class="collapse-title">
								<view class="collapse-num-box">{{index+1}}</view>
								<!-- 章名 -->
								<text class="collapse-name">{{item.zhangName}}</text>
								<!-- 锁 -->
								<!-- <template v-if="AuthCode !== 'VIP'">
									<view class="collapse-lock" v-if="index!=0"></view>
								</template> -->
							</view>
						</template>
						<view class="collapse-content-box">
							<view v-for="(jie,cindex) in item.jieList" class="collapse-content-item"
								@click="handleJieClick(item,jie,index,cindex)">
								<text class="jie-index">{{`${index+1}.${cindex+1}`}}</text>
								<text class="text">{{jie.jieName}}</text>
							</view>
						</view>
					</uni-collapse-item>
				</template>
			</uni-collapse>
			<tip-small-dialog ref="confirmDialogRef" @confirm-btn="handleConfirmPay"
				:content="Message"></tip-small-dialog>
			<tip-big-dialog ref="youkeDialogRef" @confirm-btn="ykConfirm" :imgShow="true"></tip-big-dialog>
		</scroll-view>
	</uni-popup>
</template>

<script setup>
	import {
		useCatalogue
	} from './useCatalogue';
	import {
		ref,
	} from "vue";
	import {
		getUserIdentity
	} from "@/utils/common.js"
	import {
		MESSAGE_VISITER_TO_LOGIN,
		MESSAGE_BEFORE_PAY
	} from "@/utils/constant.js"
	import tipSmallDialog from '@/components/dialog/tipSmallDialog.vue'
	import tipMiddleDialog from '@/components/dialog/tipMiddleDialog.vue';
	import tipBigDialog from '@/components/dialog/tipBigDialog.vue';
	import cacheManager from "@/utils/cacheManager.js";
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';

  // 旧道，上下分册 LevelId
	const ShuxueObj = {
		7: 6,
		8: 6,
		9: 11,
		10: 11,
		11: 11,
		12: 12,
	}


	const growthType = ref(null);
	const AuthCode = ref(null);
	const scrollTop = ref(0)
	const subjectId = ref(null)
	const shuxueShangxia = ref(0);
	const levelId = ref(null);

	onShow(() => AuthCode.value = getUserIdentity()); // 用户身份
	onLoad((options) => {
		if (cacheManager.get('auth')) {
			subjectId.value = cacheManager.get('auth').subjectId;
		} else {
			subjectId.value = options.subjectId;
		}
		if (subjectId.value == 1) {
			if (cacheManager.get('auth')) {
				levelId.value = cacheManager.get('auth').levelId;
			} else {
				levelId.value = options.levelId;
			}
			// shuxueShangxia.value = ShuxueObj[levelId.value];
		}

	})

	const $emit = defineEmits(['change-zhang'])

	const {
		getCatalogue
	} = useCatalogue();

	const popupRef = ref(null); // 索引
	const confirmDialogRef = ref(null);
	const activeCollapse = ref('');
	const Message = MESSAGE_BEFORE_PAY;
	const youkeDialogRef = ref(null);
	const selectZhang = ref(null);
  const list = ref([])
  const jieTexts = ref([])

	function handleJieClick(item, jie, index, cindex) {
		selectZhang.value = item;
		// this.$emit('listSelectJieClick', item, jie, cindex);
		$emit('change-zhang', Object.assign({}, item));
		handleClose();
	}

/*	function catalogueBjFun() {
		if (subjectId.value == 1) {
			// 数学
			return 'static/images/catalog/catalog-shuxue-bj.png'
		} else if (subjectId.value == 2) {
			// 英语
			return 'static/images/catalog/catalog-yingyu-bj.png'
		}
	}*/

	function ykConfirm() {
		uni.redirectTo({
			url: '/pages/login/index'
		});
	}

	/**
	 * @summary 展示弹窗 暴露函数
	 */
	async function showPopup(data) {
		handleShow(data);
	}

  function getFormatZhangListByArray(data) {

    const myList = data.reduce((acc, curr) => acc.concat(curr.zhangList || []), [])

    const jiedian = data[0].zhangList.length;

    return {
      myList,
      jiedian,
      jieText: data.map(item => item.lable)
    }
  }

	/**
	 * @summary 展示目录弹窗
	 */
	function handleShow(data) {
    getCatalogue().then(([err, wlist]) => {
      if (err) {
        return;
      }
      const {myList,jiedian, jieText} = getFormatZhangListByArray(wlist)
      list.value = myList;
      if (list.value) {
        jieTexts.value = jieText;
        shuxueShangxia.value = jiedian;
        if (data) {
          let callback = null;
          const index = myList.findIndex(item => item.zhangId == data.zhangId);
          scrollTop.value = 0;
          activeCollapse.value = '';
          // 滚动高度
          callback = () => {
            console.log('uni.getTopWindowStyle()', uni.getSystemInfoSync().screenWidth)
            if (subjectId.value == 2) {
              // 英语
              activeCollapse.value = index + '';
              scrollTop.value = (uni.getSystemInfoSync().screenWidth / 750) * 50 * index;
            } else {
              // 数学
              if (index < shuxueShangxia.value) {
                activeCollapse.value = index + '';
                scrollTop.value = (uni.getSystemInfoSync().screenWidth / 750) * 50 * index + (uni
                    .getSystemInfoSync().screenWidth / 750) * 50;
              } else {
                activeCollapse.value = index + '';
                scrollTop.value = (uni.getSystemInfoSync().screenWidth / 750) * 50 * index + (uni
                    .getSystemInfoSync().screenWidth / 750) * 50 * 2;
              }
            }
          }
          setTimeout(() => callback(), 50)
        }
      }
      popupRef.value.open('center');
    })
	}

	/**
	 * @summary 关闭目录弹窗
	 */
	function handleClose() {
		popupRef.value.close();
	}
	/**
	 * @summary 选中
	 * @param({zhangId:string}) data
	 */
	function handleSelectZhang(data, index) {
		selectZhang.value = data;
		$emit('change-zhang', Object.assign({}, data));
		handleClose();
	}

	function handleConfirmPay() {
		const url =
			`/pages/pay/svip?subjectId=${subjectId.value}&formPage=studyWithCatalgue&selectZhangId=${selectZhang.value.zhangId}`
		uni.redirectTo({
			url
		})
	}
	defineExpose({
		showPopup
	})
</script>