<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar title="选择员工与部门" />
			
      <view class="container">
        <view class="header">
          <wk-search-box @search="handleToSearch" />
					
          <view class="nav-tree-wrapper">
            <view class="nav-tree">
              <view
                v-for="(item, index) in navTreeList"
                :key="item.id"
                class="nav-tree-item">
                <text
                  :class="{special: index < navLen - 1 }"
                  class="text"
                  @click="handleNavgiateToDept(index)">
                  {{ item.name }}
                </text>
                <text
                  v-if="index < navLen - 1"
                  class="wk wk-arrow-right icon" />
              </view>
            </view>
          </view>
        </view>
				
        <view class="content">
          <!-- <view class="choose-all" @click="toggleCheckedAll">
						<view :class="{active: checkedAll }" class="checkbox">
							<text v-if="checkedAll" class="wk wk-check icon"></text>
						</view>
						全选
					</view> -->
					
          <view v-if="!$isEmpty(dataList.deptList)" class="dept-list">
            <view class="box" />
						
            <view
              v-for="item in dataList.deptList"
              :key="item.deptId"
              class="dept-list-item"
              @click="handleToChild(item)">
              <view
                :class="{active: item.checked }"
                class="checkbox"
                @click.stop="handleChoose(item, 'deptList')">
                <text v-if="item.checked" class="wk wk-check icon" />
              </view>
							
              <image :src="$static('images/icon/structure.png')" class="dept-icon" />
							
              <view class="text">
                {{ item.name }}<text v-if="item.allNum > 0">
                  ({{ item.allNum }}人)
                </text>
              </view>
							
              <text
                :style="{visibility: item.currentNum > 0 ? 'visible' : 'hidden' }"
                class="wk wk-arrow-right more-icon" />
            </view>
          </view>
					
          <template v-if="!$isEmpty(dataList.userList)">
            <view class="user-tips">
              {{ userTips }}
            </view>
						
            <view class="user-list">
              <view
                v-for="item in dataList.userList"
                :key="item.userId"
                class="user-list-item"
                @click="handleChoose(item, 'userList')">
                <view :class="{active: item.checked }" class="checkbox">
                  <text v-if="item.checked" class="wk wk-check icon" />
                </view>
								
                <wk-avatar
                  :avatar="item.img"
                  :name="item.realname"
                  :size="14"
                  :preview="false"
                  class="avatar" />
						
                <view class="text">
                  {{ item.realname }}
                </view>
              </view>
            </view>
          </template>
        </view>
				
        <view class="footer">
          <view class="left" @click="showPopup">
            <view class="total-box">
              <text class="total">
                {{ totalText }}
              </text>
              <text class="wk wk-arrow-right icon" />
            </view>
            <view class="desc">
              （不包含子部门）
            </view>
          </view>
          <view class="confirm-btn" @click="handleConfirm">
            确定
          </view>
        </view>
      </view>
    </view>
		
    <uni-popup
      ref="popup"
      radius="20rpx 20rpx 0 0"
      type="bottom">
      <view class="popup">
        <view class="popup-header">
          <text class="text">
            {{ totalText }}
          </text>
          <text class="confirm-btn" @click="handleConfirm">
            确定
          </text>
        </view>
				
        <view class="popup-content">
          <view class="dept-list">
            <view
              v-for="(item, index) in selectedList.deptList"
              :key="item.deptId"
              class="dept-list-item">
              <image :src="$static('images/icon/structure.png')" class="dept-icon" />
							
              <view class="text">
                {{ item.name }}
              </view>
							
              <view class="remove-btn" @click="handleRemove(index, 'deptList')">
                移除
              </view>
            </view>
          </view>
					
          <template v-if="!$isEmpty(selectedList.userList)">
            <view class="box" />
						
            <view class="user-list">
              <view
                v-for="(item, index) in selectedList.userList"
                :key="item.userId"
                class="user-list-item">
                <wk-avatar
                  :avatar="item.img"
                  :name="item.realname"
                  :size="14"
                  :preview="false"
                  class="avatar" />
									
                <view class="text">
                  {{ item.realname }}
                </view>
								
                <view class="remove-btn" @click="handleRemove(index, 'userList')">
                  移除
                </view>
              </view>
            </view>
          </template>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import { AdminQueryUserListByDept } from 'API/admin.js'
	
  import { mapGetters } from 'vuex'
  import { deepCopy } from '@/utils/lib.js'
  import { isObject } from '@/utils/types.js'
	
  export default {
    name: 'UserAndDept',
    data() {
      return {
        navTreeList: [],
				
        dataList: {
          deptList: [],
          userList: []
        },
        copyList: null,
				
        selectedList: {
          deptList: [],
          userList: []
        },
				
        checkedAll: false,
				
        bridge: {},
        defaultVal: null
      }
    },
    computed: {
			...mapGetters({
				companyInfo: 'user/expirationInfo'
			}),
			
			navLen() {
				// 处理动态增减导航项时小程序无法渲染样式问题
				return this.navTreeList.length
			},
			
			userTips() {
				if (this.$isEmpty(this.navTreeList)) return ''
				return this.navTreeList[this.navTreeList.length - 1].name + '员工'
			},
			
			totalText() {
				const userLen = this.selectedList.userList.length || 0
				const deptLen = this.selectedList.deptList.length || 0
				return `已选择：${userLen}人，${deptLen}个部门`
			}
    },
    watch: {
      companyInfo: {
        handler(val) {
          if (!this.$isEmpty(val)) {
            this.navTreeList = [{
              deptId: 0,
              name: val.companyName
            }]
            this.getUserList()
          }
        },
        deep: true,
        immediate: true
      }
    },
    onLoad() {
      this.bridge = getApp().globalData.selectedValBridge.userAndDept || {}
      const obj = this.bridge.defaultVal || {}

      this.selectedList.deptList = this.$isEmpty(obj.deptList) ? [] : obj.deptList
      this.selectedList.userList = this.$isEmpty(obj.userList) ? [] : obj.userList
    },
    onUnload() {
      getApp().globalData.selectedValBridge = {}
    },
    methods: {
      getUserList(deptId = 0) {
        AdminQueryUserListByDept({
          deptId: deptId
        }).then(res => {
          console.log('rrrrr', res)
          this.dataList = res
          this.getDefaultChecked()
          this.copyList = null
        }).catch(() => {
        })
      },
			
      /**
       * 默认勾选
       */
      getDefaultChecked() {
        const deptIds = (this.selectedList.deptList || []).map(o => o.deptId)
        const userIds = (this.selectedList.userList || []).map(o => o.userId)
				
        this.dataList.deptList.forEach(item => {
          if (deptIds.includes(item.deptId)) {
            this.$set(item, 'checked', true)
          } else {
            this.$set(item, 'checked', false)
          }
        })
        this.dataList.userList.forEach(item => {
          if (userIds.includes(item.userId)) {
            this.$set(item, 'checked', true)
          } else {
            this.$set(item, 'checked', false)
          }
        })
      },
			
      /**
       * 搜索
       * @param {Object} keyworad
       */
      handleToSearch(keyworad) {
        console.log('data: ', keyworad)
        if (!this.copyList) {
          this.copyList = { ...this.dataList }
        }
        if (this.$isEmpty(keyworad)) {
          this.dataList = { ...this.copyList }
          this.copyList = null
          return
        }
        this.dataList = {
          userList: this.copyList.userList.filter(o => o.realname.includes(keyworad)),
          deptList: this.copyList.deptList.filter(o => o.name.includes(keyworad)),
        }
      },
			
      /**
       * 切换全选状态
       */
      // toggleCheckedAll() {
      // 	this.checkedAll = !this.checkedAll
      // 	this.dataList.userList.forEach(o => {
      // 		this.$set(o, 'checked', this.checkedAll)
      // 	})
      // 	this.dataList.deptList.forEach(o => {
      // 		this.$set(o, 'checked', this.checkedAll)
      // 	})
      // 	if (this.checkedAll) {
      // 		this.$set(this.selectedList, 'userList', [...this.dataList.userList])
      // 		this.$set(this.selectedList, 'deptList', [...this.dataList.deptList])
      // 	} else {
      // 		this.$set(this.selectedList, 'userList', [])
      // 		this.$set(this.selectedList, 'deptList', [])
      // 	}
      // },
			
      /**
       * 跳转到子部门
       * @param {Object} item
       */
      handleToChild(item) {
        console.log('to child', item)
        if (item.currentNum > 0) {
          this.getUserList(item.deptId)
          this.navTreeList.push({
            deptId: item.deptId,
            name: item.name
          })
        } else {
          this.handleChoose(item, 'deptList')
        }
      },
			
      /**
       * 导航切换部门
       * @param {Object} index
       */
      handleNavgiateToDept(index) {
        if (index >= this.navTreeList.length - 1) return

        const item = this.navTreeList[index]
        this.getUserList(item.deptId)
        this.navTreeList.splice(index + 1)
      },
			
      /**
       * 切换选中
       * @param {Object} item
       * @param {Object} type
       */
      handleChoose(item, type) {
        this.$set(item, 'checked', !item.checked)
				
        if (item.checked) {
          // 勾选
          if (type === 'userList') {
            this.selectedList.userList.push(item)
          } else if (type === 'deptList') {
            this.selectedList.deptList.push(item)
          }
        } else {
          // 取消勾选
          let findIndex = -1
          if (type === 'userList') {
            findIndex = this.selectedList.userList.findIndex(o => o.userId === item.userId)
            if (findIndex !== -1) {
              this.checkedAll = false
              this.selectedList.userList.splice(findIndex, 1)
            }
          } else if (type === 'deptList') {
            findIndex = this.selectedList.deptList.findIndex(o => o.deptId === item.deptId)
            if (findIndex !== -1) {
              this.checkedAll = false
              this.selectedList.deptList.splice(findIndex, 1)
            }
          }
        }
      },
			
      /**
       * 移除
       * @param {Object} index
       * @param {Object} type
       */
      handleRemove(index, type) {
        this.checkedAll = false
        const delItem = this.selectedList[type].splice(index, 1)[0]
        this.$set(delItem, 'checked', false)
        // console.log('remove---', this.selectedList)
      },
			
      showPopup() {
        this.$refs.popup.open()
      },
			
      /**
       * 确认选择，通知上一级页面，员工部门已经选择
       */
      handleConfirm() {
        this.$refs.popup.close()
        const data = {
          guid: this.bridge.guid,
          bridge: this.bridge,
          data: this.selectedList
        }
        if (this.bridge.config && this.bridge.config.checkFn) {
          const res = this.bridge.config.checkFn(data)
          if (!res) return
        }
        uni.$emit('selected-user-and-dept', data)
        this.$Router.navigateBack()
      }
    }
  }
