import { View } from '@tarojs/components'
import Search from '@/components/search'
import SideBar from '@/components/sideBar'
import Product from '@/components/product'
import MoveBtn from '@/components/moveBtn'
import ShopCart from '@/components/shoppingCart'
import { goLink } from '@/common/common'
import styles from './index.module.scss'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { kindListApi, ProductListApi } from '@/api/index'
// import useLogin from '@/use/useLogin'
import { mpproductcolorlist, mpshoppingCartproductColorlist } from "@/api/order"
import { dataLoadingStatus } from '@/common/util'
import Taro, { useDidShow } from '@tarojs/taro'
import { getFilterData } from '@/common/util'
import userInfo from '@/reducers/userInfo'
export default () => {
    useEffect(() => {
        categoryList()
    }, [])

    //获取面料种类
    const [kindData, setKindData] = useState<any>({ list: [], defaultId: 0 })
    const { fetchData } = kindListApi()
    const categoryList = async () => {
        const res = await fetchData()
        if (res.data?.list) {
            setKindData({ ...kindData, list: res.data.list, defaultId: res.data.list[0].id })
            setFiltrate({ ...filtrate, product_kind_id: res.data.list[0].id })
        }
    }

    //获取面料列表
    const [productData, setProductData] = useState({ list: [], total: 0 })
    const [hasMore, setHasMore] = useState(true)
    const [filtrate, setFiltrate] = useState({ product_kind_id: 0, size: 5, page: 1 })
    const pageNum = useRef({ size: filtrate.size, page: filtrate.page })
    const { fetchData: productFetchData, state: productState } = ProductListApi()
    //获取数据方法
    const getProductList = async () => {
        const { data, total } = await productFetchData(filtrate)
        setProductData({ ...productData, list: data.list, total })
        setRefresherTriggeredStatus(() => false)
    }
    //监听查询条件
    useEffect(() => {
        if (filtrate.product_kind_id) getProductList()
    }, [filtrate])

    //点击面料类型
    const getProductKindId = useCallback((e) => {
        pageNum.current.page = 1
        setProductData({ list: [], total: 0 })
        setFiltrate((list) => ({ ...list, size: 5, product_kind_id: e.id }))
    }, [])

    //上拉加载数据
    const getScrolltolower = useCallback(() => {
        if (productData.list.length >= productData.total) {
            setHasMore(false)
        } else {
            pageNum.current.page++
            const newSize = pageNum.current.size * pageNum.current.page
            setFiltrate((e) => ({ ...e, size: newSize }))
        }
    }, [productData])

    const [showShopCart, setShowShopCart] = useState(false)

    //列表下拉刷新
    const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
    const getRefresherRefresh = async () => {
        pageNum.current.page = 1
        setFiltrate({ ...filtrate, size: 5 })
        setHasMore(true)
        setRefresherTriggeredStatus(true)
    }

    const onj = JSON.parse(Taro.getStorageSync('userInfo'))
    const [search, setSearchObj] = useState({
        modeId: 0,
        goodsId: null,
        code_or_name: '',
        physical_warehouse: onj.physical_warehouse
    })

    //选择的类型
    const [typeList, setTypeList] = useState<any[]>([{ id: 0, name: '大货', checked: true }, { id: 1, name: '剪版', checked: false }, { id: 2, name: '散剪', checked: false }])
    //选择类型
    const handCheckMode = (item) => {
        typeList.map(it => {
            if (it.id === item.id) {
                it.checked = true
                setSearchObj((e) => ({ ...e, modeId: it.id }))
            } else {
                it.checked = false
            }
            return it
        })
        setTypeList([...typeList])
        setGoodlist([])
    }
    const [goodList, setGoodlist] = useState<any[]>([])
    const { fetchData: colorlistFetch } = mpproductcolorlist()
    const ShopCartRef = useRef<any>(null)

    const [goodObj, setGoodsobj] = useState({})
    //点击对应商品显示购物车
    const showCart = async (item) => {
        console.log(item, 6666)
        setSearchObj((e) => ({ ...e, goodsId: item.id }))
        setShowShopCart(true)
        setGoodsobj(item)
    }

    const getGoodList = async () => {
        const res = await colorlistFetch({ product_id: search.goodsId, sale_mode: search.modeId, code_or_name: search.code_or_name, physical_warehouse: 1 })
        res.data.list.map((item) => {
            item.showInput = false
            if (search.modeId !== 2) {
                item.nums = 1
                item.buyNums = 1
            } else {
                item.nums = 3
                item.buyNums = 3
            }
            return item
        })
        setGoodlist([...res.data.list])
    }
    //监听选择的类型
    useEffect(() => {
        setSearchObj(search)
        if (search.goodsId) getGoodList()
    }, [search])

    //关闭弹窗
    const closePoup = () => {
        setShowShopCart(false)
    }
    //数据加载状态
    const statusMore = useMemo(() => {
        return dataLoadingStatus({ list: productData.list, total: productData.total, status: productState.loading })
    }, [productData, productState.loading])

    //点击加展示输入框
    const handAdd = useCallback((item) => {
        goodList.map((it) => {
            if (item.id === it.id) {
                it.showInput = true
            }
            return item
        })
        setGoodlist([...goodList])
    }, [goodList])
    //点击减
    const reduceNums = useCallback((item) => {
        goodList.map((it) => {
            if (item.id === it.id) {
                item.nums--
                if (search.modeId !== 2) {
                    if (item.nums < 1) it.showInput = false, it.nums = 1
                } else {
                    if (item.nums < 3) it.showInput = false, it.nums = 3
                }

            }
            return item
        })
        setGoodlist([...goodList])
    }, [goodList])

    //点击输入框的加
    const handPlus = useCallback((item) => {
        goodList.map((it) => {
            if (item.id === it.id) {
                // if (it.nums > item.buyNums) {
                it.nums++
                // }
            }
            return item
        })
        setGoodlist([...goodList])
    }, [goodList])


    //输入了搜索关键字
    const getSearchData = useCallback((eq) => {
        setSearchObj((e) => ({ ...e, code_or_name: eq }))
    }, [])

    const [clientObj, setclientObj] = useState({
        clientId: -1,
        clientName: ''
    })
    useDidShow(() => {

        //获取选择的客户
        let pages = Taro.getCurrentPages();
        let currPage = pages[pages.length - 1]; // 获取当前页面
        setclientObj({
            clientId: currPage.data?.clientId,
            clientName: currPage.data?.clientName,
        })
    })

    //加入购物车
    const { fetchData: preViewFetch, } = mpshoppingCartproductColorlist()
    const handSure = async () => {
        const arr = goodList.filter(item => {
            return item.showInput
        })
        const list: any[] = []
        arr.forEach(it => {
            list.push({
                roll: search.modeId === 0 ? it.nums : 0,
                length: search.modeId !== 0 ? it.nums * 100 : 0,
                product_color_id: Number(it.id)
            })
        })
        const query = {
            purchaser_id: clientObj.clientId,
            sale_mode: search.modeId,
            color_list: list,
            sale_offect: 0
        }
        let res = await preViewFetch(getFilterData(query))
        Taro.showLoading({
            mask: true,
            title: '请稍等...'
        })
        if (res.data) {
            Taro.showToast({
                title: "加入成功",
                duration: 2000,
            });
            setShowShopCart(false)
            goodList.map(item => {
                item.showInput = false
                return item
            })
            setGoodlist([...goodList])
            console.log(search, '000000.0.0.')
            Taro.hideLoading()
        } else {
            Taro.hideLoading()
            Taro.showToast({
                title: res.msg,
                duration: 2000,
            });
        }
    }
    //输入框失焦
    const onBlur = (e, id) => {
        goodList.map((item) => {
            if (item.id == id) {
                item.nums = e.detail.value
            }
            return item
        })
        setGoodlist([...goodList])
    }

    return (
        // <MoveBtn onClick={() => setShowShopCart(showShopCart)}>
        <View className={styles.main}>
            <View className={styles.search}>
                {/* <View className={styles.search_collect} onClick={() => goLink('/pages/collection/index')}>
                        我的收藏
                    </View> */}
                <View className={styles.search_input} onClick={() => goLink('/pages/searchPage/index')}>
                    <Search disabled={true} style={{ width: '263rpx' }} />
                </View>
            </View>
            <View className={styles.products}>
                <SideBar
                    list={kindData.list}
                    height='100%'
                    defaultValue={kindData.defaultId}
                    hasMore={hasMore}
                    statusMore={statusMore}
                    selfOnScrolltolower={getScrolltolower}
                    sideBarOnClick={getProductKindId}
                    heightItem={150}
                    refresherTriggered={refresherTriggeredStatus}
                    selfOnRefresherRefresh={() => getRefresherRefresh()}>
                    <Product productList={productData.list} popupShow={(item) => showCart(item)} />
                </SideBar>
            </View>
            <View className='common_safe_area_y'></View>
            <ShopCart handSure={() => handSure()}
                clientName={clientObj?.clientName}
                clientId={clientObj?.clientId}
                modeFont={search.modeId}
                handPlus={(item) => handPlus(item)}
                obj={goodObj}
                ref={ShopCartRef}
                getSearchData={(e) => { getSearchData(e) }}
                onBlur={(e, id) => onBlur(e, id)}
                reduceNums={(item) => { reduceNums(item) }}
                addNums={(item) => { handAdd(item) }}
                showPopup={showShopCart}
                handCheck={(item) => { handCheckMode(item) }}
                closePopup={() => closePoup()}
                goodList={goodList}
                typeList={typeList}
            ></ShopCart>
        </View>
        // </MoveBtn>
    )
}
// oninputEvent={(e, item) => { oninputEvent(e, item) }}
