<template>
	<view class="confirm-subscribe flex-1">
		<view class="confirm-subscribe-item">
			<select-drug-user  v-if="address" :DrugInfo='address' :type="2" ></select-drug-user>
		</view>
		<view class="confirm-subscribe-item">
			<view class="flex align-start font-30 font-weight-bold ">
				<text class="text-red">*</text> <text class="text-black font-30">线下已确诊疾病</text>
			</view>
			<view class="font-24 text-grey">
				（*请根据线下就诊情况确认或选择确诊疾病）
			</view>
			
			<view class="flex align-center flex-wrap m-b-30">
				<view 
					v-for="(item, index) in diseaseList"
					@click="selectDisease(item, index)"
					:key="index"
					:class="{'confirm-subscribe-item-tag--active': new Set(selectList).has(item)}"
					class="confirm-subscribe-item-tag flex align-center justify-center font-24 m-r-16 m-t-26"
				>
					{{ item }}
				</view>
				<view class="confirm-subscribe-item-tag flex align-center justify-center font-24 m-t-26" @click="show = true">
					+添加疾病
				</view>
			</view>
			<view class="flex justify-between align-center m-t-20 m-b-30 font-30 font-weight-bold">
				<text>确认服用过该药且无禁忌症及不良反应</text>
				<u-switch v-model="checked"></u-switch>
			</view>
			<view class="flex flex-column justify-start ">
				<text class=" font-30 font-weight-bold m-t-20 m-b-20">处方/病历/检查报告（选填）</text>
				<text class=" font-28 m-b-10" style="color: #AFAFAF;">您上传的病例资料将为医生开具处方提供参考</text>
				<view class="hint_pic">
					<u-upload ref="uUpload3"
					:header="headerInfo" 
					:action="upload_img"
					:custom-btn="true" 
					image-mode="none"
					@on-remove="closeImg"
					@on-success="onSuccess"
					@on-error="onErrorInfo"
					max-count="1" width="281" height="192"  >
						<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
							<image :src="form.hintImage?form.hintImage:(IMG_URL+'upLoad.png')" mode=""></image>
						</view>
					</u-upload>
				</view>
			</view>
		</view>
		<view class="confirm-subscribe-footer position-fixed flex align-center justify-center">
			<u-button type="primary" shape="circle" @click="confirm">预约</u-button>
		</view>
		
		<u-popup v-model="show" mode="bottom" height="50vh">
				<view class="p-20">
					<u-search placeholder="请输入要添加的疾病" v-model="keyword" height="80" @search="offlinediagnosisList(1)" @custom="offlinediagnosisList(1)"></u-search>
				</view>
				<scroll-view scroll-y class="confirm-subscribe-scroll" @scrolltolower="illnessList()">
					<view class="text-center p-t-20 font-28 text-black" v-if="showList.length == 0">
						未搜索到该疾病
					</view>
					<view class="p-l-20 p-r-20">
						<view class="confirm-subscribe-scroll-item p-t-20 p-b-20" v-for="item in showList" :key="item.id" @click="handleDisease(item)">
							{{item.name}}
						</view>
					</view>
				</scroll-view>
			</u-popup>
	</view>
</template>

