<template>
	<view class="min-page bg-gray" style="padding: 30rpx 30rpx 200rpx 30rpx;">
		<view style="background-color: #fff;border-radius: 10rpx;">
			<view style="padding: 10px 10px 0 10px;">
			    <uni-easyinput suffixIcon="search" v-model="pageData.query.name" placeholder="请输入规格搜索" @iconClick="search"
			     @blur="search" trim></uni-easyinput>
			</view>
			<view v-for="(item,index) in pageData.list" :key="index" style="padding: 10rpx;" v-if="pageData.loading">
				<tree-item @del="delSpecifications(index)" :data="item" ></tree-item>
			</view>
		</view>
		
		
		<view class="fixed-b">
			<my-button @tap="toAdd" shape="circle">添加规格组</my-button>
		</view>
	</view>
</template>

<script setup>
	import { reactive, ref } from 'vue';
	import {onLoad,onShow} from '@dcloudio/uni-app'
	import go from '@/commons/utils/go.js';
	import myButton from '@/components/my-components/my-button.vue'
	import treeItem from './components/tree-item.vue'
	import { getSpecList,delSpec } from '@/api/product.js'
	
	const pageData = reactive({
		loading: true,
		query:{
			name: ""
		},
		list: []
	})
	onShow(()=>{
		init()
	})
	function init(){
		getSpecList(pageData.query).then(res=>{
			pageData.list=res
		})
		pageData.list.map(item=>{
			filterData(item)
		})
	}
	
	/**
	 * 搜索
	 */
	function search() {
		if( pageData.query.name == ""){
			init()
			return false;
		}
	    pageData.loading = false
	    pageData.list = filterSearch(pageData.list, pageData.query.name || '')
	    setTimeout(() => {
			pageData.loading = true
	    }, 10)
	}
	
	/**
	 * 搜索数据处理
	 * @param {Object} data
	 * @param {Object} keyword
	 */
	function filterSearch(data, keyword) {
	    return data.filter(node => {
			// 判断当前节点是否匹配筛选条件
			if (node.name.includes(keyword)) {
	            if(!node.type){
	              node.isOpen=true
	            }
				return true;
			}
			// 递归过滤子节点
			if (node.children && node.children.length) {
				node.children = filterSearch(node.children, keyword);
	            node.isOpen=true
				return node.children.length > 0;
			}
			return false;
	    });
	}
	
	/**
	 * 请求获取数据处理
	 * @param {Object} item
	 */
	function filterData (item) {
		item.isOpen = false
		if( item.children && item.children.length > 0 ){
			item.children.map(item=>{
				filterData(item)
			})
		}
		
	}
	
	/**
	 * 删除规格
	 * @param {Object} index
	 */
	function delSpecifications(index){
		uni.showModal({
			title: '提示',
			content: '删除后使用此规格的商品将取消此规格,是否继续?',
			success: function (res) {
				if (res.confirm) {
					console.log('用户点击确定');
					delSpec(pageData.list[index].id).then(res=>{
						uni.showToast({
							title:'删除成功',
							icon:'none'
						})
						init()
					})
				} 
			}
		});
	}
	
	/**
	 * 新增规格
	 */
	function toAdd() {
		go.to('PAGES_PRODUCT_GUIGE_ADD')
	}
	

</script>

<style lang="scss">
	.fixed-b {
		position: fixed;
		left: 110rpx;
		right: 110rpx;
		bottom: 80rpx;
	}
</style>