<template>
	<view>
		<u-navbar bgColor="#ffffff" :placeholder="true" titleStyle="font-weight:600" title="调班申请" :autoBack="true">
			<view slot="right" style="display: flex;align-items: center;">
				<view @click="gotoShenPi"
					style="display: flex;flex-direction: column;align-items: center;justify-content: center;">
					<image src="../../../../static/images/fireman/shenpi.png" style="height: 32rpx;width: 32rpx;">
					</image>
					<view style="font-size: 18rpx;font-weight: 600;color: #1296db;">审批记录</view>
				</view>
			</view>
		</u-navbar>
		<view v-if="show">
			<view class="paibanCard">
				<view class="title">
					<view class="line"></view>
					调班人员（我）
				</view>
				<uni-swipe-action class="none">
					<uni-swipe-action-item :threshold="0" :right-options="options2" :disabled="true"
						style="padding: 28rpx 44rpx;">
						<view class="menu-item-box" style="display: flex;">
							<text
								style="background-color: #0087fc;padding: 22rpx 15rpx;color: white;border-radius: 10rpx;margin-right: 15rpx;">
								<!-- {{item.label.slice(-2)}} -->
								{{userList.userName===undefined ? "" : userList.userName.slice(-2)}}
							</text>
							<view>
								<view style="font-weight: 600;">{{ userList.userName }}({{userList.teamName}})</view>
								<view style="font-size: 24rpx;color: gray;">
									<span style="margin-right: 20rpx">{{userList.secUnitName}}</span>
									<span>{{userList.plantName}}</span>
								</view>
							</view>
						</view>
					</uni-swipe-action-item>
				</uni-swipe-action>
			</view>

			<!-- 选择代班人员 -->
			<view class="paibanCard">
				<view class="title">
					<view class="line"></view>
					选择代班人员
				</view>
				<view style="background: #FFFFFF;border-radius: 20rpx;padding: 26rpx 41rpx;">
					<view class="pickPerson">
						<view class="picktitle">
							<image src="../../../../static/images/fireman/fire.png"
								style="width: 26rpx;height: 32rpx;margin-right: 10rpx;"></image>
							消防员
						</view>
						<image src="../../../../static/images/fireman/add.png" style="width: 135rpx;height: 46rpx;"
							@click="choose(form.teamId)"></image>
					</view>
					<uni-swipe-action>
						<uni-swipe-action-item :threshold="0" :right-options="options2" @click="bindClick">
							<view class="menu-item-box" style="display: flex;" v-if="checkList.length!== 0">
								<text
									style="background-color: #0087fc;padding: 22rpx 15rpx;color: white;border-radius: 10rpx;margin-right: 15rpx;">
									{{checkList.userName===undefined ? "" : checkList.userName.slice(-2) }}
								</text>
								<view>
									<view style="font-weight: 600;">{{ checkList.userName }}({{checkList.teamName}})
									</view>
									<view style="font-size: 24rpx;color: gray;">
										<span style="margin-right: 20rpx">{{checkList.secUnitName}}</span>
										<span>{{checkList.plantName}}</span>
									</view>
								</view>
							</view>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
			</view>
			<uni-forms :model="form" ref="form" :rules="rules">
				<view class="paibanCard">
					<view class="title">调班时间</view>
					<view class="pickTime">
						<view class="input1">
							<uni-forms-item name="text1">
								<uni-datetime-picker type="datetime" :clear-icon="false" v-model="form.text1"
									placeholder="请选择开始日期"></uni-datetime-picker></uni-forms-item>
						</view>
						<view class="input2">
							<uni-forms-item name="text2"><uni-datetime-picker type="datetime" :clear-icon="false"
									v-model="form.text2" placeholder="请选择结束日期" /></uni-forms-item>
						</view>
					</view>
				</view>



			</uni-forms>

			<!-- 申请理由 -->
			<view class="paibanCard">
				<view class="title">申请原因</view>
				<uni-forms-item name="applyReason">
					<uni-easyinput type="textarea" v-model="form.applyReason" placeholder="请输入调班申请原因" />
				</uni-forms-item>
			</view>
			<!-- 排班添加按钮 -->
			<view class="addPaiBan" @click="addTiaoBan">提交申请</view>
		</view>
		<view v-else style="display: flex;flex-direction: column;align-items: center;">
			<image src="../../../../static/images/none.png" style="width: 316rpx;height: 181rpx;margin-top: 100rpx;">
			</image>
			<view>暂无调班权限</view>
		</view>
	</view>
