<template>
	<page-meta :page-style="'padding-bottom: 0;'+'overflow:'+((showFilter||show||showPoster)?'hidden':'visible')"/>
	<view style="background-color: #F6F6F6;">
		<!-- 没有权限 -->
		<block v-if="noAuthor ==1 && isFinished">
			<view class="sandTable-noAuthor">
				<block v-if="!applyer.hasApply">
					<image :src="globalImgUrls.sandBoxNoAuthor" mode="aspectFit"></image>
					<text style="margin-top: 48rpx;">您暂无权限查看沙盘推演</text>
					<text style="margin-top: 20rpx;">若想查看可以申请开通</text>
					<button @click="toApply">立即申请</button>
				</block>
				<block v-else>
					<image class="img-wait" :src="globalImgUrls.chartWait" mode="widthFix" 
					style="width: 186rpx;margin-top: 200rpx;width: 186rpx;margin-bottom: 50rpx;"></image>
					<text style="margin-bottom:15px">您已提交申请</text>
					<text>请等待销售人员与您联系</text>
				</block>
			</view>
		</block>
		<block v-if="noAuthor ==2 && isFinished">
			<view class="sandTable-noAuthor">
				<image :src="globalImgUrls.sandBoxNoAuthor" mode="aspectFit"></image>
				<text style="margin-top: 48rpx;">您暂无权限查看沙盘推演</text>
				<text style="margin: 20rpx 0 6rpx 0;">若想查看请联系对口销售</text>
				<view>
					<text>{{salesData.name}}：</text><text class="sales-mobile" @click="callToSales">{{salesData.phone}}</text>
				</view>
			</view>
		</block>
		<!-- 有权限 -->
		<view v-show="noAuthor ==0 && isFinished" style="padding-top: 156rpx;">
			<view style="position: fixed;top: 0;width: 100vw;">
				<view style="height: 2rpx;background-color: #F6F6F6;"></view>
				  <view class="search-wrap">
					  <van-search
						  shape="round"
						  placeholder="沙盘图名称搜索"
						  clear-trigger="always"
						  style="flex-grow: 1"
						  :value="sandTableQuery.keyword"
						  @change="searchValChange"
						  @search="onSearch"
						  @clear="onClearSearch"
						  placeholderStyle="color: #999999;"
					  />
					  <view class="filtration-icon-zone" @click="showFilter=true">
						<image
						  src="../static/sandTable/sandTable_filtration.png"
						  mode="widthFix"
						  class="menu-icon"/>
						<text>筛选</text>
					  </view>
				  </view>
			</view>
			<!-- 无数据 -->
			<view class="sandTable-noData" v-if="!list">
				<image :src="globalImgUrls.sandBoxNoAuthor" mode="aspectFit"></image>
				<text >暂无数据</text>
			</view>
			<view class="sandTable-list" v-else>
				<view class="sandTable-box" v-for="(item,index) in list" :key="item.sandbox_id">
					<view class="sandTable-box-top">
						<view class="sandTable-box-topL">
							<view class="sandTable-tag">
								{{item.chart_permission_name}}
							</view>
							<rich-text :nodes="item.name" class="sandTable-name"></rich-text>
						</view>
						<view class="sandTable-box-topR">
							<image src="../static/sandTable/fullScreen.png" style="margin-right: 50rpx;" @click="previewImage(index)"></image>
							<image src="../static/sandTable/sandTable-share.png" @click="generatePoster('detail',item)"></image>
						</view>
					</view>
					<view class="sandTable-item" @click="previewImage(index)">
						<image :src="item.pic_url" mode="aspectFit"></image>
