import { Image, ScrollView, Text, View } from "@tarojs/components"
import classnames from "classnames";
import Search from '@/components/search'
import Filter from "@/components/filter";
import InfiniteScroll from '@/components/infiniteScroll'
import SortBtn from "@/components/sortBtn";
import SelectData, {ListProps} from "./components/selectData";
import { goLink } from "@/common/common";
import styles  from './searchList.module.scss'
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import useManualPullDownRefresh from "@/use/useManualPullDownRefresh";
import {GetProductListApi} from "@/api/material"
import Taro, { useDidShow, usePullDownRefresh, useRouter } from "@tarojs/taro";
import { formatHashTag, formatImgUrl } from "@/common/fotmat";
import { dataLoadingStatus, getFilterData } from "@/common/util";
import LoadingCard from "@/components/loadingCard";
import useLogin from "@/use/useLogin";

export default () => {
    const {checkLogin} = useLogin()
    useDidShow(async () => {
        await checkLogin()
    })

    const [showFilter, setShowFilter] = useState(false)
    const router = useRouter()

    //搜索参数
    const [searchField, setSearchField] = useState({
        code_or_name: router.params.key,
        page : 1,
        size : 10,
        width: '',
        weight_density: '',
        product_kind_id: '',
        component: ''
    })
    
    //获取面料列表
    const [materialList, setMaterialList] = useState<{list:any[], total:number}>({list:[], total:0})
    const {fetchData: materialFetchData, state: materialState} = GetProductListApi()
    const getProductList = async () => {
        let {data} = await materialFetchData(getFilterData(searchField))
        setMaterialList({list:data.list, total:data.total})
        Taro.stopPullDownRefresh()
    }

    //监听筛选条件变化
    useEffect(() => {
        getProductList()
    }, [searchField])

    
    //上拉加载数据
    const pageNum = useRef({size: searchField.size, page: searchField.page})
    const getScrolltolower = () => {
        if(materialList.list.length < materialList.total) {
            pageNum.current.page++
            const size = pageNum.current.size * pageNum.current.page
            setSearchField({...searchField, size })
        }
    }

    //数据加载状态
    const statusMore = useMemo(() => {
        return dataLoadingStatus({list:materialList.list, total: materialList.total, status: materialState.loading})
    }, [materialList])

    //输入了搜索关键字
    const getSearchData = useCallback((e) => {
        pageNum.current.page = 1
        setMaterialList(() => ({list:[], total:0}))
        setSearchField((val) => ({...val, code_or_name:e, size:10}))
    }, [])

    const goLinkPage = (item) => {
        goLink('/pages/details/index',{id:item.id})
    }

    //页面下拉刷新
    usePullDownRefresh(() => {
        setSearchField({...searchField ,size : 10})
    })

    //监听滚动
    const [scrollStatus, setScrollStatus] = useState(false)
    const onscroll = useCallback((e) => {
        if(e.detail.scrollTop > 20) {
            setScrollStatus(true)
        } else {
            setScrollStatus(false)
        }
    },[])

    //获取筛选条件
    const getFiltr = (e) => {
        pageNum.current.page = 1
        const {data} = e
        setSearchField({
            ...searchField,  
            width: data?.width,
            weight_density: data?.weight, 
            size: 10,
            component: data?.element,
            product_kind_id: data?.seriesId
        })
        formatSelectList(e)
    }

    //筛选条件格式化
    const [selectList , setSelectList] = useState<ListProps[]>()
    const formatSelectList = (val = {data:{}, field:{}}) => {
        console.log('data123::',val.data)
        let data:ListProps[] = []
        for(let key in val.data) {
            if(key !== 'seriesId'&& val.data[key] != '') {
                data.push({title:val.field[key], value:val.data[key]})
            }
        }
        console.log('data::',data)
        setSelectList([...data])
    }

    return (
        <View className={styles.main}>
            <View className={styles.search}>
                <Search placeIcon="out" placeholder="请输入面料关键词"  defaultValue={router.params.key} changeOnSearch={getSearchData} debounceTime={300}/>
            </View>
            <View className={styles.filter}>
                <View className={styles.filter_all}>
                    <View className={styles.text_zh}>
                        <Text>综合</Text>
                        <SortBtn status="top"/>
                    </View>
                    <View className={styles.text_sc}>
                        <Text>收藏</Text>
                        <SortBtn status="top"/>
                    </View>
                    <View className={styles.text_ss} onClick={() => goLink('/pages/searchList/hightSearchList')}>
                        <Text>高级搜索</Text>
                        <Text className={classnames('iconfont icon-sousuo', styles.miconfont)}></Text>
                    </View>
                </View>
                
                <View className={styles.filter_btn_con}>
                    <View className={styles.filter_scroll}>
                        <SelectData list={selectList}/>
                    </View>
                    <View className={styles.filter_more} onClick={() => setShowFilter(true)}>
                        <Text>筛选</Text>
                        <Text className={classnames('iconfont icon-shaixuan', styles.miconfont)}></Text>
                    </View>
                </View>
            </View>
            <View className={styles.list}>
                <View className={classnames(styles.list_num, scrollStatus&&styles.list_num_shadow)}>搜索结果 ({materialList.total}条记录)</View>
                <View className={styles.scroll}>
                    <InfiniteScroll 
                        selfonScrollToLower={() => getScrolltolower()} 
                        selfOnScroll={(e) => onscroll(e)}
                        statusMore={statusMore}
                    >
                        <View className={styles.product_list}>
                            {materialList.list.map(item => {
                                return <View key={item.id} className={styles.product_item} onClick={() => goLinkPage(item)}>
                                    <View className={styles.product_img}>
                                        <Image mode="aspectFill" src={formatImgUrl(item.texture_url)}></Image>
                                        <View className={styles.color_num}>{(item.product_color_count)}色</View>
                                    </View>
                                    <View className={styles.product_info}>
                                        <View className={styles.title}>{formatHashTag(item.code, item.name)}</View>
                                        <View className={styles.tag_list}>
                                            <View className={styles.tag}>{item.width}</View>
                                            <View className={styles.tag}>{item.weight_density}</View>
                                        </View>
                                        <View className={styles.introduce}>{item.component}</View>
                                    </View>
                                </View>
                            })}
                        </View>
                    </InfiniteScroll>
                </View>
            </View>
            <Filter show={showFilter} onClose={() => setShowFilter(false)} onFiltr={(e) => getFiltr(e)} />
        </View>
    )
}