<template>
	<view class="people-selector">
		<u-popup
			:show="showComponent"
			:round="10"
			mode="bottom"
			:closeable="true"
			:customStyle="{paddingTop: '40px'}"
			@open="onOpen"
			@close="handleCloseComponet">
			<u-list
				:pagingEnabled="true"
			>
				<uni-search-bar
					class="search-bar"
					radius="100"
					placeholder="搜索"
					@confirm="manualSearch"
					@cancel="cancelSearch"
					@clear="clearSearch"
				></uni-search-bar>
				<view class="main">
					<uni-card v-if="!!searchResult.length" margin="0" spacing="0" padding="8" style="margin-bottom: 16px">
						<view>搜索结果</view>
						<u-checkbox-group
							:value="checkedSearchResult"
							placement="column"
							@change="handleCheckboxSearchResult"
						>
							<u-checkbox
								:customStyle="{marginBottom: '18px'}"
								v-for="(item, index) in searchResult"
								:key="index"
								:label="item.NAME"
								:name="item.ID"
							>
							</u-checkbox>
						</u-checkbox-group>
					</uni-card>
					<u-collapse
						:border="false"
						accordion
						ref="collapseRef"
						@open="handleOpenOrgCollapse"
						:value="currExpand">
						<uni-card margin="0" spacing="0" padding="0" style="margin-bottom: 16px">
							<u-collapse-item
								title="按组织架构选择"
								name="org"
								:duration="0"
								icon="/static/ic_org@2x.png"
							>
								<!--						@open="handleOpenDepCollapse"-->
								<!--						<text slot="icon"></text>-->
								<!--						<view>面包屑/导航</view>-->
								<view class="department">
									<each-department
										:level="1"
										:lists="orgTree"
										:checkboxValueAll="checkedAllForObj"
										@check="handleCheckValue"
										@expand="handleExpandOrg"></each-department>
								</view>
								<view class="user-list"></view>
							</u-collapse-item>
						</uni-card>
						<uni-card margin="0" spacing="0" padding="0">
							<u-collapse-item
								title="本部门选择"
								icon="/static/ic_cur_dep@2x.png"
								:duration="0"
								name="dep"
							>
								<u-checkbox-group
									:value="allLocal"
									placement="column"
									@change="checkboxAllLocal"
								>
									<u-checkbox
										:customStyle="{marginBottom: '18px'}"
										label="全选"
										name="all"
									>
									</u-checkbox>
								</u-checkbox-group>
								<u-checkbox-group
									:value="selectedSelfDepartment"
									placement="column"
									@change="checkboxChange"
								>
									<u-checkbox
										:customStyle="{marginBottom: '18px'}"
										v-for="(item, index) in selfDepartmentUsers"
										:key="index"
										:label="item.NAME"
										:name="item.ID"
									>
									</u-checkbox>
								</u-checkbox-group>
							</u-collapse-item>
						</uni-card>
					</u-collapse>
				</view>
				<view class="bottom-show">
					<view class="user-names" @click="showPopup = true">
						<view class="names">
							已选中：<text v-for="o in (checkedUsersInfo.concat(checkedDepsInfo, checkedUsersInfoLocal))">{{o.NAME}}、</text>
						</view>
						<u-icon
							class="expand-icon"
							style="margin-left: 8px;"
							color="#3b9dff"
							name="arrow-up"
						></u-icon>
					</view>
					<view class="handle-btn">
						<u-button
							@click="handleOkChecked"
							type="primary">
							确认({{checkedUsersInfo.length + checkedDepsInfo.length + checkedUsersInfoLocal.length}})
						</u-button>
					</view>
				</view>
				<u-popup
					:show="showPopup"
					:round="10"
					mode="bottom"
					@open="onOpenPopup"
					@close="handleClosePopup">
					<view class="popup-content">
						<view class="head">
							<view class="num">已选中({{checkedUsersInfo.length + checkedDepsInfo.length + checkedUsersInfoLocal.length}})</view>
							<view class="ok" @click="okPopup">确认</view>
						</view>
						<view class="body">
							<view class="list" v-for="n in (checkedUsersInfo.concat(checkedDepsInfo, checkedUsersInfoLocal))" :key="n.ID">
								<view class="n">{{n.NAME}}</view>
								<view class="d" @click="removeChecked(n)">移除</view>
							</view>
						</view>
					</view>
				</u-popup>
			</u-list>
		</u-popup>
	</view>
</template>

