<template>
	<view>
		<!--prescription/dialogue/index.wxml-->
		<view>

			<scroll-view scroll-y :scroll-into-view="toView" :style="hind?'':'height:'+ scrollHeight">
				<!-- <view class='scrollMsg'> -->
				<view class="top  bgfff pdlr20 dflex">
					<view class="topcon">
						<image :src="doctor.img?doctor.img:'/prescription/static/prescription/image/ys.png'"
							mode="aspectFit" class="logo r50 bgfff mr20"></image>
						<view class="area flex" @tap="merchant">
							<view class="areas f28 dflex">
								<view class="doctor">{{doctor.name}}</view>
								<view class="subject">{{doctor.depart}}</view>
								<view>{{doctor.title}}</view>
							</view>
							<view v-if="doctor.goodAt">擅长：{{doctor.goodAt}}</view>
						</view>
					</view>
				</view>
				<view class="tips">
					<view class="txt">根据国家相关规定，互联网医疗只能为患者提供处方服务，若您不是复诊患者，我们只能提供咨询服务。在线咨询不能代替面诊，继续咨询表示您已知晓并同意该条款。</view>
					<view class="dflex authorization">《互联网医疗风险告知及知情同意书》<view class="underline" @tap="goUrl">点击查看</view>
					</view>
				</view>
				<block v-for="(item, index) in msgList" :key="index">

					<!-- 单个消息1 客服发出（左） -->
					<view v-if="item.isMember=='0'" :id="'msg-' + index"
						style="display: flex; padding: 2vw 11vw 2vw 2vw;">
						<view style="width: 11vw; height: 11vw;">
							<image class="logo r50 bgfff"
								:src="doctor.img?doctor.img:'/prescription/static/prescription/image/ys.png'"></image>
						</view>
						<!-- <view  class="test-step">
          <image style='width: 4vw;' src='../../images/left_msg.png' mode='widthFix'></image>
        </view> -->
						<view class="leftMsg">{{item.msg}}</view>
					</view>

					<!-- 单个消息2 用户发出（右） -->
					<view v-else :id="'msg-' + index"
						style="display: flex; justify-content: flex-end; padding: 2vw 2vw 2vw 11vw;">
						<view class="rightMsg">{{item.msg}}</view>
						<!-- <view style='width: 4vw; height: 11vw; margin-right: 0.5vw; display: flex; align-items: center; z-index: 9;'>
          <image style='width: 4vw;' src='../../images/right_msg.png' mode='widthFix'></image>
        </view> -->
						<view style="width: 11vw; height: 11vw;">
							<image class="logo r50 bgfff" :src="cusHeadIcon"></image>
						</view>
					</view>

				</block>
				<!-- </view> -->

				<!-- 占位 -->
				<view style="width: 100%; height: 18vw;"></view>
			</scroll-view>

			<view class="inputRoom" :style="'bottom: ' + inputBottom">
				<!-- <image style='width: 7vw; margin-left: 3.2vw;' src='../../images/pic_icon.png' mode='widthFix'></image> -->
				<!-- <input class="ipt" bindconfirm='sendClick' adjust-position='{{false}}' value='{{inputVal}}' confirm-type='send' bindfocus='focus' bindblur='blur'></input> -->
				<block v-if="msgList.length<8">
					<view class="no" @tap="disable?'':negative()" :style="allergy?'background:#FE0419':''">否</view>
					<view class="confirm" @tap="disable?'':suer()" :style="allergy?'background:#BDC2C9':''">是，我确定</view>
				</block>
				<block v-else>
					<view class="confirm" @tap="disable?'':suer()" :style="allergy?'background:#BDC2C9':''">
						{{msgList.length>=10?"有":"是"}}
					</view>
					<view class="no" @tap="disable?'':negative()" :style="allergy?'background:#FE0419':''">
						{{msgList.length>=10?"没有":"否"}}
					</view>
				</block>
			</view>
		</view>

		<view class="mask" :hidden="isHide"></view>
		<view class="suc" :hidden="isHide">
			<view class="title">输入过敏药品</view>
			<input placeholder="请输入过敏源" @input="abnormal" data-index="1" :value="inputVal" adjust-position="false"
				@focus="focus" @blur="blur"></input>
			<view class="btn dflex">
				<view class="cancel" @tap="hidePop">取消</view>
				<view class="queren" @tap="abnormalClick" data-index="1">确认</view>
			</view>
		</view>


		<view class="mask" :hidden="isShow"></view>
		<view class="suc" :hidden="isShow">
			<view class="title">身体异常项</view>
			<input placeholder="请输入身体异常项" @input="abnormal" data-index="2" :value="inputVal" adjust-position="false"
				@focus="focus" @blur="blur"></input>
			<view class="btn dflex">
				<view class="cancel" @tap="hideShow">取消</view>
				<view class="queren" @tap="abnormalClick" data-index="2">确认</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	var windowWidth = uni.getSystemInfoSync().windowWidth;
	var windowHeight = uni.getSystemInfoSync().windowHeight;
	var keyHeight = 0;
	var inputVal = '';
	var msgList = [];
	const req = require("../../utils/request.js");
	const util = require("../../utils/util.js");
	/**
	 * 初始化数据
	 */
	/**
	 * 初始化数据
	 */
	function initData(that) {
		inputVal = '';
		msgList = [{
			isMember: "1",
			msg: that.doctor.name + '医生，您好。我是：' + that.drugUsers.name + '，' + that.drugUsers.sex + '，' + that
				.drugUsers.age + '岁， 我的病情是：' + that.jibing + ' ，病情已确定，本次问诊为复诊',
			type: "TIMTextElem",
			flow: "out"
		}, {
			isMember: "1",
			msg: "目前发病情况：未知；既往病史：未知；用药史：未知；药物过敏情况：无；用药禁忌情况：未知。",
			type: "TIMTextElem",
			flow: "out"
		}, {
			isMember: "1",
			msg: '我需要以下：' + JSON.parse(that.query.txtdrugs).length + '种药品：(' + that.drugs + ')',
			type: "TIMTextElem",
			flow: "out"
		}, {
			isMember: '0',
			msg: '您描述的患有' + that.jibing + '是否在线下医院确诊过？',
			type: "TIMTextElem",
			flow: "in",
			nextShow: true
		}];
		that.setData({
			msgList,
			inputVal
		});
	}
	/**
	 * 计算msg总高度
	 */
	// function calScrollHeight(that, keyHeight) {
	//  var query = wx.createSelectorQuery();
	//  query.select('.scrollMsg').boundingClientRect(function(rect) {
	//  }).exec();
	// }

	export default {
		data() {
			return {
				scrollHeight: '100vh',
				inputBottom: 0,
				isHide: true,
				isShow: true,
				allergen: "",
				msgList: "",
				inputVal: "",
				jibing: "",
				drugs: "",
				drugsName: "",
				doctor: "",
				cusHeadIcon: "",
				drugUsers: "",
				allergy: false,
				hind: false,
				toView: "",
				disable: false,
				malaise: ""
			};
		},

		components: {},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.query = options; // JSON.parse(options.diagnosis)
			// console.log(options)
			if (options.diagnosis) {
				let arr = [];
				JSON.parse(options.diagnosis).map(it => {
					arr.push(it.name);
				});
				this.setData({
					jibing: arr.toString()
				});
			}

			if (options.txtdrugs) {
				let drugs = [];
				let drugsName = [];
				JSON.parse(options.txtdrugs).map(it => {
					// console.log(it);
					let txt = it.drugName + it.number + it.unit + it.spec;
					let name = it.drugName;
					drugs.push(txt);
					drugsName.push(name);
				});
				this.setData({
					drugs: drugs.toString(),
					drugsName: drugsName.toString()
				});
			}

			if (options.doctor) {
				// console.log(options.doctor);
				this.setData({
					doctor: JSON.parse(options.doctor)
				});
			}

			// console.log(options);
			this.init();
			this.setData({
				cusHeadIcon: req.getStorage('userInfo').avatar
			});
		},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			uni.enableAlertBeforeUnload({
				message: '确认返回？',
				success: function(res) {
					// console.log(res);
				},
				fail: console.error
			});
		},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},

		onUnload() {
			if (this.out) return false;
			let chats = this.msgList;
			let diagnosis = JSON.parse(this.query.diagnosis);
			let txtdrugs = JSON.parse(this.query.txtdrugs);
			let from = {
				peopleId: this.drugUsers.id,
				allergy: this.allergen,
				orderId: this.query.orderId,
				//订单id
				doctorId: this.doctor.id ? this.doctor.id : '',
				chats: chats,
				diagnosis: diagnosis,
				//症状
				txtdrugs: txtdrugs,
				//产品规格
				state: 3
			};
			// console.log(from, typeof from.chats, typeof from.diagnosis, typeof from.txtdrugs, JSON.stringify(from));
			req.postRequest('/api/userDrugPeople/simple', {
				from: JSON.stringify(from)
			}, res => {});
		},

		methods: {
			async init() {
				await this.getdrugUsers(this.query.uId); // await this.getDoctor()
			},

			// 获取用药人详情
			getdrugUsers(id) {
				req.getRequest('/api/userDrugPeople/get', {
					id: id
				}, data => {
					if (data) {
						data.sex = data.sex == 1 ? '男' : '女';
						// console.log(this.data);
						this.setData({
							drugUsers: data
						});
						initData(this);
					}
				});
			},

			// 获取病症和医生
			// getDoctor() {
			//   req.postRequest('/api/userDrugPeople/getHntyAndDoctor', {}, data => {
			//     console.log(data);
			//     if (data) {
			//       // console.log(JSON.parse(data.hnty.data));
			//       if (!data.doctor || data.doctor.code != 0) {
			//         wx.showModal({
			//           content: '当前医师不在线，请稍后再试',
			//           showCancel: false,
			//           success(res) {
			//             if (res.confirm) {
			//               console.log('用户点击确定')
			//               // that.setData({ cancel: true })
			//             }
			//           }
			//         })
			//       } else {
			//         initData(this, JSON.parse(data.doctor.data));
			//         // initData(this);
			//         this.setData({ doctor: JSON.parse(data.doctor.data) })
			//       }
			//     }
			//   })
			// },
			// 页面跳转
			goUrl() {
				app.globalData.openPage('prescription/riskNotification/index');
			},

			suer: util.throttle(function() {
				// console.log(this.disable);
				if (this.disable) return false;
				let arr = [];
				msgList.map(it => {
					if (it.isMember == "0") arr.push(it);
				});
				let that = this;

				if (arr.length <= 2) {
					msgList.push({
						isMember: '1',
						msg: '是，我确定',
						nextShow: true,
						type: "TIMTextElem",
						flow: "out"
					});
				}

				setTimeout(function() {
					//要延时执行的代码
					if (arr.length == 1) {
						msgList.push({
							isMember: '0',
							msg: '您确定使用过' + that.drugsName + '，使用后并无不适症状？',
							nextShow: true,
							type: "TIMTextElem",
							flow: "in"
						});
					}

					if (arr.length == 2) {
						msgList.push({
							isMember: '0',
							msg: '您是否有药物过敏？',
							nextShow: true,
							type: "TIMTextElem",
							flow: "in"
						});
						that.setData({
							allergy: true
						});
					}

					if (arr.length == 3) {
						that.setData({
							isHide: false,
							hind: true
						});
					}

					if (arr.length == 4) {
						that.setData({
							isShow: false,
							hind: true
						});
					}

					inputVal = '';
					that.setData({
						msgList,
						inputVal,
						toView: 'msg-' + (that.msgList.length - 1)
					});
					// console.log(that.msgList);

					if (that.msgList.length == 11) {
						that.save();
					}
				}, 500); //延迟时间 这里是1秒
			}, 1000),
			negative: util.throttle(function() {
				if (this.disable) {
					return false;
				}

				let that = this;
				let arr = [];
				msgList.map(it => {
					if (it.isMember == "0") arr.push(it);
				});
				// console.log(arr);

				if (arr.length == 3) {
					msgList.push({
						isMember: '1',
						msg: '无',
						nextShow: true,
						type: "TIMTextElem",
						flow: "out"
					});
				}

				if (arr.length == 4) {
					msgList.push({
						isMember: '1',
						msg: '没有',
						nextShow: true,
						type: "TIMTextElem",
						flow: "out"
					});
				}

				setTimeout(function() {
					//要延时执行的代码
					if (arr.length == 1) {
						uni.showModal({
							title: "提示",
							content: '根据互联网医院相关规定，在线问诊仅适合复诊患者，如您是初诊请到就近医院就医。',

							// showCancel: false,
							success(res) {
								if (res.confirm) {
									// console.log('用户点击确定'); // that.setData({ cancel: true })
								}
							}

						});
					}

					if (arr.length == 2) {
						uni.showModal({
							title: "提示",
							content: '根据互联网医院相关规定，若您需要的药品未服用过，医生不能为您进行在线问诊开具处方。',

							// showCancel: false,
							success(res) {
								if (res.confirm) {
									// console.log('用户点击确定'); // that.setData({ cancel: true })
								}
							}

						});
					}

					if (arr.length == 3) {
						msgList.push({
							isMember: '0',
							msg: '请问有无肝、肾功能异常？',
							nextShow: true,
							type: "TIMTextElem",
							flow: "in"
						});
					}

					if (arr.length == 4) {
						that.setData({
							disable: true
						});
					}

					inputVal = '';
					that.setData({
						msgList,
						inputVal,
						toView: 'msg-' + (that.msgList.length - 1)
					});
				}, 500); //延迟时间 这里是1秒

				inputVal = ''; // console.log(msgList)

				this.setData({
					msgList,
					inputVal,
					toView: 'msg-' + (that.msgList.length - 1)
				});

				if (that.msgList.length == 11) {
					that.save();
				}
			}, 1000),

			hidePop() {
				this.setData({
					isHide: true
				});
			},

			hideShow() {
				this.setData({
					isShow: true
				});
			},

			// 2身体异常 1过敏源
			abnormal(e) {
				let content = e.detail.value;
				let index = e.target.dataset.index; // if()

				// console.log(e.target.dataset.index);

				if (index == 1) {
					this.setData({
						allergen: content,
						toView: 'msg-' + (this.msgList.length - 1)
					});
				}

				if (index == 2) {
					this.setData({
						malaise: content,
						toView: 'msg-' + (this.msgList.length - 1)
					});
				}
			},

			//  2身体异常 1过敏源
			abnormalClick(e) {
				let index = e.target.dataset.index;

				if (index == 1) {
					if (!this.allergen) {
						this.setData({
							isHide: true,
							hind: false
						});
						return false;
					}

					msgList.push({
						isMember: '1',
						msg: this.allergen,
						nextShow: true,
						type: "TIMTextElem",
						flow: "out"
					});
					msgList.push({
						isMember: '0',
						msg: '请问有无肝、肾功能异常？',
						nextShow: true,
						type: "TIMTextElem",
						flow: "in"
					});
				}

				if (index == 2) {
					if (!this.malaise) {
						this.setData({
							isShow: true,
							hind: false
						});
						return false;
					}

					msgList.push({
						isMember: '1',
						msg: this.malaise,
						nextShow: true,
						type: "TIMTextElem",
						flow: "out"
					});
					this.setData({
						disable: true
					});
				}

				// console.log(msgList);
				inputVal = '';
				this.setData({
					msgList,
					inputVal,
					isShow: true,
					isHide: true,
					hind: false,
					toView: 'msg-' + (msgList.length - 1)
				});

				if (this.msgList.length == 11) {
					this.save();
				}
			},

			//   /**
			//  * 获取聚焦
			//  */
			focus: function(e) {
				// keyHeight = e.detail.height;
				// this.setData({
				//   scrollHeight: (windowHeight - keyHeight) + 'px'
				// });
				// this.setData({
				//   toView: 'msg-' + (msgList.length - 1),
				//   inputBottom: keyHeight + 'px'
				// })
				this.setData({
					hind: true,
					inputBottom: 0
				}); //计算msg高度
				// calScrollHeight(this, keyHeight);
			},
			//失去聚焦(软键盘消失)
			blur: function(e) {
				// this.setData({
				//   hind: false,
				//   scrollHeight: '100vh',
				//   inputBottom: 0,
				//   // toView: 'msg-' + (msgList.length - 1)
				// })
				this.setData({
					toView: 'msg-' + (this.msgList.length - 1)
				});
			},

			/**
			 * 退回上一页
			 */
			toBackClick: function() {
				uni.navigateBack({});
			},

			save() {
				let chats = this.msgList;
				let diagnosis = JSON.parse(this.query.diagnosis);
				let txtdrugs = JSON.parse(this.query.txtdrugs);
				let from = {
					peopleId: this.drugUsers.id,
					allergy: this.allergen,
					orderId: this.query.orderId,
					//订单id
					doctorId: this.doctor.id,
					chats: chats,
					diagnosis: diagnosis,
					//症状
					txtdrugs: txtdrugs,
					//产品规格
					state: 4
				};
				this.out = true;
				// console.log(from, typeof from.chats, typeof from.diagnosis, typeof from.txtdrugs, JSON.stringify(from));
				req.postRequest('/api/userDrugPeople/simple', {
					from: JSON.stringify(from)
				}, res => {
					let identifier;

					if (res.healthInfo) {
						identifier = JSON.parse(res.healthInfo);
						// console.log(identifier);
					}

					uni.reLaunch({
						url: "/prescription/inquiry/index?comunicationid=" + res.comunicationid +
							'&sdkAppID=' + res.sdkAppID + '&userSig=' + res.userSig + '&identifier=' +
							identifier.uuid + '&doctor=' + JSON.stringify(this.doctor) + '&orderId=' + this
							.query.orderId + '&msg=' + JSON.stringify(this.msgList)
					});
					
				});
			}

		}
	};
</script>
<style>
	@import "./index.css";
</style>
