<template>
	<view>
		<view class="dataInfo">
			<view class="dataList" v-for="(item,index) in searchData" :key="index">
				<checkbox-group @change="checkClick(item)">
					<checkbox :checked="item.checked" />
				</checkbox-group>
				<view class="details">
					<!-- <view class="img">
						<image :src="item.photoUrl"></image>
					</view> -->
					<view class="text">
						<text>{{item.parentName}}</text>
						<text>规格：{{item.typeName}}</text>
						<!-- <text>￥{{item.price}}</text> -->
					</view>
				</view>
				<view class="action">
					<text @click="reduce(item)">-</text>
					<text>{{item.bookNum}}</text>
					<text @click="add(item)">+</text>
				</view>
			</view>
		</view>
		<!-- <button @click="delCart">删除</button> -->
		<view class="buy">
			<view class="checked">
				<checkbox-group @tap="checkAll">
					<checkbox :checked="allChecked" />
				</checkbox-group>
				<text>全选</text>
			</view>
			<view class="total">
				<!-- <view class="price">
					<text>总计：</text>
					<text>￥{{totalPrice}}</text>
				</view> -->
				<view class="bill" @click="finishCart">
					<text>确认申请</text>
				</view>
			</view>
		</view>
		<uni-popup
			ref="popup" 
			type="center"
			:mask-click="false"
		>
			<view class="popup">
				<view class="pop-top">
					<h4>部门工程选择</h4>
					<uni-icons 
						style="color: #AAAAAA; font-weight: bold;" 
						type="closeempty" 
						@click="closePopup"
					>
					</uni-icons>
				</view>
				<view class="select-area">
					<uni-forms ref="deptForm" :modelValue="deptFormData" :rules="rules">
						<uni-forms-item name="deptName" required label="选择部门" label-width="100">
							<zxz-uni-data-select
							  v-model="deptFormData.deptName"
							  :localdata="deptRange"
							  @change="deptChange"
							  filterable
							></zxz-uni-data-select>
						</uni-forms-item>
						<uni-forms-item name="projName" required label="选择工程" label-width="100">
							<zxz-uni-data-select
							  v-model="deptFormData.projName"
							  :localdata="projRange"
							  filterable
							></zxz-uni-data-select>
						</uni-forms-item>
						<button 
							class="submit-btn" 
							@click="formSubmit"
							:disabled="btnDisabled"
						>
							保存
						</button>
					</uni-forms>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