<!-- 						<view class="sandTable-item-origin">
							来源：弘则研究
						</view> -->
					</view>
				</view>
				<view v-if="list.length==total && list.length>0" class="bottom_text">已经到底了</view>
			</view>
		</view>
	</view>
	<!-- 筛选弹窗 -->
	<van-popup :show="showFilter" round position="bottom" @close="showFilter = false" z-index="99999" :safe-area-inset-bottom="true" >
		<view class="filter-container">
			<view class="filter-container-header">
				<text>全部筛选</text>
				<text style="color: #E3B377;" @click="showFilter=false">取消</text>
			</view>
			<view class="list-box">
				<van-collapse accordion @change="selectFisrtClassify" :value="selectedFirstId" :border="false">
					<van-collapse-item
						:title="item.classify_name" 
						:name='item.id' 
						:border="false"
						v-for="item in classfyList"
						:key="item.id"
					>
						<van-row gutter="5">
							<van-col 
								:span="_item.chart_permission_name.length>7?16:8" 
								v-for="_item in item.list" 
								:key="_item.chart_permission_id"
							>
								<text 
									:class="['list-item',_item.chart_permission_id==selectedSecondId&&'list-item-active']" 
									@click="handleSelectPerItem(_item)"
								>{{_item.chart_permission_name}}</text>
							</van-col>
						</van-row>
					</van-collapse-item>
				</van-collapse>
			</view>
		</view>
	</van-popup>
	<!-- 分享按钮 -->
	<image @click="generatePoster('list')" class="share-icon" src="@/static/share-poster-icon.png" mode="aspectFill" v-if="noAuthor==0&&isFinished"/>
	<!-- 生成海报弹窗  -->
	<div class="share-poster-wrap" @touchmove.prevent>
		<div class="poster-mask" v-if="show||showPoster" @click="showPoster=false" @touchmove.prevent></div>
        <div class="loading-box" v-if="show">
            <img class="load-img" src="../static/loading.png"/>
            <div>海报生成中...</div>
        </div>
		<img v-if="showPoster" class="poster-img" mode="widthFix" :src="posterImg" show-menu-by-longpress />
	</div>

</template>

