<template>
	<view>
		<!--prescription/Consultation/index.wxml-->
		<view class="tips dflex">
			<icon class="icon-box-img" type="warn" size="18"></icon>信息将作为医生诊断和开具处方的重要依据，请如实填写
		</view>
		<view class="drugUsers bgfff r20">
			<view class="dflex medication" @tap="goUrl" :data-url="drugUsers?'prescription/drugUsersList/index?choice=true':'prescription/drugUsers/index?add=1'">用药人
				<image src="/static/pages/images/more.png" class="more" v-if="drugUsers"></image>
			</view>
			<view class="dflex li" v-if="drugUsers">
				<view class="info flex dflex" :data-index="index">
					<view class="name">{{drugUsers.name}}<text>{{drugUsers.tel}}</text></view>
					<!-- <view class="addr"><text wx:if="{{item.isDefault == 1}}">默认</text>{{item.address}}{{item.house}}</view> -->
					<!-- <view class="authentication">已认证</view> -->
					<view class="relationship" v-if="drugUsers.label">{{drugUsers.label}}</view>
				</view>
			</view>
			<view class="add" @tap="goUrl" data-url="prescription/drugUsers/index?add=1" v-else>
				<image src="/static/pages/images/jia.png" class="jia"></image>新建用药人
			</view>
		</view>

		<view class="drugUsers bgfff r20">
			<view class="dflex medication">药品信息 <view class="dflex yao" @tap="updown">已选择{{sum?sum:'0'}}种药<image :src="pageShow?'/prescription/static/prescription/image/integral_up.png':'/prescription/static/prescription/image/integral_down.png'"
					 class="updown"></image>
				</view>
			</view>
			<view class="list mt20" v-if="pageShow">
				<view v-for="(item, index) in pageList" :key="index" class="li">
					<view class="cimgs ">
						<image :src="item.imgUrl" mode="aspectFit" class="cimg"></image>
					</view>
					<view class="zhinfo">
						<view class="zhtit">{{item.drugName}}</view>
						<view v-if="item.spec" class="guigecontent">规格：
							<text class="guige" decode="true">{{item.spec}}&nbsp;
							</text>
						</view>
						<view class="jiage">
							<view class="zhjia"></view>
							<view class="num">
								<!-- <view class="jian" bindtap="jianQuantity" data-index="{{index}}">-</view> -->
								<text class="nums">×{{item.number>=0?item.number:'0'}}{{item.unit?item.unit:''}}</text>
								<!-- <view class="jian" bindtap="jiaQuantity" data-index="{{index}}">+</view> -->
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="disease bgfff r20">
			<view>信息用于诊断开方请确保准确</view>
			<view class="diagnosis"><text>*</text>请选择线下已确诊疾病(最多可选2项)</view>
			<view class="dflex liste" v-if="TabList.length>0">
				<view v-for="(item, index) in TabList" :key="index" :class="'item ' + (item.active?'active':'')" @tap="switchTab"
				 :data-index="index" :data-id="item.id" :data-name="item.name">{{item.name}}</view>
				<view class="custom" @tap="diagnosisShow">+手动输入</view>
			</view>
			<view class="new"><text></text>请确认以下信息</view>
			<!-- <view class="mb20">
    <view>1.您是否服用过该药品且无相关禁忌症？</view>
    <radio-group bindchange="radioChange" data-problem="1">
      <radio wx:for="{{items}}" wx:key="index" value="{{item.value}}" color="#F32B09">{{item.value}}</radio>
    </radio-group>
  </view> -->
			<!-- <view class="mb20">
    <view>2.您是否对药物过敏？</view>
    <radio-group bindchange="radioChange" data-problem="2">
      <radio wx:for="{{items}}" wx:key="index" value="{{item.value}}" color="#F32B09">{{item.value}}</radio>
    </radio-group>
  </view> -->
			<!-- <view class="mb20">
    <view>3.有无不良反应？</view>
    <radio-group bindchange="radioChange" data-problem="3">
      <radio wx:for="{{items}}" wx:key="index" value="{{item.value}}" color="#F32B09">{{item.value}}</radio>
    </radio-group>
  </view> -->
			<view class="mb20">
				<view class="mb20">1.是否复诊</view>
				<radio-group @change="radioChange" data-problem="4">
					<radio v-for="(item, index) in items" :key="index" :value="item.value" color="#F32B09" :checked="item.checked">{{item.value}}</radio>
				</radio-group>
			</view>
			<view class="mb20">
				<view>2.是否上传复诊凭证（可不传）</view>
				<!-- <radio-group bindchange="radioChange" data-problem="5">
      <radio wx:for="{{items}}" wx:key="index" value="{{item.value}}" color="#F32B09">{{item.value}}</radio>
    </radio-group> -->
			</view>
			<!-- <view class="voucher" wx:if="{{voucher}}">
    您已确认在线下医院完成过就诊，但此刻复诊凭证丢失或不在身边，无历史处方记录可能影响医生对您病情的判断
  </view> -->
			<view class="dflex uploadVoucher">
				<block v-if="avatar.length<=0">
					<image src="/static/pages/images/upload.png" class="upload" @tap="uploadAvatar"></image>
					<view @tap="uploadAvatar">
						添加已就诊的病例/住院出院记录
						<view class="photo">照片仅自己和医生可见</view>
					</view>
				</block>
				<view class="dflex" v-else>
					<view v-for="(item, index) in avatar" :key="index" class="pz">
						<image :src="avatar[index]" class="scpz"></image>
						<image src="/prescription/static/prescription/image/imagecuo.png" class="cuo" @tap="cleanimage" :data-index="index"></image>
					</view>
					<image src="/static/pages/images/upload.png" class="scpz" @tap="uploadAvatar" v-if="avatar.length<3"></image>
				</view>
			</view>
		</view>
		<view class="placeholder-view" :style="'height:' + (bottomBlankHeight + 120) + 'rpx'"></view>
		<view class="bot fixed bgfff " :style="'padding: ' + (bottomBlankHeight + 20) + 'rpx 0rpx'">
			<!-- <view class="addcart">我有处方</view> -->
			<view class="sub">提交即代表同意<text @tap="goUrl" data-url="prescription/consultationAgreement/index">《患者问诊服务协议》</text>和<text
				 @tap="goUrl" data-url="prescription/privacyPolicy/index">《隐私政策》</text></view>
			<view class="mbglinear gmbtn" @tap="save"><text>提</text>交</view>
		</view>

		<view class="mask" :hidden="isHide"></view>
		<view class="suc" :hidden="isHide">
			<view class="title">请输入您的病症</view>
			<input placeholder="请输入" @input='abnormal' :value="value" auto-focus />
			<view class="btn dflex">
				<view class="cancel" @tap="hidePop">取消</view>
				<view class="queren" @tap="abnormalClick">确认</view>
			</view>
		</view>
	</view>
