<template>
	<view>
		<topnav :title='pageTitle' @tohome='tohome'></topnav>
		<view class="content">
			<view class="pageTitle">基本信息</view>
			<view class="listBox mp-20">
				<view class="listBoxItem">
					<view class="listBoxItemLeft">
						{{currentProject.name}}-{{product.name}}

					</view>
					<view class="listBoxItemRight">

					</view>
				</view>
				<view class="listBoxline"></view>
				<picker mode="date" :value="sdate" :start="startDate" :end="endDate" @change="bindDateChange">
					<view class="listBoxItem">
						<view class="listBoxItemLeft">
							<view class="vred">*</view>服务日期
						</view>
						<view class="listBoxItemRight">

							<text class="novalue" v-if="sdate==''">请选择</text>
							<text v-else>{{sdate}}</text>

							<text class="iconfont icon-Icons_ToolBar_ArrowRight"></text>
						</view>
					</view>
				</picker>

				<view class="listBoxline"></view>
				<view class="listBoxItem">
					<view class="listBoxItemLeft">
						<view class="vred">*</view>服务天数
					</view>
					<view class="listBoxItemRight">
						<uninumberbox :min="1" :max="99" :value="days" @change="bindChangeDay"></uninumberbox>
					</view>
				</view>
				<view class="listBoxline"></view>
				<view class="listBoxItem">
					<view class="listBoxItemLeft">
						<view class="vred">*</view>结束日期
					</view>
					<view class="listBoxItemRight">
						<text>{{edate}}</text>
					</view>
				</view>
			</view>

			<view class="pageTitle">被护理人信息</view>
			<view class="listBox mp-20">
				<view class="listBoxItem">
					<view class="listBoxItemLeft">
						<view class="vred">*</view>姓名
					</view>
					<view class="listBoxItemRight">
						<input type="text" class="listBoxItemInput" placeholder-class="listBoxItemInputPlaceholder"
							placeholder="请输入" :value="patient.name" @input='bindChangePatent' data-type='name' />
					</view>
				</view>
				<view class="listBoxline"></view>
				<view class="listBoxItem">
					<view class="listBoxItemLeft">
						<view class="vred">*</view>电话
					</view>
					<view class="listBoxItemRight">
						<input type="number" class="listBoxItemInput" placeholder-class="listBoxItemInputPlaceholder"
							placeholder="请输入" :value="patient.mobile" @input='bindChangePatent' data-type='mobile' />
					</view>
				</view>
				<view class="listBoxline"></view>

				<view class="listBoxItem">
					<view class="listBoxItemLeft">
						<view class="vred">*</view>性别
					</view>
					<view class="listBoxItemRight">
						<radio-group class="radiogroup" @change="radioChange">
							<label class="radioitemlabel">
								<view>
									<radio class="radioitem" :checked="patient.sex==null||patient.sex=='男'" value="男" />
								</view>
								<view>男</view>
							</label>
							<label class="radioitemlabel">
								<view>
									<radio class="radioitem" :checked="patient.sex=='女'" value="女" />
								</view>
								<view>女</view>
							</label>
						</radio-group>
					</view>
				</view>
				<view class="listBoxline"></view>

				<view class="listBoxItem">
					<view class="listBoxItemLeft">
						<text style="margin-left: 20rpx;">年龄</text>
					</view>
					<view class="listBoxItemRight">
						<input type="number" class="listBoxItemInput" placeholder-class="listBoxItemInputPlaceholder"
							placeholder="请输入" :value="patient.age" @input='bindChangePatent' data-type='age' />
					</view>
				</view>
				<view class="listBoxline"></view>

				<picker @change="bindMultiPickerChange" :value="multiIndex" :range-key='name' :range="multiArray">
					<view class="listBoxItem">
						<view class="listBoxItemLeft">
							<view class="vred">*</view>病区/楼层
						</view>
						<view class="listBoxItemRight">
							<text>{{selectArea==""?"请选择病区/楼层":selectArea}}</text>

							<text class="iconfont icon-Icons_ToolBar_ArrowRight"></text>
						</view>
					</view>
				</picker>
				<view class="listBoxline"></view>

				<picker @change="bindPickerChange" :value="index" :range="array">
					<view class="listBoxItem">
						<view class="listBoxItemLeft">
							<view class="vred">*</view>病床
						</view>
						<view class="listBoxItemRight">
							<text>{{selectbed==""?"请选择病床":selectbed}}</text>
							<text class="iconfont icon-Icons_ToolBar_ArrowRight"></text>
						</view>
					</view>
				</picker>

			</view>
			<view class="pageTitle">服务需求</view>
			<view class="listBox mp-20">
				<picker :value="itemsindex" :range="product_items" range-key="name" @change="bindChangeItem">
					<view class="listBoxItem">
						<view class="listBoxItemLeft">
							<view class="vred">*</view>产品规格
						</view>
						<view class="listBoxItemRight">
							<text>{{product_items[itemsindex]==null?"":product_items[itemsindex].name}}</text>
							<text class="iconfont icon-Icons_ToolBar_ArrowRight"></text>
						</view>
					</view>
				</picker>

				<view class="listBoxline"></view>

				<picker :value="levelindex" :range="levels" range-key="paramedic_level_name" @change="bindChangeLevel">
					<view class="listBoxItem">
						<view class="listBoxItemLeft">
							<view class="vred">*</view>护工等级

						</view>
						<view class="listBoxItemRight">
							<text>{{levels[levelindex]==null?"":levels[levelindex].paramedic_level_name}}</text>
							<text class="iconfont icon-Icons_ToolBar_ArrowRight"></text>
						</view>
					</view>
				</picker>

				<block v-for="(item,pindex) in factors">
					<view class="listBoxline"></view>
					<picker :value="factorsIndex" :range="item.factor_items" range-key="name" @change="bindChangeFactor"
						:data-pindex='pindex'>
						<view class="listBoxItem">
							<view class="listBoxItemLeft">
								<view class="vred">*</view>{{item.name}}
							</view>
							<view class="listBoxItemRight">
								<text>{{factorsArr[pindex][factorsIndex[pindex]]}}</text>

								<text class="iconfont icon-Icons_ToolBar_ArrowRight"></text>
							</view>
						</view>
					</picker>
				</block>
			</view>
			<view class="pageTitle">选择护工</view>
			<view class="listBox mp-20">
				<view class="listBoxItem" @click="bindSelectCarer">
					<view class="listBoxItemLeft">
						<text style="margin-left: 20rpx;">添加护工</text>
					</view>
					<view class="listBoxItemRight">
						<text>{{selectCarer==""?"请选择":selectCarer}}</text>
						<text class="iconfont icon-Icons_ToolBar_ArrowRight"></text>
					</view>
				</view>
				<view class="listBoxline"></view>
				<view class="listBoxItem">
					<view class="listBoxItemLeft">
						<view class="vred">*</view>协商价格
					</view>
					<view class="listBoxItemRight">
						<input type="number" class="listBoxItemInput" placeholder-class="listBoxItemInputPlaceholder"
							placeholder="请输入协商价格" @input='bindCaculate' :value="salePrice" />
					</view>
				</view>

				<view class="listBoxline" v-if="showEffect">

				</view>

				<view class="listBoxItem" v-if="showEffect">
					<view class="listBoxItemLeft">
						生效日期
					</view>
					<view class="listBoxItemRight">
						<radio-group class="radiogroup" @change="radioChangeAvailable">
							<label class="radioitemlabel" style="margin-left: 0;">
								<view>
									<radio class="radioitem" checked="true" value="today" />
								</view>
								<view>今日生效</view>
							</label>
							<label class="radioitemlabel" style="margin-left: 0;">
								<view>
									<radio class="radioitem" value="tomorrow" />
								</view>
								<view>明日生效</view>
							</label>
						</radio-group>
					</view>
				</view>

			</view>

			<view class="protocol"><label class="radio">
					<radio class="raInput" checked="true" />客户已阅读并同意陪护协议
				</label></view>
		</view>
		<view class="bottom">
			<view class="bottomLeft">
				<text class="priceTitle">金额合计：</text>
				<text class="priceInfo">￥{{totalPrice}}</text>
			</view>
			<view class="bottomRight">
				<view class="btnCancel btn" @click="bindCancel">取消</view>
				<view class="btnSubmit btn" @click="bindsubmitFun">提交</view>
			</view>
		</view>

	</view>
