<template>
	<view class="courseWrap">
		<!-- 公共组件-每个页面必须引入 -->
		<public-module></public-module>
		<z-nav-bar :title="pageTitle" @back='handleBack'>
			<view class="curseSet" slot="right" 
			v-if="tagId!='71'"
			@click="shuomingPage('/pages/course/courseSet',tagId,pid)">
				<uni-icons type="info" size="24"></uni-icons> 课程说明
			</view>
			<view class="curseSet" slot="right" v-else>
				<uni-icons type="location" size="18"></uni-icons>
				<picker class="picker" mode="multiSelector" :range="multiArray" @change="bindMultiPickerChange" @columnchange="bindMultiPickerColumnChange">
					<text @click="changeCountry">{{countryText}}</text>
				</picker>
			</view>
		</z-nav-bar>
		<view class="tabsBox" :class="[fixed ? 'fixed' : '' ]">
			<u-tabs v-if="tabList.length > 0" :class="['tabList']" @click="fatherClick" :current="curTagId"
				:activeStyle="activeStyle" :scrollable="scrollable" :list="tabList"
				itemStyle="padding-left: 15px; background-color:#fff;  padding-right: 15px; height: 50px;"></u-tabs>
		</view>
		<view class="containerBg" v-if="tagId!='71'">
			<view class="subCate flex" v-if="subList.length> 0">
				<text :class="['item',subTabId == item.id ? 'active' : '']" v-for="(item, index) in subList"
					@click="curseClick(item)" :key="index">{{item.title}}</text>
			</view>
			<view class="learnBox box">
				<view class="newBox">
					<view class="item flexbox" v-for="(item, index) in courseList" :key="index" @click="onPageJump('/pages/course/courseDetail',item.id)">
						<view class="imgcontainer">
							<image :src="item.squareImage"></image>
						</view>
						<view class="buyItems">
							<view class="txt555">
								<text>{{item.title}}</text>
							</view>
							<view class="jianjie" v-html="item.content">

							</view>
							<view class="tag-view">
								<uni-tag v-if="item.level != 0" style="margin-right: 10rpx;" :text="item.level == 1 ? '初级':'高级'" type="primary" size="small" />
								<uni-tag v-if="item.selective != 0 && item.selective == 1" style="margin-right: 10rpx;" text="必修" size="small" type="warning" />
								<uni-tag v-if="item.selective != 0 && item.selective == 2" style="margin-right: 10rpx;" text="选修" size="small" type="success" />
							</view>
						</view>
						<view class="btn_box">
							<view class="btn_box_price" v-if="item.courseCatalogueEntityList.length==1">
								<text v-if="item.courseCatalogueEntityList[0].halfFee==0">免费</text>
								<text v-else>¥{{item.courseCatalogueEntityList[0].halfFee}}/{{item.courseCatalogueEntityList[0].fee}}</text>
							</view>
							
							<view class="btn_box_price" v-if="item.courseCatalogueEntityList.length>1">
								<text v-for="(v,i) in item.courseCatalogueEntityList" :key="i">
									{{formatContent(v.title)}}<text v-if="i !== item.courseCatalogueEntityList.length - 1">/</text>
								</text>
								<text v-if="item.courseCatalogueEntityList[0].halfFee==0" style="padding-left: 20rpx;">免费</text>
								<text v-else style="margin-left: 20rpx;">各{{item.courseCatalogueEntityList[0].halfFee}}/{{item.courseCatalogueEntityList[0].fee}}</text>
							</view>
							<text class="btn_box_btn">了解课程</text>
						</view>
					</view>
				</view>
				<u-divider v-show="status == 2" text="已加载全部"></u-divider>
				<u-divider v-show="status == 3" text="暂无数据"></u-divider>
				<u-divider v-show="status == 1" text="加载中..."></u-divider>
			</view>
			<view>
				<u-back-top :scroll-top="scrollTop" bottom="150" :customStyle='bgiStyle'
				:iconStyle="iconStyle"></u-back-top>
			</view>
			<public-module></public-module>
			<z-navigation></z-navigation>
		</view>
		<view class="formBlock" v-if="tagId=='71'">
			<view v-for="(item,index) in formList" :key="index" class="form_item">
				<text class="form_title">{{item.title}}</text>
				<view class="form_solid">
					<view class="form_des">{{item.des}}</view>
					<picker mode="multiSelector" :range="multiArray" @change="bindMultiPickerChange" @columnchange="bindMultiPickerColumnChange" v-show="countryText=='城市'">
						<u-button class="form_btn">进入测试</u-button>
					</picker>
					<u-button v-show="countryText!='城市'" class="form_btn" @click="test(item)">进入测试</u-button>
				</view>
			</view>
			
			<z-navigation></z-navigation>
		</view>
	</view>
