<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">
					<u-checkbox-group :value="checkedForId" placement="column" @change="handleCheckboxAllResult" @onchange="handleCheckboxCurr">
						<uni-card v-if="!!searchResult.length" margin="0" spacing="0" padding="8" style="margin-bottom: 16px">
							<view class="search-title">搜索结果</view>
							<u-checkbox :customStyle="{marginBottom: '18px'}" v-for="(item, index) in searchResult" :key="index" :label="item.NAME" :name="item.ID">
							</u-checkbox>
						</uni-card>
						<uni-collapse accordion ref="collapse" @change="handleOpenOrgCollapse" :value="currExpand">
							<uni-card margin="0" spacing="0" padding="0" style="margin-bottom: 16px">
								<uni-collapse-item title="按组织架构选择" name="org" thumb="/static/ic_org@2x.png" :border="false" :style="currExpand === 'org' ? {marginBottom: '16px'} : {}">
									<!--						@open="handleOpenDepCollapse"-->
									<!--						<text slot="icon"></text>-->
									<!--						<view>面包屑/导航</view>-->
									<view class="department">
										<each-department :level="1" :key="subKey" :lists="orgTree" @expand="handleExpandOrg"></each-department>
									</view>
									<view class="user-list"></view>
								</uni-collapse-item>
							</uni-card>
							<uni-card margin="0" spacing="0" padding="0">
								<uni-collapse-item title="本部门选择" thumb="/static/ic_cur_dep@2x.png" name="dep">
									<view class="self">
										<u-checkbox :customStyle="{marginBottom: '18px'}" label="全选" name="all">
										</u-checkbox>
										<u-checkbox :customStyle="{marginBottom: '18px'}" v-for="(item, index) in selfDepartmentUsers" :key="index" :label="item.NAME" :name="item.ID">
										</u-checkbox>
									</view>
								</uni-collapse-item>
							</uni-card>
						</uni-collapse>
					</u-checkbox-group>
				</view>
			</u-list>
			<view class="bottom-show">
				<view class="user-names" @click="showPopup = true">
					<view class="names">
						已选中：<text v-for="o in checkedByAll.filter(i => !i.IS_DELETED && i.USER_ID!=='all'&&i.NAME!=='')">{{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">
						确认({{checkedForIdLen.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">已选中({{checkedForIdLen.length}})</view>
						<view class="ok" @click="okPopup">确认</view>
					</view>
					<view class="body">
						<view class="list" v-for="n in checkedByAll.filter(i => !i.IS_DELETED && i.USER_ID!=='all' &&i.NAME!=='')" :key="n.ID">
							<view class="n">{{n.NAME}}</view>
							<view class="d" @click="removeChecked(n)">移除</view>
						</view>
					</view>
				</view>
			</u-popup>
		</u-popup>
	</view>
</template>

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

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

	export default {
		components: {
			UButton,
			EachDepartment
		},
		props: {
			show: {
				type: Boolean,
				default: false,
				required: true
			},
			defaultChecked: {
				type: Array,
				default () {
					return []
				}
			}
		},
		data() {
			return {
				subKey: 1,
				showComponent: false,
				currExpand: 'dep',
				orgTree: [],


				checkedUsersInfoLocal: [], // 按本部门选择结果
				checkedByAll: [], // 所有选择结果

				dataByOrg: [], // orgTree副本
				showPopup: false,
				searchResult: [], // 查询结果列表
				selfDepartmentUsers: [], // 本部门人员列表
			}
		},
		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)
				getUserListFos(json).then(res => {
					if (res.IsSuccessful) {
						this.searchResult = res.Data
					}
				})
			},
			cancelSearch() {
				this.searchResult = []
			},
			clearSearch() {
				this.searchResult = []
			},
			getSubUsers(did) {
				return new Promise((resolve, reject) => {
					const orgId = uni.getStorageSync('orgId')
					const json = initFilter(orgId, did, "NAME")
					getSubUserLists(json).then(res => {
						if (res.IsSuccessful) {
							resolve(res.Data)
						}
					})
				})
			},
			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 getUserListFos(json).then(res => {
									if (res.IsSuccessful) {
										arr[i].users = res.Data
										that.subKey++
									}
								})
							}

						} else if (arr[i].users) {
							findAndAddUser(arr[i].departments);
						}
					}
				}
				if (depVal.ID === departmentId) {
					// findAndAddUser(this.orgTree)
					getUserListFos(json).then(res => {
						if (res.IsSuccessful) {
							this.selfDepartmentUsers = res.Data
						}
					})
				}
				// else {
				// 	findAndAddUser(this.orgTree)
				// }
				findAndAddUser(this.orgTree)
				let num = 0
				for (let task of this.selfDepartmentUsers) {
					const itemJson = this.defaultChecked.filter(i => !i.IS_DELETED).find((item) => {
						return item.NAME == task.NAME
					})
					if (itemJson) {
						num = num + 1
					}
				}
				this.checkedByAll = this.defaultChecked
				if (num == this.selfDepartmentUsers.length && num !== 0) {
					this.checkedByAll.push({
						NAME: '全选',
						IS_DELETED: false,
						USER_ID: 'all',
					})
				}


			},
			handleExpandOrg(val) {
				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);
							}
						})
					}

					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) {
								that.subKey++

								await getDepartmentLists(json).then(res => {
									if (res.IsSuccessful) {
										arr[i].departments = res.Data
										that.subKey++
									}
								})
							}
						} else if (arr[i].departments) {
							findAndAddDep(arr[i].departments);
						}
						that.subKey++
					}
				}
				findAndAddDep(this.orgTree)
				this.$nextTick(() => {
					setTimeout(() => {
						this.$refs.collapse.resize()
						this.dataByOrg = JSON.parse(JSON.stringify(this.orgTree))
					}, 300)
				})
			},
			async handleOkChecked() {
				const noAll = this.checkedByAll.filter(i => i.USER_ID !== 'all')
				this.$emit('select', noAll)
				this.$emit('close', false)
				return
				// const uids = this.checkedByAll.filter(i => i.DEPARTMENT_ID).map(d => d.ID)
				const uids = this.checkedByAll.filter(i => i.USER_ID).map(d => d.USER_ID)
				// const dids = this.checkedByAll.filter(i => !i.DEPARTMENT_ID).map(d => d.ID)
				const dids = this.checkedByAll.filter(i => i.DEPARTMENT_ID).map(d => d.DEPARTMENT_ID)
				const orgId = uni.getStorageSync('orgId')

				const params = {
					UserIds: uids,
					DepartmentIds: dids,
					OrgId: orgId
				}
				await getUserOrDepInfo(params).then(res => {
					if (res.IsSuccessful) {
						const data = res.Data
						let rdata = []
						this.checkedByAll.forEach(item => {
							rdata = data.map(d => {
								if (d.UserId === item.USER_ID) {
									// d.IS_DELETED = item.IS_DELETED
									// d.NAME = item.NAME
									// d.ID = item.ID
									return {
										...d,
										...item
									}
								} else {
									return {
										...d,
										IS_DELETED: false
									}
								}
							})
						})
						this.$emit('select', rdata)
						this.$emit('close', false)
					}
				})
			},
			async handleChangeCollapse() {
				this.handleGetOrg()
			},
			async handleOpenOrgCollapse(e) {
				if (e === 'org') {
					this.currExpand = 'org'
					if (!this.orgTree.length) {
						await this.handleGetOrg()
					}
				} else {
					this.currExpand = e
				}
			},
			async handleOpenDepCollapse(e) {
				if (e === 'org') {
					await this.handleGetOrg()
				}
			},
			handleCheckboxAllResult(e) {

			},
			handleCheckboxCurr(e) {
				if (e.checked) {
					if (e.id === 'all') {


						this.checkedByAll.push({
							NAME: e.name,
							IS_DELETED: false,
							USER_ID: e.id,
						})
						const arrB = []
						this.selfDepartmentUsers.map((item, index) => {
							arrB.push({
								NAME: item.NAME,
								IS_DELETED: false,
								USER_ID: item.ID,
							})
						})
						const arrayC = this.checkedByAll.filter(item => {
							return !arrB.some(obj => obj.NAME === item.NAME)
						})
						arrB.forEach(item => {
							if (!arrayC.some(obj => obj.NAME === item.NAME)) {
								arrayC.push(item)
							}
						})
						for(let item of arrayC){
							if(!this.checkedByAll.some(t=>t.NAME == item.NAME&&t.IS_DELETED==false)){
								this.checkedByAll.push({
									NAME: item.NAME,
									IS_DELETED: item.IS_DELETED,
									USER_ID: item.USER_ID,
								})
							}
						}
						// arrayC.forEach(item => {
						// 	this.checkedByAll.push({
						// 		NAME: item.NAME,
						// 		IS_DELETED: item.IS_DELETED,
						// 		USER_ID: item.USER_ID,
						// 	})

						// })

						// TODO:
					} else {
						if (e.type === 'dep') {
							this.handleExpandOrg({
								ID: e.id
							})
							this.getSubUsers(e.id).then(res => {
								this.checkedByAll.forEach(a => {
									res.forEach(b => {
										if (a.USER_ID === b.ID) {
											a.IS_DELETED = false
											b.ID = a.ID
										} else {
											b.USER_ID = b.ID
										}
									})
								})
								this.checkedByAll = res.concat(this.checkedByAll)
								// this.checkedByAll.push({
								// 	NAME: e.name,
								// 	IS_DELETED: false,
								// 	DEPARTMENT_ID: e.id,
								// 	// Nav_User: {
								// 	// 	NAME: null
								// 	// }
								// })
							})
						} else {
							this.checkedByAll.push({
								NAME: e.name,
								IS_DELETED: false,
								USER_ID: e.id,
								// Nav_User: {
								// 	NAME: e.name
								// }
							})
						}
					}
				} else {
					if (e.id === 'all') {
						this.checkedByAll.forEach(item => {
							if (item.USER_ID === e.id) {
								item.IS_DELETED = true
							}
						})
						this.selfDepartmentUsers.map((item, index) => {
							this.checkedByAll.forEach(item1 => {
								if (item1.USER_ID === item.ID) {
									item1.IS_DELETED = true
								}
							})
						})

						// TODO:
					} else {
						if (e.type === 'dep') {
							this.handleExpandOrg({
								ID: e.id
							})
							this.checkedByAll.forEach(item => {
								if (item.USER_ID == 'all') {
									item.IS_DELETED = true
								}
								if (item.USER_ID === e.id || item.DEPARTMENT_ID === e.id) {
									item.IS_DELETED = true
								}
							})
						} else {
							this.checkedByAll.forEach(item => {
								if (item.USER_ID == 'all') {
									item.IS_DELETED = true
								}
								if (item.USER_ID === e.id || item.DEPARTMENT_ID === e.id) {

									item.IS_DELETED = true
								}
							})
						}
					}
				}
			},
			removeChecked(value) {
				this.checkedByAll.forEach(item => {
					if (item.USER_ID === value.USER_ID) {
						item.IS_DELETED = true
					}
				})
			},
			onOpenPopup() {},
			okPopup() {
				this.showPopup = false
				this.$forceUpdate()
			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleCloseComponet() {
				this.$emit('close', !this.showComponent)
			}
		},
		computed: {
			checkedForId() {
				const res = this.checkedByAll
					.filter(i => !i.IS_DELETED)
					.map(o => o.USER_ID || o.DEPARTMENT_ID)
				return res
			},
			checkedForIdLen() {
				const res = this.checkedByAll
					.filter(i => !i.IS_DELETED && i.NAME !== '全选' && i.NAME !== '')
					.map(o => o.USER_ID || o.DEPARTMENT_ID)
				return res


			},
		},
		watch: {
			show(n) {
				this.showComponent = this.show
			},
			checkedByAllId: {
				handler() {
					function filterObjectsWithAValue(obj, aVal) {
						if (Array.isArray(obj)) {
							return obj.flatMap(item => filterObjectsWithAValue(item, aVal));
						} else if (typeof obj === 'object' && obj !== null) {
							if (obj.ID === aVal) {
								return [obj];
							} else {
								return Object.values(obj).flatMap(value => filterObjectsWithAValue(value, aVal));
							}
						} else {
							return [];
						}
					}

					const orgList = this.checkedByAllId.reduce((acc, cur) => acc.concat(filterObjectsWithAValue(this.dataByOrg, cur)), []);

					const result = []
					this.searchResult.concat(this.selfDepartmentUsers, orgList).forEach(item => {
						this.checkedByAllId.forEach(id => {
							if (id === item.ID) {
								result.push(item)
							}
						})
					})
					// this.checkedByAll = result
				},
				deep: true
			},
		}
	}
</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;
	}

	.search-title {
		margin-bottom: 10px;
	}

	.department,
	.self {
		padding: 0 16px;
	}
</style>