<script>
import UButton from '../../../uni_modules/uview-ui/components/u-button/u-button.vue'
import EachDepartment from './each-department-old.vue'

import {
	extendFilterGroup,
	extendGroupRule,
	extendInclude,
	extendRule,
	initFilter,
	initFilterGroup
} from '../../../utils/common'
import { getDepartmentLists } from '../../../services/app'
import { getUserLists, getUserOrDepInfo } from '../../../services/common'

export default {
	components: { UButton, EachDepartment },
	props: {
		show: {
			type: Boolean,
			default: false,
			required: true
		}
	},
	data() {
		return {
			showComponent: false,
			currExpand: 'dep',
			orgTree: [],
			showPopup: false,
			// selectedSelfDepartment: [],
			// checkedSearchResult: [],
			allLocal: [],
			searchResult: [],
			selfDepartmentUsers: [],
			checkedAllForObj: {},
			checkedAllInfo: [],
			checkedUsersInfoLocal: [],
			checkedUsersInfo: [],
			checkedDepsInfo: [],
		}
	},
	methods: {
		onOpen() {
			const appInfoData = uni.getStorageSync('appInfo')
			const departmentId = appInfoData?.User?.DEPARTMENT_ID || ''
			this.handleSearchUser(null, {ID: departmentId})
		},
		async manualSearch(e) {
			const orgId = uni.getStorageSync('orgId')
			const json = initFilter(orgId, "", "NAME")
			extendInclude(json, "Nav_Person.Nav_Post")
			extendRule(json, 'ENABLE_STATUS', 1, '0')
			const tempGroup = initFilterGroup(false);
			extendGroupRule(tempGroup, 'NAME', 9, e.value)
			extendFilterGroup(json, tempGroup)
			getUserLists(json).then(res => {
				if (res.IsSuccessful) {
					this.searchResult = res.Data
				}
			})
		},
		cancelSearch() {
			this.searchResult = []
		},
		clearSearch() {
			this.searchResult = []
		},
		handleSearchUser(userVal, depVal) {
			const appInfoData = uni.getStorageSync('appInfo')
			const departmentId = appInfoData?.User?.DEPARTMENT_ID || ''
			const orgId = uni.getStorageSync('orgId')
			const json = initFilter(orgId, "", "NAME")
			extendInclude(json, "Nav_Person.Nav_Post")
			extendRule(json, 'ENABLE_STATUS', 1, '0')
			if (depVal) {
				extendRule(json, 'DEPARTMENT_ID', 1, depVal.ID)
			}
			const tempGroup = initFilterGroup(false)
			if (userVal) {
				extendGroupRule(tempGroup, 'NAME', 9, userVal.NAME)
			}
			extendFilterGroup(json, tempGroup)
			json.Limit = 100
			const that = this
			async function findAndAddUser(arr) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i].ID === depVal.ID) {
						if (!arr[i].users) {
							await getUserLists(json).then(res => {
								if (res.IsSuccessful) {
									arr[i].users = res.Data
									that.$nextTick(() => {
										that.$refs.collapseRef.init()
									})
								}
							})
						}
					} else if (arr[i].users) {
						findAndAddUser(arr[i].departments);
					}
				}
			}

			if (depVal.ID === departmentId) {
				getUserLists(json).then(res => {
					if (res.IsSuccessful) {
						this.selfDepartmentUsers = res.Data
						this.$nextTick(() => {
							this.$refs.collapseRef.init()
						})
					}
				})
			} else {
				findAndAddUser(this.orgTree)
			}
		},
		handleExpandOrg(val) {
			this.$nextTick(() => {
				setTimeout(() => {
					this.$refs.collapseRef.init()
				}, 200)
			})
			this.handleGetOrg(val.ID)
			this.handleSearchUser(null, val)
		},
		handleGetOrg(id) {
			const orgId = uni.getStorageSync('orgId')
			const json = initFilter(orgId, "", "NAME")
			extendRule(json, 'PARENT_ID', 1, id || null)
			// const tempGroup = initFilterGroup(false)
			// if (val) {
			// 	extendGroupRule(tempGroup, 'NAME', 9, val)
			// }
			// extendFilterGroup(json, tempGroup)
			json.Limit = 100

			let that = this
			async function findAndAddDep(arr) {
				if (!id) {
					await getDepartmentLists(json).then(res => {
						if (res.IsSuccessful) {
							that.orgTree = res.Data
							// findAndAddDep(res.Data);
							that.$nextTick(() => {
								that.$refs.collapseRef.init()
							})
						}
					})
				}

				for (let i = 0; i < arr.length; i++) {
					if (arr[i].ID === id) {
						if (!arr[i].isExpand) {
							arr[i].isExpand = true
						} else {
							arr[i].isExpand = false
						}
						if (!arr[i].departments) {
							await getDepartmentLists(json).then(res => {
								if (res.IsSuccessful) {
									arr[i].departments = res.Data
									that.$nextTick(() => {
										that.$refs.collapseRef.init()
									})
								}
							})
						}
					} else if (arr[i].departments) {
						findAndAddDep(arr[i].departments);
					}
				}
			}
			findAndAddDep(this.orgTree)
		},
		handleCheckValue(ob) {
			this.checkedAllForObj = {...this.checkedAllForObj, ...ob}
			const c = Object.keys(this.checkedAllForObj).filter(r => r != 0)
			const d = c.reduce((a, b) => [...a, ...this.checkedAllForObj[b]], [])
			const k = d.reduce((a, b) => { return [...a, b]}, [])

			const checkedAllInfoArr = []
			const checkedUsersInfoArr = []
			const checkedDepsInfoArr = []
			function findObjectsWithBValue(obj) {
				if (Array.isArray(obj)) {
					obj.forEach(findObjectsWithBValue);
					return;
				}
				if (typeof obj === 'object' && obj !== null) {
					if (obj.ID && k.includes(obj.ID)) {
						if (obj.DEPARTMENT_ID) {
							checkedUsersInfoArr.push(obj)
						} else {
							checkedDepsInfoArr.push(obj)
						}
						checkedAllInfoArr.push(obj)
					}
					Object.values(obj).forEach(findObjectsWithBValue);
					return;
				}
			}
			findObjectsWithBValue(this.orgTree)

			this.checkedAllInfo = checkedAllInfoArr
			this.checkedDepsInfo = checkedDepsInfoArr

			this.checkedUsersInfo = checkedUsersInfoArr
		},
		async handleOkChecked() {
			const orgId = uni.getStorageSync('orgId')
			const userIds = this.checkedUsersInfo.map(i => i.ID)
			const userIdsLocal = this.checkedUsersInfoLocal.map(i => i.ID)
			const departmentIds = this.checkedDepsInfo.map(i => i.ID)
			const params = {
				UserIds: userIds.concat(userIdsLocal),
				DepartmentIds: departmentIds,
				OrgId: orgId
			}
			await getUserOrDepInfo(params).then(res => {
				if (res.IsSuccessful) {
					const data = res.Data
					const userAndDepartment = {
						allIds: userIds.concat(userIdsLocal, departmentIds),
						userIds: userIds.concat(userIdsLocal),
						departmentIds: departmentIds,
						allUserIdWithName: data,
						allUserInfos: this.checkedUsersInfoLocal.concat(this.checkedUsersInfo),
						allDepartmentInfos: this.checkedDepsInfo,
						allInfos: this.checkedUsersInfoLocal.concat(this.checkedUsersInfo, this.checkedDepsInfo)
					}
					this.$emit('select', data)
					this.$emit('close', false)
					// this.$store.commit('updateUserAndDepartment', userAndDepartment)
					// uni.navigateBack(-1)
				}
			})
		},
		async handleChangeCollapse() {
			this.handleGetOrg()
		},
		async handleOpenOrgCollapse(e) {
			if (e === 'org') {
				this.currExpand = 'org'
				if (!this.orgTree.length) {
					await this.handleGetOrg()
				}
			}
		},
		async handleOpenDepCollapse(e) {
			if (e === 'org') {
				await this.handleGetOrg()
			}
		},
		checkboxAllLocal(e) {
			if (e[0] === 'all') {
				this.checkedUsersInfoLocal = this.selfDepartmentUsers
			} else {
				this.checkedUsersInfoLocal = []
			}
		},
		handleCheckboxSearchResult(e) {
			if (!this.checkedAllForObj['0']) {
				this.checkedAllForObj['0'] = []
			}
			this.checkedAllForObj['0'].concat(e)
			// this.checkedAllInfo.push(this.searchResult)
			// this.checkedUsersInfo.push(this.searchResult)
			// this.checkedDepsInfo.push(this.searchResult)
			// TODO: 勾选搜索结果人员，无法联动到组织或本部门
			this.checkedUsersInfoLocal = this.checkedUsersInfoLocal.concat(this.searchResult)
		},
		checkboxChange(e) {
			const userInfoArr = []
			this.selfDepartmentUsers.forEach(item => {
				if (e.includes(item.ID)) {
					userInfoArr.push(item)
				}
			})

			// 取消选择的
			const deleted = []; // ['']
			(this.checkedAllForObj['0'] || []).forEach(a => {
				if (!(e.includes(a))) {
					// a已删除
					deleted.push(a)
				}
			})
			// 新增选择的
			const addTo = []; // [{}]
			userInfoArr.forEach(a => {
				if (!((this.checkedAllForObj['0'] || []).includes(a.ID))) {
					// 新增a
					addTo.push(a)
				}
			})

			const afterDelete = []
			this.checkedUsersInfoLocal.forEach(item => {
				if (!(deleted.includes(item.ID))) {
					// 返回不含删除的
					afterDelete.push(item)
				}
			})
			// 去新增 addTo
			const newCheckedUserInfoArr = afterDelete.concat(addTo)
			this.checkedUsersInfoLocal = newCheckedUserInfoArr
			this.checkedAllForObj['0'] = e
		},
		removeChecked(value) {
			if (value.DEPARTMENT_ID) {
				// 移除人员(含信息)
				const removeAfterUserLocal = this.checkedUsersInfoLocal.filter(item => item.ID !== value.ID)
				const removeAfterUser = this.checkedUsersInfo.filter(item => item.ID !== value.ID)
				this.checkedUsersInfoLocal = removeAfterUserLocal
				this.checkedUsersInfo = removeAfterUser

			} else {
				const removeAfterDep = this.checkedDepsInfo.filter(item => item.ID !== value.ID)
				this.checkedDepsInfo = removeAfterDep
			}
			// 移除(ID)
			Object.keys(this.checkedAllForObj).forEach(i => {
				this.checkedAllForObj[i].forEach((o, k) => {
					if (value.ID === o) {
						this.checkedAllForObj[i].splice(k, 1)
					}
				})
			})
			this.$forceUpdate()
		},
		onOpenPopup() {

		},
		okPopup() {
			this.showPopup = false
			this.$forceUpdate()
		},
		handleClosePopup() {
			this.showPopup = false
		},
		handleCloseComponet() {
			this.$emit('close', !this.showComponent)
		}
	},
	computed: {
		// ...mapState({
		//	 username: state => state.homeModule.username,
		//	 age: state => state.homeModule.age
		// })
		selectedSelfDepartment() {
			return this.checkedUsersInfoLocal.map(i => i.ID)
		},
		checkedSearchResult() {
			const a = Object.keys(this.checkedAllForObj).map(i => this.checkedAllForObj[i])
			let c = []
			a.forEach(i => {c = c.concat(i)})
			return c
		},
	},
	watch: {
		show(n) {
			this.showComponent = this.show
		}
	}
}
</script>