import { basePath } from '../../public';
	export default {
		data() {
			return {
				allChecked: false,
				inputs: "",
				list: [],
				delList: [],
				delArr: [],
				totalFine: '',
				totalGoods: [],
				sendData: {},
				deptFormData: {
					deptName: '',
					projName: '',
					agreementId: null,
					agreementCode: null
				},
				deptRange: [
					
				],
				projRange: [
					
				],
				rules: {
					deptName: {
						rules: [
							{
								required: true,
								errorMessage: '请选择部门！'
							}
						]
					},
					projName: {
						rules: [
							{
								required: true,
								errorMessage: '请选择工程！'
							}
						]
					}
				},
				btnDisabled: false,
				ableUseArr: ['admin', 'em04', 'me02', 'dm03']
			}
		},
		computed: {
			totalPrice() {
				var str = 0;
				for (var i = 0; i < this.searchData.length; i++) {
					if (this.searchData[i].checked) {
						str += this.searchData[i].num * this.searchData[i].price;
					}
				}
				this.totalFine = str
				return str;
			},
			searchData: function() {
				if (!this.inputs) {
					return this.list;
				}
				return this.list.filter((item) => {
					return item.name.includes(this.inputs);
				});
			},
		},
		methods: {
			add(item) {
				let that = this
				let num = item.bookNum
				item.bookNum = num + 1
				that.$api.fetchMaterial.itemNumChange({
					id: item.id,
					bookNum: item.bookNum
				}).then(res => {
					console.log(res);
				})
			},
			reduce(item) { //减减
				let that = this
				let num = item.bookNum
				if (num > 1) {
					num -= 1
				} else if (num = 1) {
					uni.showToast({
						icon: 'none',
						title: "该器具无法再减少"
					})
				}
				item.bookNum = num
				that.$api.fetchMaterial.itemNumChange({
					id: item.id,
					bookNum: item.bookNum
				}).then(res => {
					console.log(res);
				})
			},
			// 单个商品的选择
			checkClick(item) {
				item.checked = !item.checked
				if (!item.checked) {
					this.allChecked = false
				} else {
					// 判断每一个商品是否是被选择的状态
					const goods = this.list.every(item => {
						return item.checked === true
					})
					if (goods) {
						this.allChecked = true
					} else {
						this.allChecked = false
					}
				}
			},
			//全选、全不选
			checkAll() {
				this.allChecked = !this.allChecked
				if (this.allChecked) {
					this.list.map(item => {
						item.checked = true
					})
				} else {
					this.list.map(item => {
						item.checked = false
					})
				}
			},
			finishCart () {
				let that = this
				that.totalGoods = that.list.filter((item) => {
					return item.checked == true
				})
				if (that.totalGoods.length == 0) {
					uni.showToast({
						icon: 'none',
						title: '未选择任何商品！'
					})
				} else {
					that.$refs.popup.open()
					
				}
			},
			formatDate (value) {
			    if (typeof (value) == 'undefined') {
			        return ''
			    } else {
			        let date = new Date(parseInt(value))
			        let y = date.getFullYear()
			        let MM = date.getMonth() + 1
			        MM = MM < 10 ? ('0' + MM) : MM
			        let d = date.getDate()
			        d = d < 10 ? ('0' + d) : d
			        let h = date.getHours()
			        h = h < 10 ? ('0' + h) : h
			        let m = date.getMinutes()
			        m = m < 10 ? ('0' + m) : m
			        let s = date.getSeconds()
			        s = s < 10 ? ('0' + s) : s
			        return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
			    }
			},
			closePopup () {
				this.$refs.popup.close()
			},
			
			async getgreementId(){
				const params = {
					unitId:this.deptFormData.deptName,
					projectId:this.deptFormData.projName
				}
				const res = await this.$api.exitMaterial.ifAgreement(params)
				if(res.data.code == 200){
					this.deptFormData = { ...this.deptFormData,...res.data.data }
				}else{
					this.deptFormData.deptName = ''
					this.deptFormData.projName = ''
					
					uni.showToast({
						duration:1000,
						title:'当前单位和工程未上传协议'
					})
				}
				console.log('getgreementId ==============',res);
			},
			
			async formSubmit () {
				let that = this
				let nowRole = uni.getStorageSync('roles')
				let found = false
				that.btnDisabled = true
				for (let role of nowRole) {
					console.log(role);
					if (that.ableUseArr.includes(role)) {
						found = true;
						break;
					}
				}
				console.log(found);
				await this.getgreementId()
				if (!found) {
					uni.showToast({
						icon: 'none',
						title: '当前角色没有操作权限！',
						success: () => {
							that.btnDisabled = false
						}
					})
				} else {
					// console.log(1);
					that.$refs.deptForm.validate().then(formData => {
						console.log(formData, that.totalGoods);
						that.totalGoods = that.totalGoods.map(item => {
							return {
								id: item['id'],
								createBy: uni.getStorageSync('userInfo').sysUser.userName,
								companyId: item['companyId'],
								status: '0',
								// createTime: that.formatDate(new Date().getTime()),
								typeId: item['typeId'],
								preNum: item['bookNum'],
								manageType: item['manageType']
							}
						})
						let setArr = []
						that.totalGoods.forEach(list => {
							setArr.push(list.companyId)
						})
						console.log(setArr);
						let set = new Set(setArr)
						console.log(set.size);
						if (set.size == 1) {
							that.sendData = {
								userId: uni.getStorageSync('userInfo').sysUser.userId,
								companyId: that.totalGoods[0].companyId,
								createBy: uni.getStorageSync('userInfo').sysUser.userName,
								unitId: formData.deptName,	
								projectId: formData.projName,
								agreementId: that.deptFormData.agreementId,
								agreementCode: that.deptFormData.agreementCode,
								taskType: 29,
								taskStatus: 30,
								// createTime: that.formatDate(new Date().getTime()),
								leaseApplyInfo: {
									leasePerson: uni.getStorageSync('userInfo').sysUser.userName,
									phone: uni.getStorageSync('userInfo').sysUser.phonenumber
								},
								leaseApplyDetails: that.totalGoods
							}
							console.log('that.sendData =================== ',that.sendData);
							// 提交预约商品
							that.$api.fetchMaterial.subCart(that.sendData).then(res => {
								console.log(res);
								if (res.data.code == 200) {
									uni.showToast({
										icon: 'none',
										title: res.data.msg,
										success: () => {
											uni.redirectTo({
												url: '/pages/orderCart/orderCart'
											})
										}
									})
								} else {
									uni.showToast({
										icon: 'none',
										title: res.data.msg,
										success: () => {
											that.btnDisabled = false
										}
									})
								}
							}).catch(err => {
								console.log(err);
							})
							that.$refs.popup.close()
						} else {
							uni.showToast({
								icon: 'none',
								title: '无法同时领用机具设备和调试设备！',
								success: () => {
									that.btnDisabled = false
								}
							})
						}
					})
				}
			},
			deptChange (e) {
				let that = this
				console.log(e);
				// 切换部门时展示工程
				this.$api.fetchMaterial.getProjList({
					id: e.value
				}, null).then(res => {
					console.log(res);
					if (res.data.code == 200) {
						that.projRange = res.data.data.map((item) => {
							return {
								text: item['name'],
								value: item['id']
							}
						})
					}
				}).catch(err => {
					
				})
			}
		},
		onNavigationBarButtonTap() {
			let that = this
			that.delArr = []
			let isChecked = that.list.every((item) => {
				return item.checked == false
			})
			if (that.list.length != 0 && isChecked == false) {
				uni.showModal({
					title: '删除商品',
					content: '确认删除商品吗？',
					success: (res) => {
						if (res.confirm) {
							that.delList = that.list.filter((item) => {
								return item.checked != false
							})
							/* that.list = that.list.filter((item) => {
								return item.checked == false
							}) */
							/* uni.showToast({
								icon: 'none',
								title: '商品删除成功！'
							}) */
							for (let i = 0; i < that.delList.length; i++) {
								that.delArr.push(that.delList[i].id)
							}
							that.$api.fetchMaterial.delCart(JSON.stringify(
								that.delArr
							)).then(res => {
								console.log(res);
								if (res.data.code == 200) {
									uni.showToast({
										icon: 'none',
										title: res.data.msg,
										success: () => {
											uni.redirectTo({
												url: '/pages/orderCart/orderCart'
											})
										}
									})
								} else {
									uni.showToast({
										icon: 'none',
										title: '删除商品失败！'
									})
								}
							}).catch(err => {
								console.log(err);
							})
						}
					}
				})
			}
		},
		onShow() {
			let that = this
			/* if (uni.getStorageSync('goodList').length != 0) {
				that.list = uni.getStorageSync('goodList')
			} else {
				uni.showToast({
					icon: 'none',
					title: '预约车内暂无设备！'
				})
			} */
			// 初始化查询全部部门
			console.log(uni.getStorageSync('roles'))
			that.$api.fetchMaterial.getDeptList().then(res => {
				if (res.data.code == 200) {
					that.deptRange = res.data.data.map(item => {
						return {
							text: item['name'],
							value: item['id']
						}
					})
					console.log(that.deptRange);
				}
			}).catch(err => {
				console.log(err);
			})
			// 初始化查询预约车内所有商品
			that.$api.fetchMaterial.getCartDetail().then(res => {
				console.log(res);
				if (res.data.code == 200) {
					for (let i = 0; i < res.data.data.length; i++) {
						res.data.data[i].checked = false
					}
					that.list = res.data.data
				}
				console.log(that.list);
				if (that.list.length == 0) {
					uni.showToast({
						icon: 'none',
						title: '预约车内暂无商品！'
					})
				}
			}).catch(err => {
				console.log(err);
			})
		}
	}
