import Popup from "@/components/popup";
import { ScrollView, Text, View } from "@tarojs/components";
import { Children, memo, useEffect, useMemo, useRef, useState } from "react";
import classnames from "classnames";
import styles  from './index.module.scss'
import { ReturnExplainApi, ReturnReasonApi } from "@/api/salesAfterOrder";

//原因选择
type Param = {id:number, name:string, typle?:number}
type ReasonInfoParam = {
    show?: boolean, //显示 
    onClose?: () => void, //关闭
    title?: string, //标题
    list?: {id:number, name:string, typle?:number}[], //数据列表
    onSelect?: (val: object) => void, //选择
    defaultValue?: number, //默认选中
    dataLength?: number, //可显示的数据列数
}
export default memo(({show = false, onClose, title = '', list = [], onSelect, defaultValue, dataLength = 2}: ReasonInfoParam) => {

    const [initList, setInitList] = useState([])
    //退货原因
    const idRef = useRef(0)
    const {fetchData: fetchDataReturnReason} = ReturnReasonApi()
    const getReturnReason = async () => {
        let res = await fetchDataReturnReason()
        setInitList(res.data?.list||[])
    }
    useEffect(() => {
        getReturnReason()
    }, [])

    //售后退货说明
    const {fetchData: fetchDataReturnExplain} = ReturnExplainApi()
    const getReturnExplain = async () => {
        let res = await fetchDataReturnExplain({return_reason: idRef.current})
        setInitList(res.data?.list||[])
    }
    
    const [headerList, setHeaderList] = useState<{id: number, name: string}[]>([])
    const onSelectData = (item) => {
        if(headerList.length <= dataLength) {
            idRef.current = item.id
            if(headerList.length < dataLength - 1) getReturnExplain()
            headerList[headerList.length == dataLength?(dataLength - 1):headerList.length] = {id:item.id, name:item.name}
            setHeaderList((e) => [...e])
            console.log('headerList.length',headerList.length)
            
        }

    }

    const onHeaderClick = (index) => {
        let list = headerList.slice(0, index + 1)
    }
    

    return (
        <Popup showIconButton={false} show={show} title={title} onClose={onClose} >
            <View className={styles.reason_return_con}>
                <View className={styles.reason_title}>
                    {headerList.map((item, index) => {
                       return <Text key={item.id} onClick={() => onHeaderClick(index)}>{item.name}</Text>
                    })}
                    {dataLength > headerList.length&&<Text>请选择</Text>}
                </View>
                <ScrollView scrollY className={styles.reason_scroll}>
                    <View className={styles.reason_list}>
                        {initList.map(item => <View onClick={() => onSelectData(item)} key={item.id} className={classnames(styles.reason_item, item.id == defaultValue&&styles.select_item)}>{item.name}</View> )}
                    </View>
                </ScrollView>
            </View>
        </Popup>
    )
})