</template>

<script>
	// prescription/Consultation/index.js
	const app = getApp();
	const req = require("../../utils/request.js");
	const util = require("../../utils/util.js");

	export default {
		data() {
			return {
				TabList: [],
				items: [{
					value: '是',
					name: '是',
					checked: 'true'
				}, {
					value: '否',
					name: '否'
				}],
				bottomBlankHeight: app.globalData.isIPhoneX ? 68 : 0,
				avatar: [],
				pageList: [],
				list: [],
				pageShow: false,
				restoration: true,
				drugUsers: "",
				cancel: false,
				uploadVoucher: false,
				voucher: false,
				doctor: "",
				sum: "",
				isHide: true,
				labe:[],
				choice: false
			};
		},

		components: {},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.query = options;
			console.log(options)
			this.getDoctor().then(res=>{
				this.getDrug();
			})
		},

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

		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			let that = this;
			let diagnosis;

			if (this.TabList) {
				diagnosis = this.TabList.filter(it => it.active);
			}

			let form = {
				peopleId: this.drugUsers.id,
				orderId: this.query.orderId,
				diagnosis: JSON.stringify(diagnosis),
				isVisit: this.restoration ? 1 : 0,
				voucherImage: this.avatar,
				state: 1
			};
			req.postRequest('/api/userDrugPeople/updateODU', form, data => {});
		},

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

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},
		methods: {
			goUrl(e) {
				console.log(e)
				let url = e.currentTarget.dataset.url;
				
				app.globalData.openPage(url);
			},

			getList() {
				let that = this;
				if (this.choice) return false;
				req.getRequest('/api/userDrugPeople/list', {
					page: 1,
					limit: 1000
				}, data => {
					// console.log(data);

					if (data && data.length > 0) {
						this.setData({
							drugUsers: data[0]
						});
					} else {
						this.setData({
							drugUsers: ''
						});
					}
				});
			},
			// 手动输入病症
			diagnosisShow() {
				this.setData({
					isHide: false
				})
			},
			hidePop() {
				this.setData({
					isHide: true,
					value: "",
					inputValue: ""
				})
			},
			// 获取用户输入的病症
			abnormal(e) {
				let content = e.detail.value
				// console.log(!content, content);
				if (!content) {
					this.setData({
						value: ""
					})
				} else {
					this.setData({
						value: content
					})
				}
			},

			// 用户确认病症
			abnormalClick() {
				if (!this.value) {
					return req.msg("请输入病症")
				}
				// this.data.TabList.filter(it => {
				//   it.name == this.data.value
				// })
				let repeat = this.TabList.filter(it => {
					return it.name == this.value
				})
				if (repeat.length > 0) {
					return req.msg("该病症已存在，请选择")
				}
				// console.log(this.data.TabList.filter(it => {return it.name == this.data.value}));
				let diagnosis = [{
					name: this.value,
					id: ""
				}]
				if (this.allergen) {
					let lest = this.allergen.concat(diagnosis)
					// console.log(lest, this.allergen);
					this.setData({
						allergen: lest
					})
				} else {
					this.setData({
						allergen: diagnosis
					})
				}
				// console.log(this.allergen);
				if (req.getStorage('diagnosis')) {
					let diagnosis = req.getStorage('diagnosis')
					diagnosis.push({
						name: this.value,
						id: ""
					})
					req.setStorage('diagnosis', diagnosis)
				} else {
					req.setStorage('diagnosis', this.allergen)
				}
				// this.data.TabList.push(diagnosis)
				let i = 0
				let content = this.allergen.map(it => {
					if (it.active) {
						i++
					}
					if (i < 2) {
						it.active = true
					}
					// console.log(it);
					return it
				})
				// console.log(content, this.hnty);
				let about=JSON.parse(req.getStorage('configRes'))
				if(!about.prescription_disease||(about.prescription_disease&&about.prescription_disease!=2)){
					let list = this.hnty.concat(content)
					// console.log(list);
					this.setData({
						TabList: list,
					})
				}else{
					let list = this.labe.concat(content)
					// console.log(list);
					this.setData({
						TabList: list,
					})
				}
				this.setData({
					isHide: true,
					inputValue: "",
					value: ""
				})
			},
			switchTab(event) {
				let index = event.currentTarget.dataset.index;
				let def = this.TabList[index].active;
				let d = {};
				let arr = [];
				// console.log(def, index);
				this.TabList.map(it => {
					if (it.active) {
						arr.push(it);
					}
				});
				// console.log(arr, arr.length);
				if (arr.length == 2 && !def) return req.msg('选择不能超过两个');
				d['TabList[' + index + '].active'] = !this.TabList[index].active;
				this.setData(d);
			},

			radioChange(e) {
				// console.log('radio发生change事件，携带value值为：', e.detail.value, e);
				let that = this; // if(e.target.dataset.problem == 1){
				//   if (e.detail.value == '否') {
				//     wx.showModal({
				//       content: '为了您的用药安全，建议您到线下医院问诊',
				//       showCancel: false,
				//       success(res) {
				//         if (res.confirm) {
				//           console.log('用户点击确定')
				//           that.setData({ cancel: true })
				//         }
				//       }
				//     })
				//   }
				//   if (e.detail.value == '是'){
				//     this.setData({taboo:true})
				//   }else{
				//     this.setData({taboo:false})
				//   }
				// }
				// if(e.target.dataset.problem == 2){
				//   if (e.detail.value == '是') {
				//     wx.showModal({
				//       content: '为了您的用药安全，建议您到线下医院问诊',
				//       showCancel: false,
				//       success(res) {
				//         if (res.confirm) {
				//           console.log('用户点击确定')
				//           that.setData({ cancel: true })
				//         }
				//       }
				//     })
				//   }
				//   if (e.detail.value == '否'){
				//     this.setData({allergy:true})
				//   }else{
				//     this.setData({allergy:false})
				//   }
				// }
				// if(e.target.dataset.problem == 3){
				//   if (e.detail.value == '是' && e.target.dataset.problem == 3) {
				//     wx.showModal({
				//       content: '为了您的用药安全，建议您到线下医院问诊',
				//       showCancel: false,
				//       success(res) {
				//         if (res.confirm) {
				//           console.log('用户点击确定')
				//           that.setData({ cancel: true })
				//         }
				//       }
				//     })
				//   }
				//   if (e.detail.value == '否' && e.target.dataset.problem == 3){
				//     this.setData({reaction:true})
				//   }else{
				//     this.setData({reaction:false})
				//   }
				// }

				if (e.target.dataset.problem == 4) {
					if (e.detail.value == '否') {
						req.msg('根据相关规定，开具电子处方仅对复诊患者有效，您不是复诊患者，请就近就医。');
						that.setData({
							cancel: true,
							uploadVoucher: false,
							voucher: false
						});
					}

					if (e.detail.value == '是') {
						this.setData({
							restoration: true
						});
					} else {
						this.setData({
							restoration: false
						});
					}
				} // if(e.target.dataset.problem == 5){
				//   if (e.detail.value == '否' && e.target.dataset.problem == 5) {
				//           that.setData({ voucher: true,uploadVoucher:false })
				//   }
				//   if (e.detail.value == '是' && e.target.dataset.problem == 5){
				//     this.setData({uploadVoucher:true,voucher:false})
				//   }
				// }

			},

			//上传图片
			uploadAvatar() {
				let that = this;
				uni.chooseImage({
					count: 3,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: function({
						tempFilePaths
					}) {
						var promise = Promise.all(tempFilePaths.map((tempFilePath, index) => {
							return new Promise(function(resolve, reject) {
								req.loadIng("上传中");
								req.uploadFile('/api/upload', tempFilePath, res => {
									// console.log(res);
									that.setData({
										avatar: that.avatar.concat(res.src)
									});
									uni.showToast({
										title: '上传成功',
										icon: 'success',
										duration: 2000
									});
									// console.log(that.avatar);
								});
							});
						}));
						promise.then(function(results) {
							// console.log(results);
						}).catch(function(err) {
							// console.log(err);
						});
					}
				});
			},

			// 删除图片
			cleanimage(event) {
				let index = event.currentTarget.dataset.index;
				let arr = this.avatar;
				arr.splice(index, 1);
				this.setData({
					avatar: arr
				});
			},

			// 获取病症和医生
			getDoctor() {
				return new Promise((res, rej) => {
					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 || !data.hnty || data.hnty.code != 0) {
								uni.disableAlertBeforeUnload();
								uni.showModal({
									content: !data.doctor || data.doctor.code != 0 ? '当前医师不在线，请稍后再试' : '病症获取失败，请稍后再试',
									showCancel: false,
									success(res) {
										if (res.confirm) {
											// console.log('用户点击确定');
											uni.navigateBack(); // that.setData({ cancel: true })
										}
									}
					
								});
							}
					
							let hnty;
							let about=JSON.parse(req.getStorage('configRes'))
							// console.log(about,about.prescription_disease&&about.prescription_disease!=2)
							if(!about.prescription_disease || (about.prescription_disease&&about.prescription_disease!=2)){
								if (data.hnty && data.hnty.data) {
									hnty = JSON.parse(data.hnty.data);
								}
								if (req.getStorage('diagnosis')) {
									hnty = hnty.concat(req.getStorage('diagnosis'))
								}
								this.setData({
									TabList: hnty,
									hnty: hnty
								});
							}
							// console.log(hnty);
							this.setData({
								doctor: data.doctor.data,
							});
							res(data)
						}
					});
				})
			},

			// 获取药品信息
			getDrug() {
				req.postRequest('/api/orderdurg/drugorder', {
					orderId: this.query.orderId
				}, res => {
					var a = [true]
					let that=this
					if (!res) {} else {
						if (req.getStorage('diagnosis')) {
							that.labe = that.labe.concat(req.getStorage('diagnosis'))
						}
						a = res.drugs.map(it => {
							if(!it.label){
								
							}else{
								that.getLabel(it.label.split(','))
							}
							var regex = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]")
							var danwei = new RegExp("[\\u4E00-\\u9FFF]+$", "g")
							if (it.number < 1) {
								return req.msg(it.drugName + "药品信息不完整，暂不支持开方")
							} else if (!it.drugName) {
								return req.msg("药品信息不完整，暂不支持开方")
							} else if (regex.test(it.drugName)) {
								return req.msg(it.drugName.trim() + "药品名称不符合规范，暂不支持开方")
							} else if (!it.unit) {
								return req.msg(it.drugName + "药品单位信息不完整，暂不支持开方")
							} else if (!danwei.test(it.unit)) {
								return req.msg(it.drugName + "药品单位信息不符合规范，暂不支持开方")
							} else if (!it.spec) {
								return req.msg(it.drugName + "药品规格信息不完整，暂不支持开方")
							} else {
								return true
							}
						});
						// console.log(a)
						if (a[0]) {
							this.setData({
								pageList: res.drugs,
								sum: res.drugs.length
							})
						}
					}
				});
			},
			// 数组转换
			getLabel(arr){
				// console.log(arr,"11")
				let that=this
				let arrList = [];
				        for (let i in arr) {
				          var j = {};
				          j.name = arr[i];
						  j.id=""
				          arrList.push(j);
				        }
						
				let about=JSON.parse(req.getStorage('configRes'))
				if(!about.prescription_disease){
				
				}else{
					if(about.prescription_disease==0){
						
					}else if(about.prescription_disease==1){
						let all
						all=arrList.concat(this.TabList)
						that.TabList=all
					}else if(about.prescription_disease==2){
						that.labe=that.labe.concat(arrList)
						that.TabList=that.labe
					}
					
				}
			},

			updown() {
				// let list=this.data.list
				// let data
				if (this.pageList.length <= 0) return false;
				this.setData({
					pageShow: !this.pageShow
				});
			},

			save: util.throttle(function() {
				// console.log(this.drugUsers);
				let that = this; // console.log(this.data.TabList.filter(it=>it.active))

				let diagnosis;

				if (this.TabList) {
					diagnosis = this.TabList.filter(it => it.active);
				}

				if (!this.drugUsers) return req.msg("请添加用药人");
				if (diagnosis.length < 1) return req.msg("没有添加病症");
				if (this.pageList.length <= 0) return req.msg("药品信息错误");
				if (!this.restoration) return req.msg("根据相关规定，开具电子处方仅对复诊患者有效，您不是复诊患者，请就近就医。");
				let form = {
					peopleId: this.drugUsers.id,
					orderId: this.query.orderId,
					diagnosis: JSON.stringify(diagnosis),
					isVisit: this.restoration ? 1 : 0,
					voucherImage: this.avatar,
					state: 2
				};

				if (this.restoration && this.drugUsers && this.pageList.length > 0) {
					req.postRequest('/api/userDrugPeople/updateODU', form, data => {
						// if(data=="成功"){
						app.globalData.openPage('prescription/dialogue/index?uId=' + that.drugUsers.id + '&diagnosis=' + JSON.stringify(
								diagnosis) + '&txtdrugs=' + JSON.stringify(that.pageList) + '&orderId=' + that.query.orderId +
							'&restoration=' + form.isVisit + '&doctor=' + that.doctor); // }
					});
				}
			}, 1500)
		}
	};
</script>
<style>
	@import "./index.css";
</style>