<script>
	import { IMG_URL } from '@/env.js';
	export default {
		data() {
			return {
				IMG_URL,
				show: false,
				diseaseList: [],
				selectList: [],
				current: '',
				keyword: '',
				goodsId: '',  //商品id
				address: null ,// 用药人
				drugUserInfo: null,
				type: '',
				pageNo:1,
				pageSize:10,
				total: null,
				isLock: true ,//锁
				isSituation: null,
				num: '',
				price: '',
				goodSkuParam: '',
				prescriptionId: null,
				addressId: null,
				orderType: null,
				preventionId: null,  //防疫id
				// 添加疾病
				showList: [],
				checked: false,
				// 图片
				upload_img: '',
				href: 'api/info/upload',
				headerInfo: {
					"content-type": "application/x-www-form-urlencoded",
					"X-Access-Token": ''
				},
				imgUpload: '' , // 上传的图片地址
				imgUploadShow: '',   // 拍方抓药 
				createOrderType: '',
				payType: '',
				isZone: '',
				patterId:''
			}
		},
		
		onLoad(options) {
			this.upload_img = this.$upload_img;
			console.log(4444444,options)
			this.payType = options.payType;
			this.createOrderType = options.createOrderType;
			this.goodsId = options.goodsId;
			this.addressId = options.addressId;
			this.type = options.type;
			this.isSituation = options.isSituation
			this.num = options.num;
			this.price = options.price;
			this.imgUploadShow = options.imgUploadShow;
			this.goodSkuParam = options.goodSkuParam;
			this.prescriptionId = options.prescriptionId;
			this.preventionId = options.preventionId;
			this.orderType = options.orderType;
			this.isZone = options.isZone;
			this.patterId = options.patterId == null?'':options.patterId;
			if(options.medicineMan) {
				this.address = JSON.parse(options.medicineMan);
			}
			console.log(5555,this.patterId)
			this.offlinediagnosisList();
			// 获取上传图片需要的信息
			let token = uni.getStorageSync("__user_token");
			this.headerInfo["X-Access-Token"] = token;
			this.getGoodsdetail(this.goodsId);
		},
		methods: {
			// 商品详情
			getGoodsdetail(id){
				uni.showLoading();
				this.$api('getGoodsdetail',{id})
				.then(res => {
					let { code, result, message } = res;
					uni.hideLoading();
					if(code == 200) {
						const list = result.disease?result.disease.split("，"): []
						console.log(list)
						list.forEach(item => {
							this.diseaseList.push(item)
						})
					}else {
						let tips = message.indexOf('操作失败') > -1 ? '商品不存在' : message
						this.$Toast(tips);
					}
				}).catch(err => {
					uni.hideLoading();
					this.$Toast(err.message)
				})
			},
			// 图片上传成功
			onSuccess(data){
				this.imgUpload = data.result
			},
			// 移除图片
			closeImg() {
				this.imgUpload = ''
			},
			// token 失效
			onErrorInfo(data) {
				console.log(data)
				if(data.code == 401){
					this.$tools.navigateTo({
						url: '/pages/login/login'
					})
				}
			},
			// 下拉刷新
			illnessList() {
				if(this.isLock) {
					if(this.total !== null && this.pageNo * this.pageSize >= this.total){
						this.isLock = false;
						this.$Toast('没有更多数据了哦！');
						setTimeout(()=>{
							this.isLock = true;
						},3000)
						return
					}
					this.pageNo+=1;
					this.getRightListGoods();
				}
			},
			// 根据商品id获取地址
			
			selectUser () {
				this.$tools.navigateTo({
					url: `/pagesA/my_other_list/prescription/select_medicine_man/index?type=${this.type}&goodsId=${this.goodsId}`
				});
			},
			// 线下确诊疾病  -> 点击添加的疾病
			offlinediagnosisList(index=0) {
				// index 0 为普通列表 1为搜素
				const params = {
					pageNo: this.pageNo,
					pageSize: this.pageSize,
				}
				if(index == 1){
					params.name = this.keyword
					delete params.pageNo
				}
				uni.showLoading();
				this.$api('offlinediagnosisList',params).then(res => {
					let { code, result, message} = res;
					if(code == 200) {
						if(this.total == null) {
							this.total = result.total
						}
						if(index == 1){
							this.showList = result.records
						}else{
							this.showList = this.showList.concat(result.records)
						}
						uni.hideLoading()
					}else {
						uni.hideLoading()
						this$Toast(message)
					}
				}).catch(err => {
					uni.hideLoading()
					this$Toast(err.message)
				}) 
			},
			
			// 预约
			confirm () {
				console.log(this.address)
				console.log(this.createOrderType)
				const params = {
					userId:  this.address.id,//用药人标识
					goodId: this.goodsId,
					confirmatoryDiseaseLabel: this.selectList.toString(), //		确证疾病标签
					isAdverse: this.checked?1:0,  //1有不良反应
					casePic: this.imgUpload,  //病例图片
					paterId: this.patterId
					// caseText: ,  // 病例信息
				}
				if(params.confirmatoryDiseaseLabel == '') {
					this.$Toast('请选择疾病标签');
					return
				}
				const that = this
				this.$api('offlineAdd',params).then(res => {
					let { code, result, message} = res;
					if(code == 200) {
						//  兑购2 拼团1
						if(this.createOrderType === 'shoppingCart'){
							this.addCart(result)
						}else if(this.createOrderType === 'confirm') {
							this.setOrder(result.id)
						}else {
							that.addCart(result);
						}
					}else {
						this.$Toast(message)
					}
				}).catch(err => {
					this.$Toast(err.message)
				}) 
				
			},
			// 创建订单
			setOrder(id){
				const params = {type: this.payType,prescriptionId: this.address.id , offlineInfoId: id, id: this.goodsId, goodsPrice: this.price, goodsNum: this.num,  goodsSku: this.goodSkuParam, orderType:  this.orderType,paterId: this.patterId}
				if(this.preventionId){
					params.preventionId = this.preventionId
				}
				this.$api('teamCreateOrder', params)
				.then(res => {
					uni.hideLoading()
					let { code, message, result } = res
					if (code === 200) {
						this.$tools.navigateTo({
							url: `/pagesC/confirmOrder/confirmOrder?ids=${result.order.id}&orderType=${this.orderType}&payType=${this.payType}&isZone=${this.isZone}` 
						})
					}else if(res.code === 902) {
						// 防疫药
						uni.showModal({
							title: res.message,
							success: (res) => {
								console.log(res)
								if(res.confirm) {
									uni.navigateTo({
										url: `/pagesB/epidemicPrevention/index?goodsId=${this.goodsId}&orderType=${this.orderType}&num=${this.num}&price=${this.price}&goodSkuParam=${this.goodSkuParam}&prescriptionId=${this.address.id}&medicineMan=${JSON.stringify(this.address)}&createOrderType=${this.createOrderType}&payType=${this.payType}&offlineInfoId=${id}`
									})
								}
							}
						})
					}else {
						this.$Toast(message)
					}
				})
				},
			// 加入购物车
			addCart(result) {
				console.log(this.address)
				// type: 2, 
					const params = {offlineInfoId: result.id ,id: this.goodsId, num: this.num, price: this.price, goodSkuParam: this.goodSkuParam, prescriptionId: this.address.id,paterId: this.patterId }
					if(this.preventionId) {
						params.preventionId = this.preventionId
					}
					this.$api('addShoppingCart', params)
					.then(res => {
						if (res.code === 200) {
							uni.$emit('isUpdataShowToast')
							this.$Toast(res.message)
							let pages_url = getCurrentPages();
							const index = pages_url.findIndex(item => {
								return item.route == 'pagesC/goodsInfo/goodsInfo'
							});
							const length = pages_url.length 
							// 需要返回的层数
							const backIndex = length - (index+1);
							uni.navigateBack({
								delta: backIndex
							})
							// setTimeout(() => {
							// 	this.$tools.switchTab({
							// 		url: '/pages/shoppingCart/shoppingCart'
							// 	}, 800)
							// })
						}else if(res.code === 902) {
							// 防疫药
							uni.showModal({
								title: res.message,
								success: (res) => {
									console.log(res)
									if(res.confirm) {
										uni.navigateTo({
											url: `/pagesB/epidemicPrevention/index?goodsId=${this.goodsId}&num=${this.num}&price=${this.price}&goodSkuParam=${this.goodSkuParam}&prescriptionId=${this.address.id}&medicineMan=${JSON.stringify(this.address)}&offlineInfoId=${result.id}`
										})
									}
								}
							})
						}else {
							this.$Toast(message)
						}
					}).catch(err => {
						this.$Toast(err.message)
					})
			},
			selectDisease (item, index) {
				if(new Set(this.selectList).has(item)) {
					const index_ = this.selectList.indexOf(item);
					this.selectList.splice(index_,1);
				}else {
					this.selectList.push(item)
				}
			},
			handleDisease (item) {
				this.diseaseList.unshift(item.name)
				this.diseaseList = [...new Set(this.diseaseList)]
				this.show = false
			},
		
		}
	}