<script>
	import {apiSandTableList,apiSandTableDetail} from "../api/sandTable.js"
	import {apiReportIndexPageAuthList} from "../api/report.js"
	import {apiGetPoster} from "../api/common.js"
	import {apiApplyPermission} from "../api/user.js"
	export default {
		data() {
			return {
				sandTableQuery:{
					page_size: 20,
					curr_page: 1,
					keyword:'' ,
					chart_permission_id: 0,
					is_high_light:false // 是否高亮
				},
				total:0,
				isRequseting:false,
				showFilter:false,
				list:[],
				classfyList:[],
				selectedFirstId:0,
				selectedSecondId:0,
				// 是否显示过全部加载弹窗
				haveShowToast:false,
				showPoster:false,
				show:false,
				// 是否跳转到申请结果页面
				haveGoToResult:false,
				// 是否请求完成
				isFinished:false,
				posterImg:'',
				// 没有权限  1:立即申请 2:联系销售
				noAuthor:0,
				// 销售信息
				salesData:{
					phone:'',
					name:''
				},
				// 申请权限时的用户信息
				applyer:{
					name:'',
					company:'',
					// 是否已经申请
					hasApply:false,
					// 状态
					status:''
				}
			}
		},
		onLoad(options) {
			// 有sandbox_id 说明是单个分享进来的
			if(options.sandbox_id){
				this.selectedFirstId = options.firstClassifyId || 0
				this.selectedSecondId = options.chart_permission_id || 0
				this.getSandBoxDetail(options.sandbox_id)
			}else{
				this.sandTableQuery.keyword = options.keyword || ""
				this.selectedFirstId = options.firstClassifyId || 0
				this.sandTableQuery.chart_permission_id = this.selectedSecondId = options.chart_permission_id || 0
				this.sandTableQuery.is_high_light = options.is_high_light || false
				this.getSandBoxList()
			}
			this.getClassifyList()
		},
		onShow(options) {
			// 预览图片结束时，会触发onShow，切回竖屏
			uni.setPageOrientation({orientation : "portrait"})
			if(this.haveGoToResult){
				//从申请结果页面回来 
				this.getSandBoxList()
				this.haveGoToResult=false
			}
		},
		// 小程序自带分享
		onShareAppMessage() {
			let {keyword,chart_permission_id,is_high_light} = this.sandTableQuery
		    return {
		        title:'沙盘推演',
				path:`/pages-sandTable/sandTable?keyword=${keyword}&chart_permission_id=${chart_permission_id}`+
				`&is_high_light=${is_high_light}&firstClassifyId=${this.selectedFirstId}`
		    }
		},
		onPullDownRefresh() {
			this.sandTableQuery.curr_page=1
			this.sandTableQuery.chart_permission_id = this.selectedSecondId = this.selectedFirstId=0
			this.sandTableQuery.keyword=''
			this.is_high_light=false
			this.haveShowToast=false
			this.getSandBoxList('stopPullDown')
			this.getClassifyList()
		},
		onReachBottom() {
			if(this.isRequseting) return 
			if(this.list.length>=this.total && this.total!=0){
				// if(this.haveShowToast) return
				// // 只显示一次
				// this.haveShowToast = true
				// uni.showToast({
				// 	title:"没有了~",
				// 	icon:'none'
				// })
				return
			}
			this.sandTableQuery.curr_page++
			this.getSandBoxList()
		},
		methods: {
			// 获取沙盘图数据
			getSandBoxList(option){
				this.isRequseting=true
				apiSandTableList(this.sandTableQuery).then(({data:{list,paging,type,name,mobile,customer_info},code})=>{
					if(option == 'stopPullDown'){
						uni.stopPullDownRefresh()
					}
					// 403 没有权限
					if(code==403){
						this.applyer.name = customer_info.name
						this.applyer.company = customer_info.company_name
						this.applyer.hasApply = customer_info.has_apply
						this.applyer.status = customer_info.status
						if(type == 'apply'){
							// 申请
							this.noAuthor =1
						}else{
							// 联系销售
							this.noAuthor =2
							this.salesData.name=name
							this.salesData.phone=mobile
						}
						return 
					}
					if(this.sandTableQuery.curr_page==1){
						this.list = list
						this.total = paging.totals
					}else{
						this.list = [...this.list,...list]
					}
					this.noAuthor=0
				})
				.finally(res=>{
					this.isRequseting=false
					this.isFinished=true
					this.showFilter=false
				})
			},
			getSandBoxDetail(sandbox_id){
				this.isRequseting=true
				apiSandTableDetail({sandbox_id}).then(({data,code})=>{
					if(code==403){
						this.applyer.name = data.customer_info.name
						this.applyer.company = data.customer_info.company_name
						this.applyer.hasApply = data.customer_info.has_apply
						this.applyer.status = data.customer_info.status
						if(data.type == 'apply'){
							// 申请
							this.noAuthor =1
						}else{
							// 联系销售
							this.noAuthor =2
							this.salesData.name=data.name
							this.salesData.phone=data.mobile
						}
						return 
					}
					this.list= [data]
					this.noAuthor=0
				})
				.finally(res=>{
					this.isRequseting=false
					this.isFinished=true
					this.showFilter=false
				})
			},
			// 获取分类数据
			getClassifyList(){
				apiReportIndexPageAuthList().then(({data:{permission_list}})=>{
					// 过滤掉'更多报告' 和 没有权限的分类
					this.classfyList = permission_list.filter(item => item.sort!=100000)
					this.classfyList.forEach(item=>{
						item.list=item.list.filter(it=>it.auth_ok)
					})
					this.classfyList=this.classfyList.filter(item=>item.list.length!=0)
				})
			},
			// 权限申请
			toApply(type=''){
				if(type=='auto'){
					apiApplyPermission({
						company_name:this.applyer.company,
						real_name:this.applyer.name,
						source:7,
						from_page:'沙盘推演',
					}).then(res=>{
						console.log('自动申请成功');
					})
				}else{
					if(this.applyer.status==='流失'){
						apiApplyPermission({
							company_name:this.applyer.company,
							real_name:this.applyer.name,
							source:7,
							from_page:'沙盘推演',
						}).then(res=>{
							this.haveGoToResult=true
							uni.navigateTo({url:'/pages-applyPermission/applyResult'})
						})
					}else{
						uni.navigateTo({ url: '/pages-applyPermission/applyPermission?source=7&from_page=沙盘推演' })
					}
				}
			},
			// 联系销售申请权限
			callToSales(){
				if(!this.applyer.hasApply){
				    this.toApply('auto')
				}
				uni.makePhoneCall({
				    phoneNumber: this.salesData.phone,
				    success: (result) => {},
				    fail: (error) => {}
				})
			},
			// 搜索内容变化
			searchValChange(e){
			  this.sandTableQuery.keyword=e.detail
			  // this.sandTableQuery.is_high_light = true
			  // this.getSandBoxList()
			},
			// 清除搜索内容
			onClearSearch(){
				this.sandTableQuery={
					page_size: 20,
					curr_page: 1,
					keyword:'' ,
					chart_permission_id: 0,
					is_high_light:false
				}
				this.selectedFirstId = this.selectedSecondId = 0
				this.haveShowToast=false
				this.getSandBoxList()
			},
			// 确认搜索
			onSearch(){
			  this.sandTableQuery.chart_permission_id= this.selectedFirstId = this.selectedSecondId = 0
			  this.sandTableQuery.is_high_light = true
			  this.haveShowToast=false
			  this.getSandBoxList()
			},
			// 选中一级分类
			selectFisrtClassify(e){
				this.selectedFirstId = e.detail
			},
			handleSelectPerItem(item){
				if(this.selectedSecondId==item.chart_permission_id){
				    this.sandTableQuery.chart_permission_id=this.selectedSecondId=0
				}else{
				    this.sandTableQuery.chart_permission_id=this.selectedSecondId=item.chart_permission_id
				}
				this.sandTableQuery.curr_page=1
				uni.pageScrollTo({
					scrollTop:0,
					duration:300
				})
				this.showFilter=false
				this.getSandBoxList()
			},
			// 预览图片
			previewImage(index){
				// 先切换横屏才预览图片 ，预览图片开启之后 切换不了横屏
				uni.setPageOrientation({orientation : "landscape"}).finally(()=>{
					// 在回调函数中 用setTimeout将预览图片的任务 再往后排 不然可能会切换失败
					setTimeout(()=>{
						uni.previewImage({
							urls:this.list.map(item=> item.pic_url),
							current:index,
							showmenu:false
						})
					},10)
				})
			},
			// 生成海报
			generatePoster(type,item=''){
				this.handleCreatePoster(type,item)
			},
			async handleCreatePoster(type,item){
			    this.show=true
				let code_scene = '',source='',parsJson={}
				if(type == 'detail'){
					// 分享单个
					let {chart_permission_id} = item
					let first_permission_id = 0
					// 通过分享的沙盘图的二级分类Id，找到对应的一级Id
					U:for (let item of this.classfyList) {
						for (let it of item.list) {
							if(it.chart_permission_id == chart_permission_id){
								first_permission_id = item.id
								break U
							}
						}
					}
					code_scene=`{sandbox_id:${item.sandbox_id},chart_permission_id:${chart_permission_id},firstClassifyId:${first_permission_id}}`
					source = 'sandbox_detail'
					parsJson = {title_1:item.name,img_1:item.pic_url}
				}else{
					// 分享列表
					let {keyword,chart_permission_id,is_high_light} = this.sandTableQuery
					let firstImageUrl,secondImageUrl;
					if(!this.list || !this.list[0]){
						// 分享的列表页一条数据也没有 使用两个默认的沙盘图地址
						firstImageUrl = this.globalImgUrls.sandBoxShareDefault1
						secondImageUrl = this.globalImgUrls.sandBoxShareDefault2
					}else if(!this.list[1]){
						// 分享的列表页只有一条数据 第二个图片使用默认的沙盘图地址
						firstImageUrl = this.list[0].pic_url
						secondImageUrl = this.globalImgUrls.sandBoxShareDefault1
					}else{
						// 列表页有数据
						firstImageUrl = this.list[0].pic_url
						secondImageUrl = this.list[1].pic_url
					}
					code_scene=`{keyword:${keyword},chart_permission_id:${chart_permission_id},is_high_light:${is_high_light},firstClassifyId:${this.selectedFirstId}}}`
					source = 'sandbox_list'
					parsJson = {title_1:'沙盘推演',img_1:firstImageUrl,img_2:secondImageUrl}
				}
			    const res=await apiGetPoster({
			        code_page:'pages-sandTable/sandTable',
			        code_scene,
			        source,
			        pars:JSON.stringify(parsJson),
					version:'7.0'
			    })
			    if(res.code==200){
			        this.posterImg=res.data
			        this.show=false
			        this.showPoster=true
			    }else{
			        this.show=false 
			    }
			}
		}
	}