</script>
 
 
<style>
	body{
		box-sizing: border-box;
		padding-bottom: 10vh;
	}
	
	/deep/uni-checkbox .uni-checkbox-input {
		border-radius: 50%;
	}
 
	/deep/uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked {
		border-color: #ddd;
		color: #fff !important;
		background-color: #2DCF8C !important;
	}
 
	/deep/uni-checkbox .uni-checkbox-input {
		border-color: #ddd;
	}
 
	/deep/uni-checkbox .uni-checkbox-input:hover {
		border-color: #ddd;
	}
 
	.search {
		padding-top: 20rpx;
	}
 
	.search .searchIput {
		background-color: #e6e6e6;
		width: 95%;
		margin: 0 auto;
		height: 72rpx;
		line-height: 72rpx;
		border-radius: 50rpx;
		padding: 0 32rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
	}
 
	.search .searchIput input {
		font-size: 26rpx;
		width: 100%;
		color: grey;
	}
 
	.search .searchIput image {
		width: 34rpx;
		height: 34rpx;
	}
 
 
 
	.dataInfo {
		width: 95%;
		margin: 0 auto;
	}
 
	.dataInfo .dataList {
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 2px solid #F1F1F1;
		padding: 25rpx 0;
	}
 
	.dataInfo .dataList .details {
		display: flex;
		align-items: center;
		flex: 1;
		font-size: 0;
	}
 
	.dataInfo .dataList .details .img image {
		width: 200rpx;
		height: 140rpx;
		padding: 0 20rpx;
	}
 
	.dataInfo .dataList .details .text text {
		color: #000;
		font-size: 23rpx;
		display: block;
		padding: 10rpx 0;
	}
 
	.dataInfo .dataList .details .text text:last-child {
		/* color: red; */
		font-size: 25rpx;
	}
 
	.dataInfo .dataList .action text {
		font-size: 25rpx;
		color: #000;
		border: 1px solid #C8C7CC;
		display: inline-block;
		line-height: 50rpx;
		width: 60rpx;
		text-align: center;
		box-sizing: border-box;
	}
 
	.dataInfo .dataList .action text:nth-child(2) {
		border-left: none;
		border-right: none;
	}
 
	.buy {
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		left: 50%;
		bottom: 0;
		width: 95%;
		transform: translate(-50%, 0);
	}
 
	.buy .checked {
		display: flex;
		align-items: center;
	}
 
	.buy .checked text {
		font-size: 25rpx;
		color: #000;
		padding: 0 12rpx;
	}
 
	.buy .total {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
 
	.buy .total .price {
		padding-right: 20rpx;
 
	}
 
	.buy .total .price text {
		font-size: 27rpx;
		color: #C8C7CC;
		display: inline-block;
	}
 
	.buy .total .price text:last-child {
		color: red;
		font-weight: bold;
	}
 
	.buy .total .bill text {
		font-size: 25rpx;
		color: #fff;
		display: inline-block;
		border-radius: 30rpx;
		background: linear-gradient(#FE4A3F, #FF9600);	
		line-height: 70rpx;
		width: 150rpx;
		text-align: center;
	}
	
	.popup{
		width: 80vw;
		height: 50vh;
		background-color: #fff;
		border-radius: 15rpx;
		overflow: hidden;
	}
	
	.popup>.pop-top{
		width: 100%;
		height: 5vh;
		background-color: #F5F5F5;
		box-sizing: border-box;
		padding: 0 25rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.popup>.select-area{
		width: 85%;
		margin: 40rpx auto;
	}
	
	.popup>.select-area>.submit-btn{
		background-color: #409EFF;
		color: #fff;
	}
</style>