import { getStorage } from "@/utils/storage"
import { onLoad } from "@dcloudio/uni-app"
import { ref } from "vue"
import shopping from "@/api/https/shopping"

/*************************************************
 * 商品分类栏目
*/
function leftBarFn(props: AnyObject) {

    onLoad(async () => {
        await GetStoreCategoryMap()
    })

    /*************************************************
     * @info 左侧tab数据
     * 获取列表数据
     */
    const cat = ref<Array<AnyObject>>([])
    async function GetStoreCategoryMap() {
        let data = {
            storeID: getStorage('storeID'),
            parentID: -1,
        }
        let res = await shopping.getStore_category_map(data)
        if (res.code == 0) {
            handledata(res.data, true)
        } else {
            cat.value = []
            handleOriginData()
        }
    }

    /*************************************************
     * 处理列表数据
     */
    const _isMap = ref<boolean>(false)
    function handledata(curdeData: Array<AnyObject>, isMap: boolean) {
        let data = curdeData
        let catData: Array<AnyObject> = []
        data.forEach((item: AnyObject) => {
            if (item.name !== '3件9.9') {
                item.name = item.name.slice(0, 4)
            }
            catData.push(item)
        })

        //把sku分类过滤掉
        if (!isMap) catData = catData.filter((item) => item.type === 0)
        let catLevel1 = catData.filter((item) => item.level === 1)
        let catLevel2 = catData.filter((item) => item.level === 2)

        // 组合分类
        let catData2: Array<AnyObject> = []
        let catData3: AnyObject
        catLevel1.forEach((level1: AnyObject) => {
            isMap
                ? (catData3 = catLevel2.filter(
                    (level2) => level2.parentID === level1.categoryID
                ))
                : (catData3 = catLevel2.filter((level2) => level2.parentID === level1.id))
            level1.children = catData3
            _isMap.value = isMap
            catData2.push(level1)
        })
        let lastData = props.dafauleData.concat(catData2)
        cat.value = lastData
    }

    async function handleOriginData() {
        let res = await shopping.get_categories()
        if (res.code == 0) {
            handledata(res.data, false)
        }
    }

    return {
        cat,        // 右侧菜单数据
        GetStoreCategoryMap,    // 获取数据
    }
}

export default leftBarFn