<template>
	<u-popup class="jnpf-tree-select-popup" mode="right" v-model="showPopup" width="100%" @close="close">
		<view class="jnpf-tree-select-body">
			<view class="jnpf-tree-select-title">
				<text class="icon-ym icon-ym-report-icon-preview-pagePre backIcon" @tap="close()"></text>
				<view class="title">岗位选择</view>
			</view>
			<view class="jnpf-tree-select-search">
				<u-search :placeholder="$t('app.apply.pleaseKeyword')" v-model="keyword" height="72"
					:show-action="false" @change="handleSearch" bg-color="#f0f2f6" shape="square">
				</u-search>
			</view>
			<view class="jnpf-tree-selected">
				<view class="jnpf-tree-selected-head">
					<view>{{$t('component.jnpf.common.selected')}}({{selectedList.length||0}})</view>
					<view v-if="multiple" class="clear-btn" @click="setCheckAll">
						{{$t('component.jnpf.common.clearAll')}}
					</view>
				</view>
				<view class="jnpf-tree-selected-box">
					<scroll-view scroll-y="true" class="select-list">
						<u-tag closeable @close="delSelect(index)" v-for="(item,index) in selectedList" :key="index"
							:text="item.orgNameTree" class="u-selectTag" />
					</scroll-view>
				</view>
			</view>
			<view class="jnpf-tree-selected-line"></view>
			<view class="jnpf-tree-selected-tabs">
				<view class="tab-item" :class="{'tab-item-active':activeKey==='1'}" @click="toggloActive('1')">岗位
				</view>
				<view class="tab-item" :class="{'tab-item-active':activeKey==='2'}" @click="toggloActive('2')"
					v-if="selectType === 'all'">
					当前岗位
				</view>
			</view>
			<view class="jnpf-tree-select-tree">
				<scroll-view :scroll-y="true" style="height: 100%" v-if="activeKey==='1' && !hasPage">
					<ly-tree v-if="selectType !== 'all'" :tree-data="options" :node-key="realProps.value"
						default-expand-all :props="realProps" :filter-node-method="filterNode"
						child-visible-for-filter-node show-node-icon @node-click="handleTreeNodeClick"
						:show-checkbox="multiple" :show-radio="!multiple" :expandOnClickNode="false"
						:checkOnClickNode="true" :expandOnCheckNode="false" checkStrictly ref="tree">
					</ly-tree>
					<ly-tree ref="tree" v-if="selectType === 'all'" :props="realProps" :node-key="realProps.value"
						:load="loadNode" lazy :tree-data="lazyOptions" show-node-icon :defaultExpandAll='false'
						@node-click="handleTreeNodeClick" :show-checkbox="multiple" :show-radio="!multiple"
						:expandOnClickNode="false" :checkOnClickNode="true" :expandOnCheckNode="false" checkStrictly />
				</scroll-view>
				<scroll-view :scroll-y="true" style="height: 100%" :refresher-enabled="false" :refresher-threshold="100"
					:scroll-with-animation='true' :refresher-triggered="triggered" @scrolltolower="handleScrollToLower"
					v-else>
					<view class="jnpf-selcet-list" v-if="list.length">
						<view class="jnpf-selcet-cell" v-for="item in list" :key="item.id"
							@click.stop="handleNodeClick(item)">
							<view class="jnpf-selcet-cell-action">
								<lyCheckbox :type="multiple ? 'checkbox' : 'radio'"
									:checked="selectedIds.includes(item.id)" />
							</view>
							<view class="jnpf-selcet-cell-name">
								{{item.orgNameTree}}
							</view>
						</view>
					</view>
					<Empty class="h-full" v-else />
				</scroll-view>
			</view>
			<!-- 底部按钮 -->
			<view class="jnpf-tree-select-actions">
				<u-button class="buttom-btn" @click="close()">{{$t('common.cancelText')}}</u-button>
				<u-button class="buttom-btn" type="primary"
					@click.stop="handleConfirm()">{{$t('common.okText')}}</u-button>
			</view>
		</view>
	</u-popup>
