index.tsx 9.01 KB
import React, {useEffect, useState} from 'react'
import './style.less'
import NavBar from '@/components/nav-bar'
import _mp4 from './mp4.png';
import _pdf from './pdf.png';
import _preview from './preview.png';

import {useSearchParams} from "react-router-dom";
import {getFilePreview, getProductBook} from "@/api/apiConfig";
import {SpinLoading, Checkbox, Toast} from 'antd-mobile'
import { useNavigate, useLocation } from "react-router-dom";

export interface ListType {
    id: string;
    fileId: string;
    name: string;
    url?: string;
    type: 'pdf' | 'mp4' | string
}

type CheckboxValue = string | number;

const ProductionList: React.FC = () => {
    const [title, setTitle] = useState<string>('');
    const [list, setList] = useState<ListType[]>([]);
    const [show, setShow] = useState<boolean>(false);
    const [showBatch, setShowBatch] = useState<boolean>(false);
    const navigate = useNavigate();
    const location = useLocation();
    console.log('location', location?.pathname, location?.search)
    const [checkItems, setCheckItems] = useState<CheckboxValue[]>([])
    const [checkValues, setCheckValues] = useState<CheckboxValue[]>([])


    // 因是hook,必须写在组件的顶部执行,useSearchParams() 返回的是数组
    const [params] = useSearchParams();
    // 通过 get 方法获取目标参数
    const name = params.get("name") || "";
    const id = params.get("id") || "";


    useEffect(() => {
        if (name) {
            setTitle(name)
        }
    }, [name])

    useEffect(() => {
        if (id) {
            setShow(false);
            getProductBook({pro_line: id}).then((res: any) => {
                setShow(true);
                let _checkItems: CheckboxValue[] = [];
                const _list = res?.product_book?.map((item: any) => {
                    _checkItems.push(item?.id);
                    const _arr = item?.guide_book_file_info_?.[0]?.name?.split('.') || [];
                    return {
                        id: item?.id || '',
                        fileId: item?.guide_book_file_info_?.[0]?.fileId || '',
                        name: _arr?.[0] || '',
                        type: _arr?.[1] || '',
                    }
                }) || [];
                setList(_list)
                setCheckItems(_checkItems)
            }).catch((e: any) => {
                console.log('e', e)
                setShow(true);
                setList([])
            })
        }
    }, [id])

    const rightInfo = (
        <div className={'production-list_nav-right'}>
            <span
                className={'production-list_nav-right-info'}
                onClick={() => setShowBatch(true)}
            >批量操作</span>
        </div>
    )

    const checkboxChange = (value: CheckboxValue[]) => {
        setCheckValues(value)
    }

    // 假设这是你的API调用函数
    const fetchData = async (item: ListType) => {
        // 替换为你的实际API URL和请求逻辑
        const res = await getFilePreview(item?.fileId);
        return res;
    }


    const toDetail = async (ids: CheckboxValue[]) => {
        if (ids?.length) {
            let _arr = list?.filter((item: ListType) => ids?.includes(item?.id || '')) || [];
            // 创建一个promise数组,每个promise都是对API的一次调用
            const promises = _arr?.map((item: ListType) => fetchData(item));
            // 使用Promise.all来并行地解决这些promise
            Promise.all(promises)
                .then((results: any) => {
                    let sxPreViewList: ListType[] = _arr?.map((it: ListType, index: number) => {
                        return {
                            ...it,
                            url: results?.[index] || ''
                        }
                    })
                    localStorage.setItem('sxPreViewListStorage', JSON.stringify(sxPreViewList));
                    localStorage.setItem('sxListPath', `${location?.pathname}${location?.search}`);
                    navigate(`/production/detail?name=${sxPreViewList?.[0]?.name}`, { replace: true });
                })
                .catch((e: any) => {
                    console.log('e', e)
                    localStorage.setItem('sxPreViewListStorage', '');
                    localStorage.setItem('sxListPath', '');
                });
        } else {
            localStorage.setItem('sxPreViewListStorage', '');
            localStorage.setItem('sxListPath', '');
            Toast.show({
                content: '请先选择数据!',
                maskClassName: 'to-detail-mask',
            })
        }

    }

    return (
        <div className={'sxjx-content-main sxjx-layout-main-unfoot'}>
            <div className={`production-list ${showBatch ? 'production-list--batch' : ''}`}>
                <NavBar title={title} showBack={true} rightInfo={ !showBatch ? rightInfo : ''}
                        customBack={{onClick: () => {
                                const _url = '/production/management';
                                navigate(_url, { replace: true });
                       }}}
                />
                {
                    !show ? <SpinLoading color='primary'/> :
                        <div className={'production-list_list'}>
                            <Checkbox.Group
                                onChange={checkboxChange}
                                value={checkValues}
                            >
                                {
                                    list?.map((item: ListType) => {
                                        return <div
                                            key={item?.id}
                                            className={`production-list_list-item`}
                                            style={{backgroundColor: '#fff'}}
                                            onClick={() => {
                                                if (!showBatch) {
                                                    toDetail([item?.id || ''])
                                                }
                                            }}
                                        >
                                            <img className={'production-list_list-item-img'}
                                                 src={item?.type === 'mp4' ? _mp4 : _pdf}/>
                                            <div className={'omit2 production-list_list-item-name'}>
                                                {item?.name}
                                            </div>
                                            {
                                                showBatch ?  <Checkbox key={item?.id} value={item?.id} /> : ''
                                            }
                                        </div>
                                    })
                                }
                            </Checkbox.Group>


                        </div>
                }
                {
                    showBatch ? <div className={'production-list--batch_info'}>
                        <div className={'production-list--batch_info-top'}>
                            <Checkbox
                                indeterminate={checkValues.length > 0 && checkValues?.length < checkItems?.length}
                                checked={checkValues?.length === checkItems?.length}
                                onChange={checked => {
                                    console.log('checked', checked)
                                    if (checked) {
                                        setCheckValues(checkItems)
                                    } else {
                                        setCheckValues([])
                                    }
                                }}
                            >
                                全选
                            </Checkbox>
                            <div className={'production-list--batch_info-top-choose'}>已选择<span>{checkValues?.length}</span>条</div>
                            <div className={'production-list--batch_info-top-close'}
                                 onClick={() => {
                                     setShowBatch(false);
                                     setCheckValues([])
                                 }}
                            >取消</div>
                        </div>
                        <div className={'production-list--batch_info-bottom'}>
                            <div className={'production-list--batch_info-bottom_item'}
                                 onClick={() => {
                                     toDetail(checkValues)
                                 }}
                            >
                                <img className={'production-list--batch_info-bottom_item-icon'} src={_preview} alt=""/>
                                <span className={'production-list--batch_info-bottom_item-info'}>预览</span>
                            </div>
                        </div>
                    </div> : ''
                }

            </div>
        </div>
    )
}

export default ProductionList;