</script>

<style lang="scss" scoped>
	page{
		padding-bottom: 0;
		// 无权限
		.sandTable-noAuthor{
			display: flex;
			flex-direction: column;
			align-items: center;
			height: 100vh;
			image{
				margin-top: 180rpx;
			}
			text{
				font-family: 'PingFang SC';
				font-style: normal;
				font-weight: 400;
				font-size: 28rpx;
				color: #999999;
			}
			.sales-mobile{
				color: #E3B377;
			}
			button{
				background: #E6B77D;
				border-radius: 4px;
				width: 634rpx;
				height: 80rpx;
				margin-top: 108rpx;
				font-family: 'PingFang SC';
				font-style: normal;
				font-weight: 500;
				font-size: 32rpx;
				color: #FFFFFF;
			}
		}
		// 搜索区域
		.search-wrap{
			display: flex;
			background-color: white;
			padding: 20rpx 34rpx 20rpx 10rpx;
			height: 156rpx;
			align-items: center;
			.filtration-icon-zone{
				display: flex;
				align-items: center;
				image{
					width: 52rpx;
					height: 52rpx;
				}
				text{
					font-family: 'PingFang SC';
					font-style: normal;
					font-weight: 400;
					font-size: 32rpx;
					color: #E3B377;
				}
			}
		}
		// 列表区域 无数据
		.sandTable-noData{
			display: flex;
			flex-direction: column;
			align-items: center;
			height: calc(100vh - 158rpx);
			image{
				margin-top: 180rpx;
			}
			text{
				margin-top: 48rpx;
				font-family: 'PingFang SC';
				font-style: normal;
				font-weight: 400;
				font-size: 28rpx;
				color: #999999;
			}
		}
		// 列表区域
		.sandTable-box{
			padding: 24rpx 34rpx 40rpx 34rpx;
			background-color: white;
			margin-top: 10rpx;
			.sandTable-box-top{
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 32rpx;
				.sandTable-box-topL{
					display: flex;
					align-items: center;
					.sandTable-tag{
						margin-right: 20rpx;
						padding: 4rpx 22rpx;
						background: #333333;
						border-radius: 8rpx 8rpx 8rpx 8rpx;
						font-size: 24rpx;
						font-family: PingFang SC-Medium, PingFang SC;
						font-weight: 500;
						color: #E4B478;
						display: flex;
						align-items: center;
						justify-content: center;
					}
					.sandTable-name{
						font-size: 32rpx;
						font-family: PingFang SC-Medium, PingFang SC;
						font-weight: 500;
						color: #333333;
						max-width: 390rpx;
					}
				}
				.sandTable-box-topR{
					display: flex;
					align-items: center;
					image{
						width: 32rpx;
						height: 32rpx;
					}
				}
			}
			.sandTable-item{
				border: 2rpx solid #C4C4C4;
				image{
					width: 100%;
					height: 480rpx;
				}
				.sandTable-item-origin{
					text-align: right;
					padding:0 24rpx 20rpx 0 ;
					font-size: 20rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #666666;
				}
			}
		}
		.bottom_text{
			display: flex;
			justify-content: center;
			height: 60rpx;
			color: gray;
			font-size: 32rpx;
		}
		// 过滤弹窗
		.filter-container{
			height: 700rpx;
			width: 100vw;
			position: relative;
			.filter-container-header{
				padding: 54rpx 34rpx 20rpx 34rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				text{
					font-size: 32rpx;
					font-family: PingFang SC-Medium, PingFang SC;
					font-weight: 500;
					color: #000000;
				}
			}
			.list-box{
			    min-height: 30vh;
			    max-height: 60vh;
			    .list-item{
			        display: block;
			        margin: 10rpx;
			        height: 76rpx;
			        line-height: 76rpx;
			        color: #000;
			        background: #F6F6F6;
			        border-radius: 4px 4px 4px 4px;
			        text-align: center;
			    }
			    .list-item-active{
			        background-color: #FAEEDE;
			    }
			}
			button{
				position: absolute;
				bottom: 0;
				height: 80rpx;
				width: 100vw;
				border-radius: 0;
				background-color: #E6B77D;
				font-size: 32rpx;
				font-family: PingFang SC-Medium, PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
			}
		}
		// 分享海报
		.share-poster-wrap{
		    .poster-mask{
		        position: fixed;
		        left: 0;
		        top: 0;
		        right: 0;
		        bottom: 0;
		        background: rgba(0, 0, 0, 0.4);
		        z-index: 998;
		    }
		    .loading-box{
		        background-color: #fff;
		        position: fixed;
		        left: 50%;
		        top: 50%;
		        z-index: 999;
		        transform: translate(-50%,-50%);
		        width: 417rpx;
		        height: 261rpx;
		        text-align: center;
		        padding-top: 80rpx;
		        font-size: 32rpx;
		        font-weight: bold;
		        .load-img{
		            width: 91rpx;
		            height: 91rpx;
		            animation: circle 1s linear infinite;
		        }
		        @keyframes circle {
		            0%{
		                transform: rotateZ(0);
		            }
		            100%{
		                transform: rotateZ(360deg);
		            }
		        }
		    }
		    .poster-img{
		        width: 90vw;
		        display: block;
		        position: fixed;
		        left: 50%;
		        top: 50%;
		        z-index: 999;
		        transform: translate(-50%,-50%);
		        border-radius: 16rpx;
		    }
		}
		// 分享图标
		.share-icon{
			position: fixed;
			bottom: 100rpx;
			right: 34rpx;
			z-index: 50;
			width: 76rpx;
			height: 76rpx;
		}
	
	}

</style>
<style scoped>
 /deep/ .van-search__content{background-color:#F6F6F6;
border: 2px solid #E5E5E5;box-sizing: border-box;}
</style>
<style lang='scss'>
.filter-container{
    .list-box{
        .van-cell__title, .van-cell__value{
            flex: none !important;
        }
        .van-cell:after{
            border: none !important;
        }
        .van-cell__title{
            font-size: 14px;
        }
        .van-hairline--top:after{
            border-top-width: 0 !important;
        }
    }
}
</style>