</template>
<script>
	import {
		getPositionByCondition,
		getOrgAndPosSelector,
		getPositionSelector
	} from '@/api/common'
	import lyCheckbox from '@/components/ly-tree/components/ly-checkbox.vue';
	import Empty from '../Empty/index.vue'

	const defaultProps = {
		label: 'fullName',
		value: 'id',
		icon: 'icon',
		children: 'children'
	}
	export default {
		props: {
			selectedData: {
				type: Array,
				default: () => []
			},
			ableIds: {
				type: Array,
				default: () => []
			},
			selectType: {
				type: String,
				default: 'all'
			},
			// 通过双向绑定控制组件的弹出与收起
			modelValue: {
				type: Boolean,
				default: false
			},
			// 弹出的z-index值
			zIndex: {
				type: [String, Number],
				default: 0
			},
			props: {
				type: Object,
				default: () => ({
					label: 'fullName',
					value: 'id',
					icon: 'icon',
					children: 'children',
					isLeaf: 'isLeaf'
				})
			},
			multiple: {
				type: Boolean,
				default: false
			}
		},
		components: {
			lyCheckbox,
			Empty
		},
		data() {
			return {
				moving: false,
				selectedList: [],
				selectedIds: [],
				keyword: '',
				showPopup: false,
				options: [],
				lazyOptions: [],
				activeKey: '1',
				hasPage: false,
				pagination: {
					hasPage: 1,
					currentPage: 1,
					pageSize: 20
				},
				triggered: false,
				finish: false,
				list: [],
			};
		},
		watch: {
			// 在select弹起的时候，重新初始化所有数据
			modelValue: {
				handler(val) {
					this.showPopup = val
					if (!val) this.activeKey = ''
					if (val) setTimeout(() => this.init(), 10);
				},
				immediate: true
			},
			selectedList: {
				handler(val) {
					this.selectedIds = val.map((o) => o.id);
					this.$refs.tree && this.$refs.tree.setCheckedKeys(this.selectedIds)
				},
				deep: true
			},
		},
		computed: {
			uZIndex() {
				// 如果用户有传递z-index值，优先使用
				return this.zIndex ? this.zIndex : this.$u.zIndex.popup;
			},
			realProps() {
				return {
					...defaultProps,
					...this.props
				}
			},
			getCurrPosList() {
				const userInfo = uni.getStorageSync('userInfo') || {}
				const list = (userInfo.positionList || []).map((o) => ({
					...o,
					orgNameTree: o.treeName
				}))
				return list
			}
		},
		methods: {
			init() {
				this.keyword = ""
				this.hasPage = 0
				this.activeKey = '1'
				this.finish = false
				this.pagination.currentPage = 1
				this.$nextTick(() => {
					this.triggered = true
				})
				this.selectedList = JSON.parse(JSON.stringify(this.selectedData))
				if (this.selectType !== 'all') this.getConditionOptions()
			},
			getConditionOptions() {
				if (!this.ableIds.length) return
				const query = {
					ids: this.ableIds
				}
				getPositionByCondition(query).then(res => {
					this.options = res.data.list || []
					this.$refs.tree && this.$refs.tree.setCheckedKeys(this.selectedIds)
				})
			},
			filterNode(value, data) {
				if (!value) return true;
				return data[this.realProps.label].indexOf(value) !== -1;
			},
			loadNode(node, resolve) {
				const id = node.key || '0'
				const type = node?.data?.type || 'organize'
				const data = {
					id,
					type
				}
				getOrgAndPosSelector(data).then(res => {
					const list = (res.data?.list || []).map(o => ({
						...o,
						disabled: o.type !== 'position'
					}))
					resolve(list)
					this.$refs.tree && this.$refs.tree.setCheckedKeys(this.selectedIds)
				})
			},
			handleScrollToLower() {
				if (this.finish || this.activeKey === '2') return
				this.getTreeData()
			},
			getTreeData() {
				let data = {
					keyword: this.keyword,
					parentId: '0',
					...this.pagination
				}
				getPositionSelector(data).then(res => {
					const list = res.data.list || []
					if (list.length < this.pagination.pageSize) this.finish = true;
					this.list = this.list.concat(list);
					this.pagination.currentPage++
				})
			},
			onTreeCheck(item) {
				this.handleTreeNodeClick(item);
			},
			handleTreeNodeClick(item) {
				const data = item.data
				if (this.selectType === 'all' && data.type !== 'position') return
				this.handleNodeClick(data)
			},
			handleNodeClick(data) {
				const index = this.selectedList.findIndex((o) => o.id === data.id);
				if (index !== -1) return this.selectedList.splice(index, 1);
				this.multiple ? this.selectedList.push(data) : (this.selectedList = [data]);
			},
			delSelect(index) {
				this.selectedList.splice(index, 1);
			},
			setCheckAll() {
				this.selectedIds = []
				this.selectedList = []
			},
			handleConfirm() {
				this.$emit('confirm', this.selectedList, this.selectedIds);
				this.close();
			},
			close() {
				this.$emit('close', false);
			},
			toggloActive(key) {
				if (this.activeKey === key) return
				this.keyword = ''
				this.$nextTick(() => {
					this.activeKey = key
					if (this.activeKey === '2') this.list = this.getCurrPosList
				})
			},
			handleSearch(val) {
				this.keyword = val
				if (this.selectType !== 'all') return this.$refs.tree && this.$refs.tree.filter(val)
				this.hasPage = !!val
				this.list = []
				if (this.activeKey != '1') this.activeKey = '1'
				this.$nextTick(() => {
					if (this.keyword) {
						this.pagination.currentPage = 1
						this.finish = false
						this.$u.debounce(this.getTreeData, 300)
					}
				})
			},
		}
	};
</script>