<template>
	<view v-if="node.visible" 
		class="ly-tree-node" 
		name="LyTreeNode" 
		ref="node">
		<view class="ly-tree-node__content" :class="{'ly-tree-node__content-current': node.isCurrent && highlightCurrent}" :style="{ 'padding-left': (node.level - 1) * indent + 'px' }">
			<text v-if="node.isLeaf" class="ly-tree-node__expand-icon-holder"></text>	
			<text v-else class="ly-tree-node__expand-icon" @click.stop="handleExpandIconClick">{{node.expanded ? iconExpand : iconCollapse}}</text>

			<ly-checkbox v-if="checkboxVisible || radioVisible" :type="checkboxVisible ? 'checkbox' : 'radio'" :checked="node.checked"
			 :indeterminate="node.indeterminate" :disabled="!!node.disabled" @check="handleCheckChange(!node.checked)" />

			<image v-if="node.loading" class="ly-tree-node__loading-icon" mode="widthFix" src="data:image/gif;base64,[encoded data, 5196 characters]"></image>

			<template v-if="node.icon && node.icon.length > 0">
				<image v-if="node.icon.indexOf('/') !== -1" class="ly-tree-node__icon" :src="node.icon" mode="widthFix"></image>
				<text v-else class="ly-tree-node__icon" :class="node.icon"></text>
			</template>

			<text class="ly-tree-node__label" @click.stop="handleClick">{{node.label}}</text>
		</view>

		<view v-if="(!renderAfterExpand || childNodeRendered)" class="ly-tree-node__children" :class="{'ly-tree-node__children-hide': !expanded}" role="group">
			<ly-tree-node v-for="cNodeId in node.childNodesId" :nodeId="cNodeId" :render-after-expand="renderAfterExpand"
			 :show-checkbox="showCheckbox" :show-radio="showRadio" :check-only-leaf="checkOnlyLeaf" :key="getNodeKey(cNodeId)"
			 :indent="indent" :icon-class="iconClass">
			</ly-tree-node>
		</view>
	</view>
</template>

