<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar :title="navTitle">
        <!-- #ifndef MP-WEIXIN -->
        <button v-if="isRadio" class="button white-btn" @click="handleConfirm">
          确定
        </button>
        <!-- #endif -->
      </wk-nav-bar>

      <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(listData)" class="dept-list">
            <view class="box" />
						
            <view
              v-for="item in listData"
              :key="item[typeObj.valueField]"
              class="dept-list-item"
              @click="handleToChild(item)">
              <view
                :class="{active: item.checked }"
                class="checkbox"
                @click.stop="handleChoose(item)">
                <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[typeObj.labelField] }}<text v-if="item.currentNum && item.currentNum > 0">
                  ({{ item.currentNum }}人)
                </text>
              </view>
							
              <text
                :style="{visibility: !$isEmpty(item.children) ? 'visible' : 'hidden' }"
                class="wk wk-arrow-right more-icon" />
            </view>
          </view>
        </view>
				
        <!-- #ifdef MP-WEIXIN -->
        <view v-if="isRadio" class="footer-btn-group">
          <button class="button" @click="handleConfirm">
            确定
          </button>
        </view>
        <!-- #endif -->
				
        <view
          v-if="!isRadio"
          class="footer">
          <view class="left" @click="showPopup">
            <view class="total-box">
              <text class="total">
                已选择：{{ selectedList.length }}个部门
              </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">
            已选择：{{ selectedList.length }}个部门
          </text>
          <text class="confirm-btn" @click="handleConfirm">
            确定
          </text>
        </view>

        <view class="popup-content">
          <view class="dept-list">
            <view
              v-for="(item, index) in selectedList"
              :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)">
                移除
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import {
    AdminQueryDeptTree
  } from 'API/admin'

  import { mapGetters } from 'vuex'
  import { deepCopy } from '@/utils/lib.js'
  import { isObject } from '@/utils/types.js'

  export default {
    name: 'DeptChoose',
    data() {
      return {
        navTreeList: [],

        typeObj: {
          labelField: 'name',
          valueField: 'id'
        },

        selectedList: [],
				
        listData: [],
        deptData: [],
        copyList: null,

        checkedAll: false,

        defaultVal: null,

        routerQuery: {},
        bridge: {}
      }
    },
    computed: {
			...mapGetters({
				companyInfo: 'user/expirationInfo'
			}),

			navTitle() {
				return this.bridge.title || '选择部门'
			},
			isRadio() {
				return this.bridge.maxlength === 1
			},

			navLen() {
				// 处理动态增减导航项时小程序无法渲染样式问题
				return this.navTreeList.length
			}
    },
    watch: {
      companyInfo: {
        handler(val) {
          if (!this.$isEmpty(val)) {
            this.navTreeList = [{
              deptId: 0,
              name: val.companyName
            }]
            this.getList()
          }
        },
        deep: true,
        immediate: true
      }
    },
    onLoad(options) {
      this.routerQuery = options || {}
      this.bridge = getApp().globalData.selectedValBridge.dept || {}
      this.selectedList = this.bridge.defaultVal || []
    },
    onUnload() {
      getApp().globalData.selectedValBridge = {}
    },
    methods: {
      /**
       * 获取选项列表
       */
      getList(deptId = null) {
        if (!this.$isEmpty(this.bridge.list)) {
          this.listData = this.bridge.list
          return
        }

        const otherParams = this.bridge.params || {} // 附加参数
        const params = {
          search: '',
          type: 'tree',
					...otherParams
        }
				
        if (deptId) {
          params.id = deptId
        }

        const request = this.bridge.request || AdminQueryDeptTree
        if (!request) return

        request(params).then(res => {
          this.listData = res
          this.getDefaultChecked()
          this.copyList = null
        }).catch()
      },
			
      getDefaultChecked() {
        const key = this.typeObj.valueField
        const deptIds = (this.selectedList || []).map(o => o[key])
        this.listData.forEach(item => {
          if (deptIds.includes(item[key])) {
            this.$set(item, 'checked', true)
          } else {
            this.$set(item, 'checked', false)
          }
        })
        console.log('deptIds: ', deptIds, this.listData)
      },

      handleToSearch(keyworad) {
        if (!this.copyList) {
          this.copyList = [...this.listData]
        }
        if (this.$isEmpty(keyworad)) {
          this.listData = [...this.copyList]
          this.copyList = null
          return
        }
        this.listData = this.copyList.filter(o => o[this.typeObj.labelField].includes(keyworad))
      },
			
      /**
       * 跳转到子部门
       * @param {Object} item
       */
      handleToChild(item) {
        console.log('to child', item)
        if (!this.$isEmpty(item.children)) {
          this.listData = item.children
          this.copyList = null
          this.navTreeList.push({
            deptId: item[this.typeObj.valueField],
            name: item[this.typeObj.labelField]
          })
          this.getDefaultChecked()
        } else {
          this.handleChoose(item)
        }
      },
			
      /**
       * 导航切换部门
       * @param {Object} index
       */
      handleNavgiateToDept(index) {
        if (index >= this.navTreeList.length - 1) return
			
        const item = this.navTreeList[index]
        this.getList(item.deptId)
        this.navTreeList.splice(index + 1)
      },
			
      /**
       * 切换选中
       * @param {Object} item
       * @param {Object} type
       */
      handleChoose(item) {
        this.$set(item, 'checked', !item.checked)
        const key = this.typeObj.valueField
				
        if (item.checked) {
          // 勾选
          const maxlength = this.bridge.maxLength
          if (this.selectedList.length >= maxlength) {
            this.selectedList.splice(maxlength - 1)
          }
          this.selectedList.push(item)
          this.getDefaultChecked()
        } else {
          // 取消勾选
          const findIndex = this.selectedList.findIndex(o => o[key] === item[key])
          if (findIndex !== -1) {
            this.checkedAll = false
            this.selectedList.splice(findIndex, 1)
          }
        }
      },
			
      showPopup() {
        this.$refs.popup.open()
      },
      handleRemove(index) {
        this.selectedList.splice(index, 1)
        this.getDefaultChecked()
      },

      handleConfirm() {
        this.$refs.popup.close()
        const data = {
          guid: this.bridge.guid,
          bridge: this.bridge,
          data: this.selectedList
        }
        console.log('data: ', data)
        if (this.bridge.config && this.bridge.config.checkFn) {
          const res = this.bridge.config.checkFn(data)
          if (!res) return
        }
        uni.$emit('selected-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;
					}
				}
			}
		}

		.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
					}
				}
			}
		}
	}
</style>