</template>

<script>
	import {
		getUserProfile
	} from '@/api/system/user.js'
	import {
		deptTreeSelect
	} from '@/api/system/dept.js'
	// 消防员信息 消防员详细信息
	import {
		listFiremen,
		getFiremen,
		getFiremenByName
	} from "@/api/fireman/index.js"
	import {
		schedulyDutyLog
	} from "@/api/fireman/dutylog.js"
	// 新增调班
	import {
		addTransferInfo
	} from "@/api/fireman/tiaoban.js"
	import {
		getInfo
	} from "@/api/login.js"
	let self = null;
	export default {
		data() {
			return {
				rules: {
					text1: {
						rules: [{
							required: true,
							errorMessage: '请输入开始时间'
						}]
					},
					text2: {
						rules: [{
							required: true,
							errorMessage: '请输入结束时间'
						}]
					},
					applyReason: {
						rules: [{
							required: true,
							errorMessage: '请输入申请原因'
						}]
					}
				},
				tiaobanList: [], //选中的调班选择人员
				treeData: [], //人员树列表
				checkList: [], //选中的代班人员列表
				form: {
					id: undefined,
					applyTransferId: undefined,
					applyTransfer: undefined,
					transferBeginDate: undefined,
					transferEndDate: undefined,
					replaceDutyId: undefined,
					replaceDutyName: undefined,
					applyReason: undefined,
					approvalContent: undefined,
					secUnitId: undefined,
					secUnitName: undefined,
					plantId: undefined,
					plantName: undefined,
					status: undefined,
					delFlag: undefined,
					createBy: undefined,
					createTime: undefined,
					updateBy: undefined,
					updateTime: undefined,
					remark: undefined,
					text1: undefined, //开始时间
					text2: undefined, //结束时间
					text3: undefined,
					text4: undefined
				},
				// applyReason: "", //申请原因
				multiple: false,
				selectParent: false,
				checkStrictly: false,
				activeId: '',
				personList: [], //人员列表
				options2: [{
					text: '删除',
					style: {
						backgroundColor: '#F56C6C'
					}
				}], //滑动删除
				userList: [], //申请调班信息
				userId: '', //申请人的id
				show: false, //页面申请显示
			};
		},
		created() {
			self = this
		},
		mounted() {
			this.getInfo()
			this.getDept()
		},
		methods: {
			getChooseName(id) {
				getFiremen(id).then(res => {
					console.log("代班人", res.data);
					let dataInfo = res.data
					this.checkList = dataInfo
					this.form.replaceDutyId = dataInfo.id;
					this.form.replaceDuty = dataInfo.userName;
				})
				// console.log(id, "选择的人");
			},
			// 选择人员
			choose(teamId) {
				this.$tab.navigateTo(`/pages/indexpage/fireMan/tiaoban/choosePerson/choosePerson?teamId=${teamId}`)
			},
			// 跳转审批页面
			gotoShenPi() {
				this.$tab.navigateTo('/pages/indexpage/fireMan/shenpi/shenpi')
			},
			// 获取用户信息 判断是否是消防员
			getInfo() {
				getInfo().then(res => {
					let role = res.data.roles.findIndex(item => item == "firemen")
					if (role == '-1') {
						this.show = false;
					} else {
						this.show = true
						let userId = res.data.user.userId
						// this.userList = res.data.user
						console.log("userId", res.data);
						getFiremenByName(userId).then(res2 => {
							this.userList = res2.data
							console.log("调班人信息", res2);
							this.form.applyTransfer = this.userList.userName
							this.form.applyTransferId = this.userList.id
							this.form.teamName = this.userList.teamName
							this.form.teamId = this.userList.teamId
						})
					}
					// let role = res.data.roles.findIndex(item => item == "firemen")

					// console.log("调班人信息", res);
				})
			},
			// 代办人：滑动按钮点击功能
			bindClick(e) {
				console.log(e);
				setTimeout(() => {
					this.checkList.splice(e.index, 1);
					uni.showToast({
						title: "删除成功",
						icon: 'success'
					});
				}, 200)
			},
			// 获取消防站人员
			getDept() {
				listFiremen().then(res => {
					this.personList = res.rows;
					this.treeData = this.arrConversion(this.personList);
				})
			},
			// 添加排班
			addTiaoBan() {
				// 代办人信息
				// this.checkList.map((item, index) => {
				// 	this.form.replaceDutyId = item.personid;
				// 	this.form.replaceDuty = item.userName;
				// })
				this.$refs.form.validate().then((res) => {
					if (this.form.replaceDutyId == null) {
						this.$modal.msg('请选择代班人');
					} else {
						addTransferInfo(this.form).then(res => {
							if (res.code === 200) {
								this.$modal.msgSuccess("申请成功");
								setTimeout(() => {
									this.$tab.navigateTo('/pages/indexpage/fireMan/shenpi/shenpi')
								}, 800)
							}

						})
					}

				}).catch(err => {
					this.$modal.msg('请填写完整');
				})

				// }).catch(err => {
				// 	// console.log('表单错误信息：', err);
				// 	uni.showToast({
				// 		title: `有未填写信息`
				// 	});
				// });



			},
			gotoShenPi() {
				this.$tab.navigateTo('/pages/indexpage/fireMan/shenpi/shenpi')
			},
			// 一维数组变为三维数组
			arrConversion(arr) {
				let keys = Object.keys(arr[0])
				let level1 = 'secUnitName' //获取一级属性名称
				let level2 = 'plantName' //获取二级属性名称
				let list = Array.from(new Set(
					arr.map(item => {
						return item[level1]
					})))
				let subList = []
				list.forEach(res => {
					arr.forEach((ele, index) => {
						if (ele[level1] === res) {
							let nameArr = subList.map(item => item.label)
							// console.log(nameArr)
							if (nameArr.indexOf(res) !== -1) {
								let nameArr2 = subList[nameArr.indexOf(res)].children.map(item => item
									.label)
								if (nameArr2.indexOf(ele[level2]) !== -1) {
									subList[nameArr.indexOf(res)].children[nameArr2.indexOf(ele[level2])]
										.children.push({
											...ele
										})
								} else {
									subList[nameArr.indexOf(res)].children.push({
										label: ele[level2],
										checked: false,
										// id: (nameArr.indexOf(res) + 2) + "-" + (nameArr.indexOf(
										// 	res) + 2),
										children: [{
											...ele,
											checked: false,
										}]
									})
								}
							} else {
								subList.push({
									label: res,
									checked: false,
									children: [{
										label: ele[level2],
										checked: false,
										// id: (nameArr.indexOf(res) + 2) + "-" + (nameArr
										// 	.indexOf(
										// 		res) + 2),
										children: [{
											...ele,
											checked: false,
										}]
									}]
								})
							}
						}
					})

				})
				subList.forEach((item, index) => {

					this.$set(item, "id", index + 1)
					item.children.forEach((item2, index2) => {
						this.$set(item2, "id", (index + 1) + "-" + (index2 + 1))
						item2.children.map((item3, index3) => {
							this.$set(item3, "personid", item3.id)
							this.$set(item3, "id", (index + 1) + "-" + (index2 + 1) + "-" + (
								index3 +
								1));
							this.$set(item3, "label", item3.userName)
						})
					})
				})
				return subList
			},
			// 以下是插件方法
			openTree: function() {
				this.$refs.nextTreeAsyncRef.showTree = true
			},
			changeVerify: function(current, chooseList) {
				// 注意：返回非空字符串会阻止原有行为，并提示返回的字符串
				// 如果函数体不做return返回值，即验证通过，控件正常处理业务
				console.log('当前变化的数据', current)
				console.log('已选择的数据', chooseList)
				if (chooseList && chooseList.length > 1) {

					return '最多可以选择1个代班人员'
				}
			},
			checkedFunc: function(id) {
				if (this.activeId === id) {
					this.activeId = '';
					this.$refs.nextTreeRef.checkedFunc(id, false)
				} else {
					this.activeId = id;
					this.$refs.nextTreeRef.checkedFunc(id)
				}
			},
			loadData(nodeItem) {
				// 同步实现的代码处理方式 可以返回单个子节点的集合也可以返回子孙节点的集合
				// 如果期望子集节点中还存在孙子节点可以打开，请在初始化数据的时候，初始化个空数组的子节点配置值{[this.childrenKey]: []}

				// if(nodeItem && this.localData[nodeItem.id]) {
				//  return this.localData[nodeItem.id]
				// } else {
				//  return []
				// }
				// 异步的代码实现方式 可以返回单个子节点的集合也可以返回子孙节点的集合
				// 如果期望子集节点中还存在孙子节点可以打开，请在初始化数据的时候，初始化个空数组的子节点配置值{[this.childrenKey]: []}
				return new Promise((resolve, reject) => {
					setTimeout(() => {
						if (nodeItem && self.localData[nodeItem.id]) {
							return resolve(self.localData[nodeItem.id])
						} else {
							return resolve([])
						}
					}, 1000)
				})
			},
			getTitle: function(checked) {
				return `已选：${checked.length}项`
			},
			echoDefault: function() {
				const selectIds = ['2-1', '3-3-35']
				this.checkedTreeData(this.treeData, selectIds)
				console.log('treeData的数据：', this.treeData)
				this.multiple = true
				this.$refs.nextTreeRef.showTree = true
			},
			itemclick: function(_multiple, _selectParent, _checkStrictly = false) {
				this.multiple = _multiple
				this.selectParent = _selectParent
				this.checkStrictly = _checkStrictly
				this.$refs.nextTreeRef.showTree = true
			},
			checkedTreeData: function(treeData, selectIds) {
				// 注意 vue2当数据深嵌套时，如果没有在treeData里面初始化checked属性，那在改变数据的时候直接将checked属性赋值为true，这时候ui界面有可能不会更新，
				// 这时候建议使用this.$set去更新checked属性值，或者在初始化this.treeData的时候初始化checked属性
				(treeData || []).map(item => {
					if (selectIds.indexOf(item.id) !== -1) {
						item.checked = true
					} else {
						item.checked = false
					}
					if (item.children && item.children.length) {
						this.checkedTreeData(item.children, selectIds)
					}
				})
			},
			onconfirm: function(list) {
				console.log('选中项的数量列表list：', list)
				// this.checkList.push(list)
				this.checkList = list
			},
			oncancel: function() {
				// 清除treeData的选中状态
				this.checkedTreeData(this.treeData, [])
			}
		}
	}