<script>
	import {
		getNodeKey
	} from './tool/util.js';
	import lyCheckbox from './components/ly-checkbox.vue';
	
	// #ifdef APP-NVUE
	var domModule = weex.requireModule('dom');
	domModule.addRule('fontFace', {
		'fontFamily': "lyExpandIcons",
		'src': "url('data:font/truetype;charset=utf-8;base64,AAEAAAALAIAAAwAwR1NVQrD+s+0AAAE4AAAAQk9TLzI/YkrfAAABfAAAAFZjbWFwjN/t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wECAQMBBAAKY2FyZXQtZG93bgtjYXJldC1yaWdodAAAAAA=')"
	});
	// #endif

	export default {
		name: 'LyTreeNode',

		componentName: 'LyTreeNode',

		components: {
			lyCheckbox
		},

		props: {
			nodeId: [Number, String],
			renderAfterExpand: {
				type: Boolean,
				default: true
			},
			checkOnlyLeaf: {
				type: Boolean,
				default: false
			},
			showCheckbox: {
				type: Boolean,
				default: false
			},
			showRadio: {
				type: Boolean,
				default: false
			},
			indent: Number,
			iconClass: String
		},

		data() {
			return {
				node: {
					indeterminate: false,
					checked: false,
					expanded: false
				},
				expanded: false,
				childNodeRendered: false,
				oldChecked: null,
				oldIndeterminate: null,
				highlightCurrent: false,
				iconExpand: '\ue8ec',
				iconCollapse: '\ue8ed'
			};
		},

		inject: ['tree'],

		computed: {
			checkboxVisible() {
				if (this.checkOnlyLeaf) {
					return this.showCheckbox && this.node.isLeaf;
				}

				return this.showCheckbox;
			},
			radioVisible() {
				if (this.checkOnlyLeaf) {
					return this.showRadio && this.node.isLeaf;
				}

				return this.showRadio;
			}
		},

		watch: {
			'node.indeterminate'(val) {
				this.handleSelectChange(this.node.checked, val);
			},
			'node.checked'(val) {
				this.handleSelectChange(val, this.node.indeterminate);
			},
			'node.expanded'(val) {
				this.$nextTick(() => this.expanded = val);
				if (val) {
					this.childNodeRendered = true;
				}
			}
		},

		methods: {
			getNodeKey(nodeId) {
				let node = this.tree.store.root.getChildNodes([nodeId])[0];
				return getNodeKey(this.tree.nodeKey, node.data);
			},

			handleSelectChange(checked, indeterminate) {
				if (this.oldChecked !== checked && this.oldIndeterminate !== indeterminate) {

					if (this.checkOnlyLeaf && !this.node.isLeaf) return;

					if (this.checkboxVisible) {
						const allNodes = this.tree.store._getAllNodes();
						this.tree.$emit('check-change', {
							checked,
							indeterminate,
							node: this.node,
							data: this.node.data,
							checkedall: allNodes.every(item => item.checked)
						});
					} else {
						this.tree.$emit('radio-change', {
							checked,
							node: this.node,
							data: this.node.data,
							checkedall: false
						});
					}
				}

				if (!this.expanded && this.tree.expandOnCheckNode && checked) {
					this.handleExpandIconClick();
				}

				this.oldChecked = checked;
				this.indeterminate = indeterminate;
			},

			handleClick(e) {
				this.tree.store.setCurrentNode(this.node);
				this.tree.$emit('current-change', {
					node: this.node,
					data: this.tree.store.currentNode ? this.tree.store.currentNode.data : null,
					currentNode: this.tree.store.currentNode
				});
				this.tree.currentNode = this.node;

				if (this.tree.expandOnClickNode) {
					this.handleExpandIconClick();
				}

				if (this.tree.checkOnClickNode && !this.node.disabled) {
					(this.checkboxVisible || this.radioVisible) && this.handleCheckChange(!this.node.checked);
				}

				this.tree.$emit('node-click', this.node);
				
				// #ifdef APP-NVUE
				e.stopPropagation()
				// #endif
			},

			handleExpandIconClick() {
				if (this.node.isLeaf) return;

				if (this.expanded) {
					this.tree.$emit('node-collapse', this.node);
					this.node.collapse();
				} else {
					this.node.expand();
					this.tree.$emit('node-expand', this.node);

					if (this.tree.accordion) {
						uni.$emit(`${this.tree.elId}-tree-node-expand`, this.node);
					}
				}
			},

			handleCheckChange(checked) {
				if (this.node.disabled) return;

				if (this.checkboxVisible) {
					this.node.setChecked(checked, !(this.tree.checkStrictly || this.checkOnlyLeaf));
				} else {
					this.node.setRadioChecked(checked);
				}

				this.$nextTick(() => {
					this.tree.$emit('check', {
						node: this.node,
						data: this.node.data,
						checkedNodes: this.tree.store.getCheckedNodes(),
						checkedKeys: this.tree.store.getCheckedKeys(),
						halfCheckedNodes: this.tree.store.getHalfCheckedNodes(),
						halfCheckedKeys: this.tree.store.getHalfCheckedKeys()
					});
				});
			}
		},

		created() {
			if (!this.tree) {
				throw new Error('Can not find node\'s tree.');
			}
			
			const props = this.tree.props || {};
			const childrenKey = props['children'] || 'children';

			this.node = this.tree.store.nodesMap[this.nodeId];
			this.highlightCurrent = this.tree.highlightCurrent;

			if (this.node.expanded) {
				this.expanded = true;
				this.childNodeRendered = true;
			}

			this.$watch(`node.data.${childrenKey}`, () => {
				this.node.updateChildren();
			});

			if (this.tree.accordion) {
				uni.$on(`${this.tree.elId}-tree-node-expand`, node => {
					if (this.node.id !== node.id && this.node.level === node.level) {
						this.node.collapse();
					}
				});
			}
		},

		beforeDestroy() {
			this.$parent = null;
		}
	};
</script>

