<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">
				<view class="main">
					<u-checkbox-group :value="checkedForId" placement="column" @change="handleCheckboxAllResult" @onchange="handleCheckboxCurr">
						<uni-collapse accordion ref="collapse" @change="handleOpenOrgCollapse" :value="currExpand">
							<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'}" v-for="(item, index) in selfDepartmentUsers" :key="index" :label="item.NAME" :name="item.USER_ID||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 {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendRule,
		initFilter,
		initFilterGroup
	} from '../../../utils/common'
	import {
		getDepartmentLists
	} from '../../../services/app'
	import {
		getUserLists,
		getUserOrDepInfo,
		getSubUserLists
	} from '../../../services/common'

	export default {
		props: {
			show: {
				type: Boolean,
				default: false,
				required: true
			},
			defaultChecked: {
				type: Array,
				default () {
					return []
				}
			},
			depId: {
				type: String,
				default () {
					return ''
				},

			}
		},
		data() {
			return {
				subKey: 1,
				showComponent: false,
				currExpand: 'dep',
				orgTree: [],
				checkedUsersInfoLocal: [], // 按本部门选择结果
				checkedByAll: [], // 所有选择结果

				dataByOrg: [], // orgTree副本
				showPopup: false,
				searchResult: [], // 查询结果列表
				selfDepartmentUsers: [], // 本部门人员列表
			}
		},
		methods: {
			onOpen() {
				this.handleSearchUser(null, {
					ID: this.depId
				})
			},
			handleSearchUser(userVal, depVal) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME")
				extendInclude(json, "Nav_Person.Nav_Post")
				extendRule(json, 'ENABLE_STATUS', 1, '0')
				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
				getUserLists(json).then(res => {
					if (res.IsSuccessful) {
						let arr = []
						arr = res.Data.filter((item) => {
							return !this.defaultChecked.some((item1) => item.ID === item1.USER_ID)
						})
						if (arr.length == 0) {
							this.selfDepartmentUsers = this.defaultChecked
							this.selfDepartmentUsers = this.selfDepartmentUsers
						} else {
							this.selfDepartmentUsers = res.Data
							this.selfDepartmentUsers.map(item=>{
								arr.map(item1=>{
									if(item.ID==item1.USER_ID){
										item.IS_DELETED = true
									}
								})
							})
							this.selfDepartmentUsers = this.selfDepartmentUsers
						}
						this.checkedByAll = this.defaultChecked.filter(i => i.NAME !== '')
					}
				})
				
			},
			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.checkedByAll=[]
				this.selfDepartmentUsers = []
				this.$emit('close', false)
				return
			},
			async handleOpenOrgCollapse(e) {
				if (e === 'org') {
					this.currExpand = 'org'
					if (!this.orgTree.length) {
						await this.handleGetOrg()
					}
				} else {
					this.currExpand = e
				}
			},
			handleCheckboxAllResult(e) {
			},
			handleCheckboxCurr(e) {
				if (e.checked) {
					this.checkedByAll.push({
						NAME: e.name,
						IS_DELETED: false,
						USER_ID: e.id,
						// Nav_User: {
						// 	NAME: e.name
						// }
					})
				} else {
					this.checkedByAll.forEach(item => {
						if (item.USER_ID == e.id || item.NAME == e.name) {
							item.IS_DELETED = !e.checked
						}

					})
					this.checkedByAll = this.checkedByAll
					this.selfDepartmentUsers.map((item, index) => {
						if (item.ID == e.id) {
							item.IS_DELETED = !e.checked
						}
					})
					this.selfDepartmentUsers = this.selfDepartmentUsers
				}

			},

			onOpenPopup() {},
			okPopup() {
				this.showPopup = false
				this.$forceUpdate()
			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleCloseComponet() {
				this.checkedByAll=[]
				this.selfDepartmentUsers = []
				this.$emit('close', !this.showComponent)
			}
		},
		computed: {
			checkedForId() {
				const res = this.checkedByAll
					.filter(i => !i.IS_DELETED)
					.map(o => o.USER_ID)
				return res
			},
			checkedForIdLen() {
				const res = this.checkedByAll
					.filter(i => !i.IS_DELETED && i.NAME !== '')
					.map(o => o.USER_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>