<style scoped>
.people-selector {
	/*height: 100vh;*/
}
.people-selector .main {
	padding: 6px 16px 70px;
}
.bottom-show {
	height: 62px;
	border-top: 1px solid #C9C9C9;
	display: flex;
	align-items: center;
	position: fixed;
	width: 100%;
	bottom: 0;
	left: 0;
	padding: 0 16px;
	box-sizing: border-box;
	z-index: 10;
	justify-content: space-between;
	background: #fff;
}
.user-names {
	color: #3b9dff;
	font-size: 14px;
	line-height: 18px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	flex: 1;
	width: calc(100% - 112px - 25px);
	padding-right: 25px;
}
.user-names .names {
	/*width: 184px;*/
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	flex: 1;
}
.user-names .expand-icon {
	width: 16px;
	height: 16px;
}
.handle-btn {
	/*background: #fff;*/
}
.popup-content {
	height: 400px;
}
.popup-content .head {
	height: 50px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-bottom: 1px solid #C9C9C9;
	padding: 0 16px;
	font-size: 14px;
}
.popup-content .head .num {
	color: #333333;
}
.popup-content .head .ok {
	color: #3b9dff;
}
.popup-content .body {
	padding: 16px;
	height: 350px;
	overflow-y: auto;
}
.popup-content .body .list {
	display: flex;
	justify-content: space-between;
	margin-bottom: 16px;
	font-size: 14px;
	color: #333333;
	line-height: 18px;
}
.popup-content .body .list .d {
	width: 32px;
	height: 18px;
	line-height: 18px;
	border: 1px solid #c9c9c9;
	border-radius: 4px;
	color: #999999;
	font-size: 10px;
	text-align: center;
}
</style>