</script>

<style lang="scss">
	page {
		box-sizing: border-box;
		padding: 24rpx;
		background-color: #eff0f4;

		/deep/.uni-easyinput__content {
			background-color: #fff;
		}

		/deep/.none .button-group--right {
			display: none;
		}

		/deep/.is-input-border {
			border: none;
		}

		/deep/.uni-swipe {
			background-color: #fff;
			padding: 28rpx 0 28rpx 20rpx;
		}

		/deep/.uni-card {
			border-radius: 10rpx;
		}

		/deep/.u-list {
			height: 0 !important;
		}

		/deep/.u-row {
			margin-bottom: 10rpx;
			padding: 10rpx 30rpx;
			border-radius: 10rpx;
			display: flex;
			justify-content: space-between !important;
			background-color: #f9fbfc;

			:first-child {
				color: black;
			}
		}

		/deep/.uni-date-x--border {
			border-top: none;
			border-right: none;
			border-left: none;
			padding: 15rpx;
			border-radius: 0;
		}

		/deep/.uniui-calendar {

			color: #454545;
			font-weight: 500;
			font-size: 28rpx;
		}

		/deep/.uniui-calendar:before {
			content: none;
		}

		/deep/.input1 .uniui-calendar :before {
			content: '开始日期';
		}

		/deep/.input2 .uniui-calendar :before {
			content: '结束日期';
		}

		/deep/.uni-icons {
			color: #171819 !important;
			font-size: 30rpx !important;
		}

		/deep/.uni-date__x-input {
			padding-left: 50rpx;
		}

		// /deep/.uni-swipe {
		// 	padding: 28rpx 0 28rpx 24rpx;
		// }

		.paibanCard {
			margin-bottom: 15rpx;

			.title {
				color: grey;
				margin-bottom: 15rpx;
				font-size: 24rpx
			}

			.pickTime {
				background-color: #fff;
				border-radius: 10rpx;
			}

			.pickPerson {
				background-color: #fff;
				border-radius: 10rpx;
				display: flex;
				align-items: center;
				padding: 15rpx;
				justify-content: space-between;
				// margin-bottom: 15rpx;
			}

			.picktitle {
				color: #171819;
				font-size: 30rpx;
			}
		}

		.addPaiBan {
			width: 85%;
			background: linear-gradient(0deg, #2A86FF, #8FBCFF);
			font-weight: 400;
			font-size: 36rpx;
			color: #FFFFFF;
			line-height: 38rpx;
			text-align: center;
			padding: 20rpx;
			border-radius: 40rpx;
			margin: 50rpx auto;
		}
	}
</style>