</template>

<script>
	var util = require("../../../../utils/util.js");
	import uninumberbox from "@/uni_modules/uni-number-box/components/uni-number-box/uni-number-box.vue";
	export default {
		components: {
			uninumberbox
		}, //2.注册组件
		data() {
			const currentDate = this.getDate({
				format: true
			})

			return {
				pageTitle: "创建订单",
				sdate: currentDate,
				edate: "",
				days: 1,
				patient: {
					name: "",
					mobile: "",
					age: "",
					sex: "",
					weight: "",
					hight: ""
				},
				product: [],
				product_items: [],
				levels: [],
				factors: [],
				factorsIndex: [],
				levelindex: 0,
				itemsindex: 0,
				currentProject: null,
				totalPrice: 0,
				salePrice: 0,
				multiArray: [],
				showMuti: [],
				objectMultiArray: [],
				multiIndex: [0, 0],
				selectArea: "",
				selectAreaID: "",
				objectArray: [],
				selectCarer: "",
				selectCarerID: '',
				array: [],
				index: 0,
				selectbed: "",
				selectbedID: "",
				contact: "",
				mobile: "",
				factorsArr: [],
				id: "",
				showEffect: false,
				isEdit: false,
				orderCarerID: '',
				orderCarer: '',
				available_day: ''
			}
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		onLoad: function(option) {
			var that = this;
			this.loadproductdata();
			this.loadAreas();
			if (!util.isNull(option.id)) {
				this.id = option.id;
				this.showEffect = true;
				util.getOrderInfo(option.id, function(r) {
					var order = r.data;
					that.available_day = 'today'
					that.pageTitle = "修改订单";
					that.isEdit = true;
					that.patient = order.patient;
					that.patient.mobile = order.mobile;
					that.sdate = order.from_date;
					that.edate = order.to_date;
					that.selectArea = order.bed.building_name + '-' + order.bed.area_name;
					that.selectbed = order.bed.room_name + "-" + order.bed.name;
					that.selectbedID = order.bed.id;
					that.selectCarer = order.paramedic.name;
					that.selectCarerID = order.paramedic.id;
					that.orderCarerID = order.paramedic.id;
					that.orderCarer = order.paramedic.name;
					that.salePrice = order.price;
					let edate = Date.parse(order.to_date);
					let sdate = Date.parse(order.from_date);
					console.log(edate - sdate)
					that.days = parseInt((edate - sdate) / (1000 * 60 * 60 * 24)) + 1
					var i = 0;
					for (var m of that.product_items) {
						if (m.id == order.product_item.id) {
							that.itemsindex = i;
						}
						i++;
					}

					var j = 0;
					for (var m of that.levels) {
						if (m.id == order.paramedic_level.id) {
							that.levelindex = j;
						}
						j++;
					}

					var _i = 0;
					for (var m of that.factors) {
						that.factorsIndex[_i] = [];
						var _j = 0;
						for (var mod of m.factor_items) {
							var _ii = 0;
							for (var f of order.factorjson) {
								if (m.id == order.factorjson[_ii].factor_id && mod.id == order.factorjson[_ii]
									.factor_item_id) {
									that.factorsIndex[_i] = _j;
								}
								_ii++;
							}
							_j++;
						}
						_i++;
					}
					//that.toCaculate()
					console.log(that.factorsIndex)

				}, function(r) {

				})
			}


			this.toCalEDate(this.sdate, this.days);
		},
		onShow: function() {
			var carer = uni.getStorageSync("selectCarer");
			if (carer != null && !util.isNull(carer)) {
				this.selectCarer = carer.name;
				this.selectCarerID = carer.id;

			}

		},
		onUnload: function() {
			uni.removeStorageSync('selectCarer');

		},
		onHide: function() {
			uni.removeStorageSync('selectCarer');
		},
		methods: {
			tohome: function() {
				uni.navigateTo({
					url: "../../../../pages/index/index"
				})
			},
			bindSelectCarer: function() {
				uni.navigateTo({
					url: "../../../packagecarer/pages/selectcarer/selectcarer?from=createOrder"
				})
			},
			bindCancel: function(e) {
				uni.navigateBack({
					delta: 0
				})

			},
			bindMultiPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				var mutiIndex = e.detail.value;
				var that = this;
				this.multiIndex = e.detail.value;
				this.selectArea = that.objectMultiArray[mutiIndex].name;
				this.selectAreaID = that.objectMultiArray[mutiIndex].id;
				this.selectbedID = "";
				this.selectbed = "";
				that.loadBeds(that.selectAreaID);
			},
			bindPickerChange: function(e) {
				var that = this;
				var index = e.detail.value;
				that.index = e.detail.value;
				that.selectbedID = that.objectArray[index].id;
				that.selectbed = that.objectArray[index].name + '床';

			},
			radioChangeAvailable: function(e) {
				this.available_day = e.detail.value;
			},
			radioChange: function(e) {
				var _patient = this.patient;
				_patient.sex = e.detail.value;
				this.patient = _patient;
			},
			loadBeds: function(id) {
				var that = this;
				util.request({
					api: 'manager/get-area-beds/' + id,
					utilSuccess: function(res) {
						var arr = [];
						var objectArr = [];
						console.log(res)
						res.forEach(function(item, index) {
							arr.push(item.room_name + "-" +item.name);
							objectArr.push({
								id: item.id,
								name: item.room_name + "-" + item.name
							});
						})

						that.objectArray = objectArr;
						that.array = arr;
					},
					utilFail: function(err) {
						util.alert(err);
					}
				});

			},

			loadAreas: function() {
				var that = this;
				util.request({
					api: 'manager/get-project-areas/' + that.currentProject.id,
					utilSuccess: function(res) {
						var arr = [];
						var objectArr = [];

						console.log(res)
						res.forEach(function(item, index) {
							arr.push(item.building_name + "-"+item.name);
							objectArr.push({
								id: item.id,
								name: item.building_name + "-" + item.name

							});
						})
						that.multiArray = arr;
						that.objectMultiArray = objectArr;
					},
					utilFail: function(err) {
						util.alert(err);
					}
				});
			},
			toCalEDate: function(sdate, num) {
				//new Date():系统当前时间，先将当前时间转化为时间戳的形式
				var timestamp = Date.parse(sdate); //想在系统当前时间基础上，想加的天数或小时

				var dayNum = num - 1; //天数*24小时

				timestamp = timestamp + dayNum * 24 * 60 * 60 * 1000; //转化成年月日 时分秒 的形式

				var dayText = util.formatTime(new Date(timestamp), 'YYYY-MM-DD');
				this.edate = dayText;

				this.totalPrice = this.days * this.salePrice;
			},
			bindCaculate: function(e) {
				this.salePrice = e.detail.value;

				this.totalPrice = this.days * this.salePrice;
			},
			toCaculate: function() {
				var _total = 0;
				var i = 0;
				for (var m of this.factors) {
					_total += parseFloat(m.factor_items[this.factorsIndex[i]].price);
					i++;
				}
				var singlePrice = parseFloat(this.product_items[this.itemsindex]
					.price) + parseFloat(this.levels[this.levelindex]
					.price) + _total;

				this.salePrice = singlePrice;
				this.totalPrice = this.days * singlePrice;
			},
			bindChangeFactor: function(e) {
				var pindex = e.currentTarget.dataset.pindex;
				this.factorsIndex.splice(pindex, 1, e.detail.value);
				this.toCaculate();
			},
			bindChangeItem: function(e) {
				this.itemsindex = e.target.value
				this.toCaculate();
			},
			bindChangeLevel: function(e) {
				this.levelindex = e.target.value
				this.toCaculate();
			},
			bindDateChange: function(e) {
				this.sdate = e.target.value
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 1;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			bindChangeDay: function(e) {
				this.days = e
				this.toCalEDate(this.sdate, e);

			},
			bindChangePatent: function(e) {
				var type = e.currentTarget.dataset.type;
				var _patient = this.patient;
				switch (type) {
					case "name":
						_patient.name = e.detail.value;
						break;
					case "mobile":
						_patient.mobile = e.detail.value;
						break;
					case "age":
						_patient.age = e.detail.value;
						break;
				}

				this.patient = _patient;
			},
			loadproductdata: function() {
				var that = this;
				var currentProject = uni.getStorageSync('currentProject');
				that.currentProject = currentProject;
				util.request({
					bindThis: that,
					api: 'manager/get-care-product/' + currentProject.id,
					customLoading: false,
					utilSuccess: function(res) {
						that.product = res;
						var _factors = res.factors;
						var _factorsIndex = [];
						var _factorsArr = [];
						var _total = 0;
						for (var m of _factors) {
							_factorsIndex.push(0);
							_total += parseFloat(m.factor_items[0].price);
							var arr = [];
							for (var item of m.factor_items) {
								arr.push(item.name)
							}
							_factorsArr.push(arr);
						}
						that.factors = _factors;
						that.factorsArr = _factorsArr;
						that.factorsIndex = _factorsIndex;
						that.product_items = res.product_items;
						that.levels = res.product_paramedic_levels;
						that.salePrice = parseFloat(res.product_items[0].price) + parseFloat(res
							.product_paramedic_levels[0]
							.price) + _total;

						that.toCaculate();
					},
					utilFail: function(res) {
						util.alert(res);
					}
				});
			},
			bindsubmitFun: function() {
				let that = this; // 如果未登录，先跳转到登录页面

				if (!util.isLogin()) {
					uni.navigateTo({
						url: '/pages/login/login'
					});
					return;
				}



				if (this.days < 1) {
					uni.showModal({
						title: '提示',
						content: '服务天数不能为0',
						showCancel: false
					});
					return;
				}

				if (this.sdate == "") {
					uni.showModal({
						title: '提示',
						content: '请选择开始日期',
						showCancel: false
					});
					return;
				}

				if (this.selectbed == "") {
					uni.showModal({
						title: '提示',
						content: '请选择病床',
						showCancel: false
					});
					return;
				}

				if (this.patient.name == "") {
					uni.showModal({
						title: '提示',
						content: '请填写被护理人姓名',
						showCancel: false
					});
					return;
				}

				if (this.patient.mobile == "") {
					uni.showModal({
						title: '提示',
						content: '请填写被护理人电话',
						showCancel: false
					});
					return;
				}

				if (this.patient.sex == "") {
					uni.showModal({
						title: '提示',
						content: '请选择被护理人性别',
						showCancel: false
					});
					return;
				} //组建立即购买信息

				this.createOrder();
			},
			createOrder: function(e) {
				var that = this;
				var strFactor = [];
				var i = 0;
				for (var factor of that.factors) {
					var mod = factor.factor_items[that.factorsIndex[i]];
					console.log(mod)
					strFactor.push({
						id: factor.id,
						factor_item_id: mod.id
					})

					i++;
				}

				if (strFactor.length != that.factors.length) {
					uni.showModal({
						title: '提示',
						content: '请选择服务详情',
						showCancel: false
					});
					return false;
				}

				console.log('1：提交进入');
				var data = {
					product_id: that.product.id,
					product_item_id: that.product_items[that.itemsindex].id,
					bed_id: this.selectbedID,
					patient_name: this.patient.name,
					patient_mobile: this.patient.mobile,
					patient_age: this.patient.age,
					patient_sex: this.patient.sex,
					contact: this.contact,
					mobile: this.mobile,
					from_date: this.sdate,
					to_date: this.edate,
					paramedic_id: this.paramedic_id,
					product_paramedic_level_id: this.levels[that.levelindex].id,
					factors: JSON.stringify(strFactor),
					price: that.salePrice,
					paramedic_id: that.selectCarerID,
					available_day: that.available_day
				};
				console.log('2：数据' + JSON.stringify(data));
				var url = util.isNull(that.id) ? "manager/create-order" : "manager/update-order/" + that.id;
				util.request({
					bindThis: that,
					method: 'POST',
					customLoading: false,
					api: url,
					data: data,
					utilSuccess: function(res) {
						console.log('3：提交成功返回' + res);
						that.processAfterCreateOrder(res);
					},
					utilFail: function(res) {
						console.log('4：提交失败' + res);
						util.alert(res);
					}
				});
			},
			processAfterCreateOrder: function(res) {
				var id = res.id;
				if (res.affected_orders.length != 0) {
					// uni.showModal({
					// 	title: '提示',
					// 	content: "该订单的操作影响到了相关订单是否去修改？",
					// 	confirmText: "确认",
					// 	confirmColor: "#000",
					// 	cancelColor: "#eee",
					// 	success(res) {
					// 		if (res.confirm) {

					// 		} else if (res.cancel) {
					// 			uni.navigateTo({
					// 				url: '/package/packageorder/pages/orderinfo/orderinfo?id=' + id
					// 			});
					// 		}
					// 	}

					// });
					
					var m=res.affected_orders[0]
					var from_paramedic_id=m.from_paramedic_id;
					
					
					uni.navigateTo({
						url: '/package/packageorder/pages/updateOtherOrder/updateOtherOrder?id='+id+'&from_paramedic_id=' + from_paramedic_id
					});

				} else {

					uni.navigateTo({
						url: '/package/packageorder/pages/orderinfo/orderinfo?id=' + id
					});

				}
			}
		}
	}
</script>

<style>
	page {
		padding-top: 160rpx;
		padding-bottom: 120rpx;
	}

	.bottom {
		background: #FFFFFF;
		box-shadow: 0 -2rpx 12rpx 0 rgba(0, 0, 0, 0.16), inset 0 1rpx 0 0 #E4E4E4;
		width: 100%;
		height: 100rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: space-between;
	}

	.bottom .bottomLeft {
		display: flex;
		align-items: center;
	}

	.bottom .bottomRight {
		display: flex;
	}

	.btn {
		width: 220rpx;
		line-height: 100rpx;
		text-align: center;
		line-height: 100rpx;
		font-family: SourceHanSansCN-Medium;
		font-size: 32rpx;
		letter-spacing: 0;
	}

	.btnCancel {

		color: #666666;
		background: #F0F0F0;
	}

	.btnSubmit {

		color: #FFFFFF;
		background: #0DC99E;
	}


	.priceTitle {
		font-family: SourceHanSansCN-Normal;
		font-size: 24rpx;
		color: #999999;
		letter-spacing: 0;
		line-height: 28rpx;
		margin-left: 32rpx;
	}

	.priceInfo {
		font-family: SourceHanSansCN-Normal;
		font-size: 24rpx;
		color: orange;
		margin-left: 10rpx;
		letter-spacing: 0;
		line-height: 28rpx;
	}

	.protocol {
		padding: 30rpx 21rpx;
		font-family: SourceHanSansCN-Normal;
		font-size: 28rpx;
		color: #999999;
		letter-spacing: 0;
		align-items: center;
		display: flex;
	}

	.protocol .raInput {
		transform: scale(0.7)
	}

	.icon-Icons_ToolBar_ArrowRight {
		color: rgba(0, 0, 0, 0.45);
		font-size: 22rpx;
		margin-left: 13rpx;
		margin-top: 5rpx;
	}

	.radiogroup {
		display: flex;
		flex-direction: row;
	}

	.radioitemlabel {
		flex: 1;
		display: flex;
		align-items: center;
		margin-left: 134rpx;
	}

	.radioitem {
		transform: scale(0.7)
	}
</style>