</script>

<style scoped lang="scss">
	$active-color: #1C69FF;
	
	.checkbox {
		width: 40rpx;
		height: 40rpx;
		text-align: center;
		border: 4rpx solid $light;
		border-radius: 50%;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		
		.icon {
			font-size: $wk-font-sm;
			line-height: 1;
			color: white;
		}
		
		&.active {
			border-color: $active-color;
			background-color: $active-color;
		}
	}
	
	.container {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		
		.header {
			width: 100%;
			background-color: white;
			
			::v-deep .wk-search-box {
				padding-left: 4%;
				padding-right: 4%;
				.search-box__body {
					background-color: #EFEFEF;
				}
			}
			
			.nav-tree-wrapper {
				padding: 15rpx 4% 30rpx;
				.nav-tree {
					width: 100%;
					flex-wrap: nowrap;
					overflow: auto;
					@include left;
					.nav-tree-item {
						flex-shrink: 0;
						font-size: $wk-font-base;
						color: $gray;
						
						.special {
							color: $active-color;
						}
						
						.icon {
							font-size: $wk-font-mini;
							color: $light;
							margin: 0 10rpx;
						}
					}
				}
			}
		}

		.content {
			flex: 1;
			overflow: auto;
			// .choose-all {
			// 	width: 100%;
			// 	font-size: $wk-font-medium;
			// 	background-color: white;
			// 	padding: 25rpx 4%;
			// 	margin: 16rpx 0;
			// 	@include left;
			// 	.checkbox {
			// 		margin-right: 36rpx;
			// 	}
			// }
			
			.dept-list {
				.box {
					width: 100%;
					height: 16rpx;
				}
				
				.dept-list-item {
					position: relative;
					width: 100%;
					font-size: $wk-font-medium;
					padding: 20rpx 4%;
					background-color: white;
					@include left;
					.checkbox {
						margin-right: 26rpx;
					}
					.dept-icon {
						width: 74rpx;
						height: 74rpx;
					}
					.text {
						flex: 1;
						margin-left: 36rpx;
						@include ellipsis
					}
					.more-icon {
						color: #919191;
						margin-right: 15rpx;
					}
					&::after {
						position: absolute;
						bottom: 1rpx;
						right: 0;
						content: '';
						width: calc(100% - 190rpx);
						height: 1rpx;
						background-color: #EBEEF1;
						display: block;
					}
					&:last-child::after {
						display: none;
					}
				}
			}
			
			.user-tips {
				width: 100%;
				height: 60rpx;
				line-height: 60rpx;
				color: $gray;
				font-size: $wk-font-base;
				padding: 0 4%;
			}
			
			.user-list {
				.user-list-item {
					position: relative;
					width: 100%;
					font-size: $wk-font-medium;
					padding: 20rpx 4%;
					background-color: white;
					@include left;
					.checkbox {
						margin-right: 26rpx;
					}
					.text {
						flex: 1;
						margin-left: 36rpx;
						@include ellipsis
					}
					.avatar {
						width: 74rpx;
						height: 74rpx;
					}
					&::after {
						position: absolute;
						bottom: 1rpx;
						right: 0;
						content: '';
						width: calc(100% - 190rpx);
						height: 1rpx;
						background-color: #EBEEF1;
						display: block;
					}
					&:last-child::after {
						display: none;
					}
				}
			}
		}
		
		.footer {
			position: relative;
			z-index: 1;
			width: 100%;
			height: 104rpx;
			box-shadow: 0 -4rpx 14rpx rgba(220,220,220,0.7);
			background-color: white;
			padding: 0 4%;
			@include left;
			.left {
				flex: 1;
				overflow: hidden;
				margin-right: 30rpx;
				.total-box {
					width: 100%;
					font-size: $wk-font-base;
					color: $active-color;
					.total {
						margin-right: 15rpx;
					}
					.icon {
						transform: rotate(-90deg);
						display: inline-block;
					}
				}
				.desc {
					font-size: $wk-font-mini;
					color: $light;
				}
			}
			.confirm-btn {
				width: 170rpx;
				height: 74rpx;
				font-size: $wk-font-base;
				color: white;
				border-radius: 12rpx;
				background-color: $active-color;
				flex-shrink: 0;
				@include center;
			}
		}
	}
	
	.popup {
		padding-bottom: 20rpx;
		
		.popup-header {
			position: relative;
			padding: 15rpx 38rpx;
			border-bottom: 1rpx solid $border-color;
			@include left;
			.text {
				flex: 1;
				color: $dark;
				font-size: $wk-font-medium;
			}
			.confirm-btn {
				color: $active-color;
				font-size: $wk-font-base;
				padding: 20rpx 0 20rpx 20rpx;
			}
		}
		.popup-content {
			min-height: 50vh;
			max-height: 80vh;
			overflow: auto;
			
			.remove-btn {
				width: 104rpx;
				height: 56rpx;
				font-size: $wk-font-base;
				border: 1rpx solid #D2D2D2;
				border-radius: 8rpx;
				@include center;
			}
			
			.dept-list {
				.dept-list-item {
					width: 100%;
					font-size: $wk-font-medium;
					padding: 20rpx 38rpx;
					background-color: white;
					border-bottom: 1rpx solid $border-color;
					@include left;
					.dept-icon {
						width: 74rpx;
						height: 74rpx;
					}
					.text {
						flex: 1;
						margin-left: 36rpx;
						@include ellipsis
					}
				}
			}
			.box {
				width: 100%;
				height: 15rpx;
				background-color: #F5F5F5;
			}
			.user-list {
				.user-list-item {
					position: relative;
					width: 100%;
					font-size: $wk-font-medium;
					padding: 20rpx 4%;
					background-color: white;
					@include left;
					.text {
						flex: 1;
						margin-left: 36rpx;
						@include ellipsis
					}
					.avatar {
						width: 74rpx;
						height: 74rpx;
					}
					&::after {
						position: absolute;
						bottom: 1rpx;
						right: 0;
						content: '';
						width: calc(100% - 130rpx);
						height: 1rpx;
						background-color: #EBEEF1;
						display: block;
					}
					&:last-child::after {
						display: none;
					}
				}
			}
		}
	}
</style>