</script>

<style lang="scss" scoped>
	.hint_pic{
		display: flex;
		flex-direction: column;
		margin-right: 40rpx;
		/deep/.u-list-item {
			margin: 0;
			width: 232rpx !important;
			height: 232rpx !important;
			border-radius: 12rpx;
			.u-preview-image{
				width: 264rpx;
				height: 232rpx;
			}
			image {
				width: 232rpx;
				height: 232rpx;
			}
		}
		image {
			width: 232rpx;
			height: 232rpx;
			border-radius: 12rpx;
		}
	}
	.confirm-subscribe {
		padding: 20rpx 20rpx 140rpx;
		&-item {
			padding: 20rpx;
			background: #ffffff;
			border-radius: 18rpx;
			box-shadow: 0px 4rpx 6rpx 0px rgba(0,0,0,0.16); 
			margin-bottom: 40rpx;
			
			&-tag {
				padding: 0 20rpx;
				height: 50rpx;
				background: #E2E2E2;
				color: #1d1d1d;
				border-radius: 24rpx;
				&--active {
					background: #baebfc;
					color: #01aeea;
				}
			}
		}
		
		&-footer {
			z-index: 1;
			height: 120rpx;
			bottom: 0;
			left: 0;
			width: 100%;
			background: #fff;
			/deep/.u-btn {
				width: 660rpx;
				height: 80rpx;
			}
		}
		
		&-scroll {
			height: calc(50vh - 120rpx );
			&-item {
				border-bottom: 2rpx solid #D2D2D2;
			}
		}
	}
</style>