<style>
	.ly-tree-node__content {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		height: 70rpx;
	}
	
	.ly-tree-node__expand-icon-holder {
		width: 50rpx;
		height: 36rpx;
		padding-right: 16rpx;
	}

	.ly-tree-node__icon {
		width: 40rpx;
		height: 40rpx;
		overflow: hidden;
		margin-right: 16rpx;
	}
	
	.ly-tree-node__loading-icon {
		margin-right: 16rpx;
		width: 30rpx;
		height: 30rpx;
	}

	.ly-tree-node__label {
		font-size: 28rpx;
		color: #606266;
		width: 750rpx;
	}
	
	.ly-tree-node__children {
		overflow: hidden;
		background-color: transparent
	}
	
	.ly-tree-node__children-hide {
		height: 0px;
		line-height: 0px;
	}

	.ly-tree-node__content-current {
		background-color: #F5F7FA
	}
	
	/* icon-start */
	/* #ifndef APP-NVUE */
	@font-face {
		font-family: "lyExpandIcons";
		src: url('data:font/truetype;charset=utf-8;base64,AAEAAAALAIAAAwAwR1NVQrD+s+0AAAE4AAAAQk9TLzI/YkrfAAABfAAAAFZjbWFwjN/tlQAAAeAAAAF+Z2x5ZvmkuOMAAANoAAAAcGhlYWQZcwxrAAAA4AAAADZoaGVhB94DhAAAALwAAAAkaG10eAwAAAAAAAHUAAAADGxvY2EAHAA4AAADYAAAAAhtYXhwAQ4AGAAAARgAAAAgbmFtZT5U/n0AAAPYAAACbXBvc3SyMEhaAAAGSAAAAEIAAQAAA4D/gABcBAAAAAAABAAAAQAAAAAAAAAAAAAAAAAAAAMAAQAAAAEAADJ4N4JfDzz1AAsEAAAAAADbKmRFAAAAANsqZEUAAAAABAAC5AAAAAgAAgAAAAAAAAABAAAAAwAMAAEAAAAAAAIAAAAKAAoAAAD/AAAAAAAAAAEAAAAKAB4ALAABREZMVAAIAAQAAA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AAIADgC/AAMAAQQJAAMAEADNAAMAAQQJAAQAEADdAAMAAQQJAAUAFgDtAAMAAQQJAAYAEAEDAAMAAQQJAAoAVgETAAMAAQQJAAsAJgFpCkNyZWF0ZWQgYnkgaWNvbmZvbnQKaWNvbmZvbnRSZWd1bGFyaWNvbmZvbnRpY29uZm9udFZlcnNpb24gMS4waWNvbmZvbnRHZW5lcmF0ZWQgYnkgc3ZnMnR0ZiBmcm9tIEZvbnRlbGxvIHByb2plY3QuaHR0cDovL2ZvbnRlbGxvLmNvbQAKAEMAcgBlAGEAdABlAGQAIABiAHkAIABpAGMAbwBuAGYAbwBuAHQACgBpAGMAbwBuAGYAbwBuAHQAUgBlAGcAdQBsAGEAcgBpAGMAbwBuAGYAbwBuAHQAaQBjAG8AbgBmAG8AbgB0AFYAZQByAHMAaQBvAG4AIAAxAC4AMABpAGMAbwBuAGYAbwBuAHQARwBlAG4AZQByAGEAdABlAGQAIABiAHkAIABzAHYAZwAyAHQAdABmACAAZgByAG8AbQAgAEYAbwBuAHQAZQBsAGwAbwAgAHAAcgBvAGoAZQBjAHQALgBoAHQAdABwADoALwAvAGYAbwBuAHQAZQBsAGwAbwAuAGMAbwBtAAAAAAIAAAAAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwECAQMBBAAKY2FyZXQtZG93bgtjYXJldC1yaWdodAAAAAA=') format('truetype');
	}
	/* #endif */
	
	.ly-tree-node__expand-icon {
		font-family: lyExpandIcons;
		font-size: 36rpx;
		font-style: normal;
		text-decoration: none;
		text-align: center;
		color: #DCDFE6;
		font-weight: 500;
		padding-right: 16rpx
	}
	/* icon-end */
</style>