</template>

<script>
import musicPlay from '@/components/music.vue'
import $http from '@/config/requestConfig.js';
var clear;
import {
	mapState
} from 'vuex';
export default {
	data() {
		return {
			playData: {},
			tagId: null,
			pid:null,
			fixed: false,
			fatherTabId: null,
			subTabId: null, //
			bgiStyle: {
				background: '#fff'
			},
			iconStyle: {
				fontSize: '40rpx',
				fontWeight: 'bold',
				color: '#258feb',
			},
			scrollTop: 0,
			activeStyle: {
				color: '#333',
				fontWeight: 'bold',
				transform: 'scale(1.2)'
			},
			subList: [],
			scrollable: false,
			pageTitle: '',
			tabList: [],
			curTagId: 0,
			courseList: [],
			status: 3, // 0 不显示, 1 加载中，2 加载全部完成，3 暂无数据
			page: 1,
			flag: true, // 函数是否执行完
			//心身量表
			formList: [],
			//选择城市弹窗
			cityList: [],
			isPicker: false,
			countries: [],
			multiArray: [[], []],
			value: [0, 0],
			selectedData: {},  //城市
			countryIndex: 0,  //抑郁症文字区分国家展示
			countryText: '',
			//列表显示价格
			courseCatalogueEntityList: []
		};
	},
	//第一次加载
	onLoad(e) {
		// 隐藏原生的tabbar
		uni.hideTabBar();
		this.tagId = e.id
		this.pageTitle = e.title
		this.pid = e.pid
		this.getCateList(this.tagId)
		//如果是心身量表栏目
		if(this.tagId=='71'){
			this.getFormList();
		}
		
		//显示城市数据
		this.getCityList();
		let countryData = uni.getStorageSync('countryData');
		let text= '';
		if(countryData&&countryData.country){
			text = countryData.country
			if(countryData.city){
				text = text + countryData.city
			}
		}else{
			text= '城市';
		}
		this.countryText = text;
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
		if (this.scrollTop > 500) {
			this.fixed = true
		} else {
			this.fixed = false
		}
	},
	onPullDownRefresh() {
		this.status = 3
		this.page = 1
		this.courseList = []
		this.getData(this.subTabId)
		uni.stopPullDownRefresh()
	},
	onReachBottom() {
		if (this.status != 2 && this.flag) {
			this.page++
			this.getData(this.subTabId)
		}
	},
	computed: {
		...mapState(['userInfo'])
	},
	//页面显示
	onShow() {
		//隐藏原生的tabbar
		uni.hideTabBar();
		uni.removeStorageSync('data')
		uni.removeStorageSync('selectedData')
		uni.removeStorageSync('resList')
	},
	components: {
		musicPlay
	},
	//方法
	methods: {
		//判断显示‘上/中/下’
		formatContent(content) {
		  const keywords = ["上部", "中部", "下部"];
		  let result = [];
			
		  // 判断是否包含关键字
		  keywords.forEach((keyword) => {
			if (content.includes(keyword)) {
			  result.push(keyword.substring(0, 1));
			}
		  });
		  return result.join("");
		},
		//获取国家-一级
		getCountryList() {
			$http.request({
				url: "common/baseArea/getAllBaseArea",
				method: "POST",
				data: {},
				header: {
					'Content-Type': 'application/json'
				},
			})
			.then(res => {
				if (res.code == 0) {
					this.countries = res.baseAreas;
					this.countries.forEach((country, index)=>{
						if(country.code=='86'){
							this.countries[index].cities = this.cityList;
						}
					})
					
					//初始化 picker 数据
					this.initPickerData();
				}
			}).catch(e => {
				
			});
		},
		//获取城市-二级
		getCityList() {
			$http.request({
				url: "common/province/getProvinceList",
				method: "POST",
				data: {},
				header: {
					'Content-Type': 'application/json'
				},
			})
			.then(res => {
				if (res.code == 0) {
					const newCityList = res.provinceList.map( city => {
						return city.provName;
					});
					this.cityList = newCityList;
					this.getCountryList();
				}
			}).catch(e => {
				
			});
		},
		//展示城市数据
		initPickerData() {
			//第一列是国家名
			const countryNames = this.countries.map(item => item.title);
			this.multiArray[0] = countryNames;
			//默认选择中国，并加载其省份
			if (this.countries[0].cities) {  //如果默认显示的是第一个-中国，则显示城市列
				this.multiArray[1] = Object.keys(this.countries[0].cities).map(key => this.countries[0].cities[key]);
			} else {
				this.multiArray[1] = [];
			}
			//强制更新视图
			this.$set(this, 'multiArray', [...this.multiArray]);
		},
		//picker修改值
		bindMultiPickerChange(e) {
			this.value = e.detail.value;
			this.updateCurrentSelection();
		},
		//修改动作
		bindMultiPickerColumnChange(e) {
			let data = {
				multiArray: this.multiArray,
				value: this.value
			};
			if (e.detail.column === 0) {
				// 如果是第一列（国家）改变了，则需要更新第二列（城市）
				const selectedCountry = this.countries[e.detail.value];
				if (selectedCountry.cities) {
					// 如果选择了中国，加载省份
					data.multiArray[1] = Object.keys(selectedCountry.cities).map(key => selectedCountry.cities[key]);
					data.value = [e.detail.value, 0];
				} else {
					// 否则清空第二列
					data.multiArray[1] = [];
					data.value = [e.detail.value, 0];
				}
			}
		
			this.$set(this, 'multiArray', [...data.multiArray]);
			this.value = data.value;
		},
		updateCurrentSelection() {
			const countryIndex = this.value[0];
			this.countryIndex = countryIndex;  //判断抑郁结果  标准的定义文字显示
			const cityIndex = this.value[1];
			const selectedCountry = this.multiArray[0][countryIndex];
			const selectedCity = this.multiArray[1][cityIndex];
			
			this.selectedData = {
				country: selectedCountry
			}
			this.countryText = selectedCountry;
			if(selectedCity){
				this.selectedData.city = selectedCity;
				this.countryText = selectedCountry + selectedCity;
			}else{
				this.selectedData.city = ''
			}
			uni.setStorageSync('countryData', this.selectedData)
		},
		//点击地理位置修改城市
		changeCountry(){
			this.initPickerData();
		},
		handleBack(){
			uni.setStorageSync('fixed',true)
		},
		surl(imageurl) {
			return `url(${imageurl})`
		},
		getCateList(id) {
			$http.request({
					url: "medical/home/getChildCourseMedicalTree",
					method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
					data: {
						"id": id,
					},
					header: { //默认 无 说明：请求头
						'Content-Type': 'application/json'
					},
				})
				.then(res => {
					if (res.code == 0) {
						if (res.labels.length > 0) {
							var list = []
							res.labels.forEach(item => {
								item.name = item.title
							})
							this.tabList = res.labels
							// this.fatherTabId = this.tabList[0].id
							if (this.tabList[0].isLast == 1) { // 终极
								this.subList = []
								this.subTabId = this.tabList[0].id
							} else { //非终极
								if (this.tabList[0].children.length > 0) {
									this.subList = this.tabList[0].children
									this.subTabId = this.subList[0].id

								} else {
									this.subList = []
									this.subTabId = null
								}
							}
							if (this.subTabId) {
								// console.log(this.subTabId, this.subList[0].title, '初始进入')
								this.courseList = []
								this.status = 1
								this.getData(this.subTabId)
							}


						}else{
							this.subList = []
							this.subTabId = id
							this.getData(id)
						}
						console.log(this.curTagId, '当前高亮')
					}
				}).catch(e => {
					console.log(e, '获取子分类报错')
				});
		},
		fatherClick(e) {
			this.page = 1
			var item = e
			if (item.isLast == 1) { // 终极
				this.subList = []
				this.subTabId = item.id
			} else {
				if (item.children.length > 0) { // 非终极
					this.subList = item.children
					this.subTabId = item.children[0].id
				} else {
					this.subList = []
					this.subTabId = null
				}
			}
			if (this.subTabId) {
				this.status = 1
				this.courseList = []
				this.getData(this.subTabId);
			}

		},
		curseClick(item) {
			this.subTabId = item.id
			this.courseList = []
			this.page = 1
			this.getData(this.subTabId);
		},
		getData(id) {
			this.status = 1
			this.flag = false
			$http.request({
					url: "medical/home/getMedicalCourseList",
					method: "POST",
					data: {
						"id": id,
						"limit": 12,
						"page": this.page
					},
					header: {
						'Content-Type': 'application/json'
					},
				})
				.then(res => {
					if (res.code == 0) {
						if (res.courses.records.length > 0) {
							var list = res.courses.records
							this.courseList = this.courseList.concat(list)
							if (res.courses.pages > this.page) {
								this.status = 0
							} else {
								this.status = 2
							}
						} else if (this.page > 1) {
							this.status = 2 // 加载完成

						} else {
							this.status = 3 // 暂无数据
						}
						this.flag = true
					}
					
				}).catch(e => {
					this.flag = true
					console.log(e, '数据报错')
					this.status = 3
					uni.showToast({
						title:`获取数据失败`,
						icon:'error'
					})
				});
		},
		// 跳转
		onPageJump(url,id) {
			uni.navigateTo({
				url: `${url}?id=${id}`
			});
		},
		shuomingPage(url,id,pid){
			uni.navigateTo({
				url: `${url}?id=${id}&pid=${pid}`
			});
		},
		//心身量表
		getFormList() {
			$http.request({
				url: "common/selfEvaluationForm/formList",
				method: "POST",
				data: {},
				header: {
					'Content-Type': 'application/json'
				},
			})
			.then(res => {
				if (res.code == 0) {
					this.formList = res.formList;
				}
			}).catch(e => {
				
			});
		},
		//进入测试
		test(item){
			uni.setStorageSync('data',JSON.stringify(item))
			uni.navigateTo({
				url: '/pages/course/scale'
			})
		}
	},
};
</script>
<style lang="scss" scoped>
	@import '@/style/mixin.scss';

	.courseWrap{
		height: 100vh;
		background-color: #f4f7ff;
	}
	.containerBg {
		background-color: $containerColor;
		padding: 0 20rpx;

	}
	.curseSet{margin-right: 18rpx; font-size: 28rpx; display: flex; align-items: center;}
	.fixed {
		position: fixed;
		z-index: 1; width: 100%; background-color: #fff;
	}

	.newBox {
		.flexbox{
			padding-bottom: 100rpx !important;
		}
		.item {
			position: relative;
			margin-bottom: 20rpx;
			background-color: #fff;
			border-radius: 20rpx;
			@include ptop_bottm(20px);
			@include pleft_right(10px);

			@include mshadow(10px, 1) .imgcontainer {
				width: 250rpx;
				height: 250rpx;
				margin-right: 20rpx;
				
				image {
					width: 100%;
				}
			}
			.btn_box{
				position: absolute;
				bottom: 20rpx;
				right: 20rpx;
				display: flex;
				align-items: center;
				.btn_box_price{
					font-size: 32rpx;
					font-weight: 500;
					margin-right: 30rpx;
					color: red;
					line-height: 54rpx;
				}
				.btn_box_btn{
					width: 140rpx;
					height: 54rpx;
					text-align: center;
					line-height: 54rpx;
					border-radius: 20rpx;
					@include theme("btn_bg");
					font-size: 28rpx; color: #fff;
				}
			}
			.buyItems {
				width: 60%;
			}

			.jianjie {
				line-height: 30rpx; height: 60rpx; overflow: hidden; 
				overflow: hidden!important;
				margin-top: 10rpx;
				font-size: 24rpx;
				@include bov();
				color: #9c9c9c;
			}

			.txt555 {
				font-size: 30rpx;
				color: #000;
				@include bov()
			}
		}
	}

	.subCate {
		padding-top:10px;
		padding-bottom: 10px;
		display: flex;
		.item {		
			border: 1px solid #bfcad9;
			display: inline-block;
			text-align: center;
			font-size: 26rpx;
			background-color: #fff;
			border-radius: 4px; width: 100%;
			color: #333;
			margin-right: 16rpx;
			padding: 14rpx 30rpx;
		}

		.item:last-child() {
			margin-right: 0;
		}

		.item.active {
			border-color: $themeColor;
			background-color: $themeColor;
			color: #fff;
		}
	}

	.tabList {
		text-align: center;
	}

	.flexbox {
		display: flex;
	}

	.imgcontainer {
		background-color: $imgBg;
		display: flex;
		justify-content: center;
		align-items: center;
		overflow: hidden;
		image{
			width: 100%;
			height: 250rpx;
		}
	}

	.box {
		// background-color: #fff;		
		min-height: calc(100vh - 270rpx);
	}

	.learnBox {
		margin-bottom: 10px;
		padding-top: 10px;

		.learn {
			flex-wrap: wrap;
			justify-content: space-between;
			margin-top: 20rpx;

			.item {
				width: 48%;
				margin-bottom: 16px;

				overflow: hidden;

				image {
					width: 100%;
					height: 200rpx;
				}

				.txt555 {
					display: block;
					text-align: center;
					height: 40rpx;
					width: 100%;
					line-height: 40rpx;
					@include bov(1);
					margin-top: 10rpx;
					font-size: 24rpx;

				}

			}
		}
	}
	
	.formBlock{
		background-color: #f4f7ff;
		padding: 20rpx;
	}
	.form_item{
		margin-bottom: 50rpx;
	}
	.form_solid{
		border-radius: 20rpx;
		background-color: #fff;
		padding: 20rpx 20rpx 50rpx;
		box-shadow: 0px 0px 10px 0px #a7bbe4;
	}
	.form_title{
		display: inline-block;
		width: 100%;
		font-size: 42rpx;
		color: #333;
		text-align: center;
		padding: 30rpx 0 20rpx;
	}
	.form_des{
		font-size: 30rpx;
		line-height: 48rpx;
		color: #666;
	}
	.form_btn{
		width: 300rpx;
		height: 70rpx;
		margin: 40rpx auto 0;
		color: #fff;
		font-size: 30rpx;
		background: #258feb;
		border-radius: 10rpx;
	}
	
	.popup_mark{
		width: 100%;
		height: 100%;
		background: #000;
		opacity: 0.5;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
	}
	.popup_block{
		width: 580rpx;
		height: 360rpx;
		position: fixed;
		top: 50%;
		left: 50%;
		margin-top: -180rpx;
		margin-left: -290rpx;
		background: #fff;
		z-index: 999;
		border-radius: 5px;
	}
	.popup_title{
		display: block;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 32rpx;
		color: #333;
		text-align: center;
		border-bottom: 1rpx solid #f0f0f0;
	}
	.popup_con{
		font-size: 28rpx;
		padding-top: 50rpx;
		text-align: center;
	}
	.popup_picker{
		position: absolute;
		bottom: 0;
		width: 100%;
	}
	.scale_btn{
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		color: #fff;
		font-size: 28rpx;
		background: #258feb;
		border: none;
		border-radius: 0 0 5px 5px;
	}
</style>