/* eslint-disable no-confusing-arrow */
/* eslint-disable react/jsx-indent */
/* eslint-disable indent */
/* eslint-disable complexity */
import React, { useMemo, useState, useEffect, useCallback, useRef } from 'react';
import './style';
import { Label, Popup, Toast, ScrollView } from 'cbkfe-ui';
import CommonHeader from '../CommonHeader';
import PackageContent from '../PackageContent';
import StoresMap from '../StoreMap';
import { isObject, isArray, browser, queryCode, scrollTo } from 'cbkfe-utils';
import { gd_getMapLocation, getLocation, mb_fullScreen, mb_open } from 'cbkfe-bridge';
import { requestStoreMapInfo, requestPackageInfo, requestPackagesByPage } from './action';
import CBKEmitter from '../events';

const params = queryCode('') || {};
const arrowIcon = 'https://static.caibeike.com/i/770142f0abdd06f8e0646efdc6eb275e-LHsYrR-AOwAOhp1';
const isApp = browser.parseUA.isApp;
const isAndroid = browser.versions.android;
const isWechat = browser.versions.wechat;
const isAmapApp = browser.parseUA.isAmapApp;


function openUrlWithAppend(url, selectedCount) {
    if (!url) {
        return;
    }
    if (!isObject(selectedCount) || !selectedCount.itemSkuId) {
        mb_open(url);
    } else {
        let appendStr = `&defaultId=${selectedCount.itemSkuId}`;
        mb_open(url + (isApp ? encodeURIComponent(appendStr) : appendStr));
    }
}
// 权益说明的样式
function PackageDescription({ title, list, only }) {
    return isArray(list, true) ? <div className={`cbkfe-cardPackages-description cbkfe-cardPackages-description--${only ? 'only' : ''}`}>
        <div className="package-description-title">{title}</div>
        {list.map(item => <p key={item} className="package-description-li">· {item}</p>)}
    </div> : null;
}
// 菜单模块
function PackageMenu({ info, hideHeader }) {
    return <div>
        <PackageContent Header={hideHeader ? null : () => {
            return <CommonHeader title={info.packageTitle || ''} hideLine={true} label={info.packageSubTitle || ''} />;
        }} info={{
            packageType: info.packageType,
            infos: info.allPackageContents,
            comments: info.comments,
            type: 'vouchers'
        }}>
            {isArray(info.rightsComments, true) && <PackageDescription only={!isArray(info.allPackageContents, true) && !isArray(info.comments, true)} title="权益说明" list={info.rightsComments} />}
        </PackageContent>

    </div>;
}

function PackageContentModal({ onClose, showModal, itemSpuCode, selectedCount }) {
    const [info, setInfo] = useState(null);
    const [_show, setShow] = useState(false);

    useEffect(() => {
        const m = async () => {
            if (!info && showModal) {
                const info = await requestPackageInfo({ ...params, ...{ itemSpuCode }}).catch(e => {
                    Toast.info(e.message || '系统异常');
                });
                setInfo(info);
            }
            setShow(showModal);
        };
        m();
    }, [showModal, info, itemSpuCode]);

    if (!info) { return null }
    return <Popup
        scrollId="card-modal-content"
        contentClass="cbkfe-packageInfoCard-popup"
        type="middle"
        show={_show}
        onBackClick={onClose}
    >
        <div className="package-card-modal">
            <div className="card-modal-header">
                <img className="modal-header-image" src={info.imageUrl} />
                <div className="modal-header-titles">
                    <p className="modal-header-brandTitle">
                        {info.brandTitle}
                        <img onClick={onClose} className="modal-header-closeIcon" src="https://static.caibeike.com/i/f368d525c182b8ff6aeeff437dad5da6-lZ1hxr-fAwfAhp1" /></p>
                    <p className="modal-header-packageTitle">{info.packageTitle || ''}</p>
                </div>
            </div>
            <div id="card-modal-content" className="card-modal-content">
                <PackageMenu info={info} hideHeader={true} />
            </div>
            <div className={`${info.packageType === 'food' ? 'card-modal-footer--food' : 'card-modal-footer--park'}`}>
                <div
                    dot-event-name="spk_page_locamod_click"
                    dot-pv-name="spk_page_locamod_pv"
                    data-item_id={params.dealCode}
                    data-item_code={info.itemSpuCode}
                    onClick={() => {
                        onClose();
                        let url = info.packageDetailUrl;
                        if (location.pathname.indexOf('/preview/') >= 0 && url) { // 如果链接中是预览模式
                            url = url.replace('/package/detail', '/package/preview/detail');
                        }
                        url && openUrlWithAppend(url, selectedCount);
                    }} className="card-modal-btn">查看详情</div>
            </div>
        </div>
    </Popup>;
}

// 原通兑券列表
function CardPackage({ info = {}, index, selectedCount }) {
    const [_info, updateInfo] = useState(info);
    const [showPackageDetail, setShowPackageDetail] = useState('');
    useEffect(() => {
        info !== _info && isObject(info, true) && updateInfo(info);
    }, [info, _info]);

    return useMemo(() => {
        const isNoAppoint = _info.appointType === 2;

        return <div
            dot-pv-name="spk_page_loca_pv"
            dot-event-name="spk_page_loca_click"
            data-item_id={params.dealCode}
            data-item_code={_info.itemSpuCode}
            data-index={index}
            onClick={(e) => {
                let url = _info.packageDetailUrl;
                if (location.pathname.indexOf('/preview/') >= 0 && url) { // 如果链接中是预览模式
                    url = url.replace('/package/detail', '/package/preview/detail');
                }
                url && openUrlWithAppend(url, selectedCount);
            }} className={`cbkfe-card-package ${_info.boutique ? 'package-image--boutique' : ''}`}>
            {/* 支持不同 tag 添加_info.iconUrl, _info.iconUrl 与 _info.boutique 为互斥关系, 为兼容之前的 tag,  _info.boutique 为 true 将使用之前的 tag  */}
            {!_info.boutique && _info.iconUrl && (<img src={_info.iconUrl} className="package-image--TagIconUrl" />)}
            <div className={`package-image-container ${isNoAppoint && 'package-image--noAppoint'} `}>
                <img className={`package-image ${isNoAppoint ? 'package-image--noAppoint' : ''}`} src={_info.imageUrl} />
            </div>
            <div className="package-info">
                <div className="package-info-title">
                    <span className="package-title-text">
                        {_info.brandTitle}
                    </span>
                    {_info.distanceTitle && <span className="package-info-distance">{_info.distanceTitle}</span>}
                </div>
                <div className="package-info-subTitle">
                    <span
                        dot-event-name="spk_page_locaco_click"
                        data-item_id={params.dealCode}
                        data-item_code={_info.itemSpuCode}
                        data-index={index}
                        className="package-info-content"
                        onClick={(e) => {
                            // 关闭套餐内容弹窗模块
                            // e.preventDefault();
                            // e.stopPropagation();
                            // setShowPackageDetail('sm');
                        }}>
                        <span className="package-subTitle">{_info.itemSkuTitle}</span>
                        {/* <img className="package-title-icon" src={arrowIcon} /> */}
                    </span>
                    {_info.consumeText && <span className="package-consumeText">{_info.consumeText}</span>}
                </div>
                {_info.firstCanAppointDay ? <div className="package-info-firstCanAppointDay">
                    <div className="package-info-firstCanAppointDayText">{_info.firstCanAppointDay}</div>
                    {/* <span className="package-info-firstCanAppointDayDistance">{_info.distanceTitle}</span> */}
                </div> : null}
                <div className="package-info-item">
                    {isArray(_info.properties, true) && <div className="cardPackage-item__desc">
                        {_info.properties.map((text, index) => <span className="cardPackage-item__descItem" key={text + index} >{text}</span>)}
                    </div>}
                    {/* 消耗次数  */}
                    {/* {
                        _info.consumeText && <div className="package-info-consumption-count">
                            <div className="package-info-consumption-count-box">
                                <div className="package-info-consumption-count-box__left">
                                    <img className="package-info-consumption-count-box__left__icon" src="https://static.caibeike.com/i/c2e29202fde6766a19407254b1de0b90-n8lxtx-AMwbghp1" />
                                </div>
                                <div className="package-info-consumption-count-box__right">{_info.consumeText}</div>
                            </div>
                        </div>
                    } */}
                    {/* {isArray(_info.properties, true) && _info.distanceTitle && !_info.firstCanAppointDay ? <span className="package-distance">{_info.distanceTitle}</span> : null} */}
                </div>


                {isArray(_info.tags, true) && <div className="cardPackage-item__labels">
                    {_info.tags.map((text, index) => <Label value={text} key={index} labelClassName="cbkfe-label-cardPackages" valueClassName="label-value-cardPackages" type="primary" className="cardPackage-item__label" />)}
                </div>}
            </div>
            {(_info.verifyNum || isObject(_info.dealTravel)) && <div className={`package-exprience package-exprience--${!isObject(_info.dealTravel) ? 'white' : ''}`}>
                {isObject(_info.dealTravel) && isArray(_info.dealTravel.headImages, true)
                    && _info.dealTravel.headImages.map((travelImg, index) =>
                        <img key={index} src={travelImg} className="package-exprience-travelImg" />
                    )}
                {isObject(_info.dealTravel) && _info.dealTravel.travelNum
                    ? <span className="package-exprience-travelNum">{_info.dealTravel.travelNum}位体验师推荐</span>
                    : <span className="package-exprience-travelNum"></span>}
                {_info.verifyNum && <span className="package-verify">{_info.verifyNum}</span>}

            </div>}
            {/*
                注意：不要去掉 showPackageDetail，添加 showPackageDetail 原因如下
                原因：是避免list 中 item 下的 PackageContentModal 在某个城市点击弹出弹窗之后在切换到另一个城市下点击时弹出弹窗时，弹窗内容一前一个城市的对应 index 的弹窗内容一致  
                不确定 PackageContentModal 组件中的逻辑用途，所以通过 showPackageDetail 控制
            */}
            {showPackageDetail && <PackageContentModal
                showModal={showPackageDetail}
                itemSpuCode={_info.itemSpuCode}
                selectedCount={selectedCount}
                onClose={() => {
                    setShowPackageDetail('');
                }}
            />
            }
        </div>;
    }, [_info, showPackageDetail, index, selectedCount]);
}

// 酒店通兑券列表 2022-05-10
function HotelCardPackage({ info = {}, index, selectedCount, isSelsct = false, checked = false, onChange }) {
    const [_info, updateInfo] = useState(info);
    const [showPackageDetail, setShowPackageDetail] = useState('');

    useEffect(() => {
        info !== _info && isObject(info, true) && updateInfo(info);
    }, [info, _info]);

    const selectChange = (e) => {
        e.preventDefault();
        e.stopPropagation();
        onChange && typeof onChange === 'function' && onChange(!checked, _info);
    };

    const toUrl = (e, _info) => {
        e.preventDefault();
        e.stopPropagation();
        let url = _info.packageDetailUrl;
        if (location.pathname.indexOf('/preview/') >= 0 && url) { // 如果链接中是预览模式
            url = url.replace('/package/detail', '/package/preview/detail');
        }
        url && openUrlWithAppend(url, selectedCount);
    };

    return useMemo(() => {
        return <div className="cbkfe-hotelcard-package">
            <div className={`package-image-container`} onClick={(e) => toUrl(e, _info)}>
                <img className={`package-image`} src={_info.imageUrl} />
                {_info.iconUrl ? <img className={`package-imgicon`} src={_info.iconUrl} /> : null}
            </div>
            <div className="package-info" onClick={(e) => isSelsct ? selectChange(e) : toUrl(e, _info)}>
                <div className="package-info-headers">
                    <div className="package-info-aisde">
                        <div className="package-info-title" onClick={(e) => toUrl(e, _info)}>
                            <span className="package-title-text">{_info.brandTitle}</span>
                            {isSelsct ? <i className="iconfont icon--arrow" /> : null}
                        </div>
                        <div className="package-info-subTitle">
                            <span className="package-info-content">
                                <span className="package-subTitle">
                                    {_info.hotelPriceDesc ? <i>{_info.hotelPriceDesc}</i> : null}
                                    {_info.itemSkuTitle}
                                </span>
                            </span>
                        </div>
                    </div>
                    {isSelsct ? (
                         <div className="package-info-checked" onClick={(e) => selectChange(e)}>
                            <span className={`package-info-checked ${checked ? 'checked' : ''}`}></span>
                        </div>
                    ) : null}
                </div>
                {_info.firstCanAppointDay || _info.consumeText ? (
                    <div className="package-info-firstCanAppointDay">
                        {_info.firstCanAppointDay && <div className="package-info-firstCanAppointDayText">{_info.firstCanAppointDay}</div>}
                        {_info.consumeText && <div className="package-info-firstCanAppointNo">{_info.consumeText}</div>}
                    </div>
                ) : null}
                {_info.hotelRankingDesc ? (
                    <div className="package-info-zzb" onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        if (_info.hotelRankingUrl) {
                            mb_open(_info.hotelRankingUrl);
                        }
                    }}>
                        <span className="package-info-zzbText">{_info.hotelRankingDesc}</span>
                    </div>
                ) : (
                    <React.Fragment>
                         {isArray(_info.tags, true) || (isObject(_info.dealTravel) && _info.dealTravel.travelNum) ? (
                            <div className="cardPackage-item__labels">
                                {isObject(_info.dealTravel) && _info.dealTravel.travelNum
                                    ? <span className="cardPackage-item__firetlabel">{_info.dealTravel.travelNum}位体验师推荐</span>
                                    : isObject(_info.dealTravel) && _info.dealTravel.hotelRecommendedDesc ? <span className="cardPackage-item__firetlabel">{_info.dealTravel.hotelRecommendedDesc}人种草</span> : null
                                }
                                {isArray(_info.tags, true) && _info.tags.map((text, index) => <Label value={text} key={index} labelClassName="cbkfe-label-cardPackages" valueClassName="label-value-cardPackages" type="primary" className="cardPackage-item__label" />)}
                            </div>
                        ) : null}
                    </React.Fragment>
                )}
            </div>

            {/*
                注意：不要去掉 showPackageDetail，添加 showPackageDetail 原因如下
                原因：是避免list 中 item 下的 PackageContentModal 在某个城市点击弹出弹窗之后在切换到另一个城市下点击时弹出弹窗时，弹窗内容一前一个城市的对应 index 的弹窗内容一致  
                不确定 PackageContentModal 组件中的逻辑用途，所以通过 showPackageDetail 控制
            */}
            {showPackageDetail && <PackageContentModal
                showModal={showPackageDetail}
                itemSpuCode={_info.itemSpuCode}
                selectedCount={selectedCount}
                onClose={() => {
                    setShowPackageDetail('');
                }}
            />
            }
        </div>;
    }, [_info, showPackageDetail, isSelsct, checked, index, selectedCount]);
}

// 选择城市弹窗
function SwitchCity({ visible, cityList, defaultCity, headerRef, updateSwitchCityVisible, updateCurrChooseCity, }) {
    const contentRef = useRef(null);
    const [init, setInit] = useState(false);// 默认展示defaultCity

    const handleCity = useCallback((city) => {
        if (defaultCity !== city.cityId) {
            if (isObject(city, true)) { // 如果city有值，就执行请求数据操作 ,切换数据
                updateCurrChooseCity(city);
            }
        }
    }, [updateCurrChooseCity]);


    useEffect(() => {
        const close = () => {
            updateSwitchCityVisible(false);
        };
        CBKEmitter.addListener('closePackagesBack', close);
        return function () {
            CBKEmitter.removeEventListener('closePackagesBack');
        };
    }, [updateSwitchCityVisible]);

    useEffect(() => {
        if (visible && headerRef.current && contentRef.current) {
            const rect = headerRef.current.getBoundingClientRect();  // 方法返回元素的大小及其相对于视口的位置。
            if (rect.top > 0) {
                const scroll = (barHeight) => {
                    const moveDom = document.querySelector('.cbkfe-card-packages');
                    const height = barHeight + 1; // +1 是为了滑动等时候不要把导航弄出来
                    new scrollTo().scrollTo({
                        positionY: moveDom.offsetTop - height,
                        duration: 200
                    });
                };
                isApp ? mb_fullScreen({
                    isFull: true, interval: 0, success: (result) => {
                        scroll(result && result.barHeight || (isAndroid ? 74 : 64));
                    }
                }) : scroll(0);
            }
        }
    }, [visible, headerRef]);

    useEffect(() => {
        let _current = contentRef.current;
        const swiperDom = document.querySelector('.package-switchCity-scroll');// 滚动区域
        const swiperContentDom = document.querySelector('.package-switchCity-touch');// 滚动区域父容器
        const swiperDomHeight = swiperDom.offsetHeight;
        const windowHeight = window.innerHeight;
        if (swiperDomHeight / windowHeight > 0.6) {
            swiperContentDom.style.height = '100%';
        } else {
            swiperContentDom.style.height = swiperDomHeight + 'px';
        }



        let isDocument = true;
        const move1 = function (e) {
            if (isDocument) {
                e.stopPropagation();
                e.preventDefault();
            }
        };
        const move2 = function (e) {
            e.stopPropagation();
        };

        const start1 = function (e) {
            e.stopPropagation();
            isDocument = true;
        };
        const start2 = function (e) {
            e.stopPropagation();
            isDocument = _current.clientHeight >= document.querySelector('.package-switchCity-scroll').offsetHeight;
        };

        if (visible && _current) {
            document.addEventListener('touchmove', move1, { passive: false });
            document.addEventListener('touchstart', start1, { passive: false });
            _current.addEventListener('touchmove', move2, { passive: true });
            _current.addEventListener('touchstart', start2, { passive: true });
            !init && new ScrollView('.package-switchCity-content', {
                useTransition: true,
                preventDefault: true,
                // 是否有惯性缓冲动画
                scrollY: true,
                momentum: true,
                // 超出边界时候是否还能拖动
                bounce: true,
                // 超出边界还原时间点
                bounceTime: 300,
                disableMouse: true,
                disablePointer: true,
                // 超出边界返回的动画
                bounceEasing: 'circular',
                bindToWrapper: true,
                deceleration: 0.01, // 默认0.006
                click: true,
            });
            setInit(true);
        }
        return function () {
            if (visible && _current) {
                document.removeEventListener('touchmove', move1, { passive: false });
                document.removeEventListener('touchstart', start1, { passive: false });
                _current.removeEventListener('touchmove', move2);
                _current.removeEventListener('touchstart', start2, { passive: true });
                _current = null;
            }
        };
    }, [visible, init]);
    return useMemo(() => {
        return <div
            onClick={(e) => {
                e.stopPropagation();
                e.preventDefault();
                updateSwitchCityVisible(false);
                CBKEmitter.emit('cardTemplatePackagesVisibleChange', false);
            }}
            className={`cbkfe-package-switchCity cbkfe-package-switchCity--${visible ? 'visible' : 'hidden'}`}>
            <div ref={contentRef} className="package-switchCity-touch">
                {/* <div className="package-switchCity-touch2"> */}
                <div className="package-switchCity-content" >
                    <div className=" package-switchCity-scroll">
                        {isArray(cityList, true) && cityList.map((city, index) => <div
                            key={index}
                            onClick={() => handleCity(city)}
                            className={`package-switchCity-city package-switchCity-city--${defaultCity === city.cityId ? 'active' : ''} `}>
                            {city.cityName}({city.storeNum})
                        </div>)}
                        {isArray(cityList, true) && <div className="package-switchCity-scroll-bottom"></div>}
                    </div>

                    {/* </div> */}
                </div>
            </div>
        </div>;
    }, [visible, contentRef, cityList, handleCity, updateSwitchCityVisible]);
}

export default function CardPackages({ list = [], limit = 30, title = '', storeNum = 0, className, storesInfo = {}, selectedCount, children, anchorName, cityList, grouonNo, combineType, storeNumDesc, itemPackagesTypeDesc, isShowStorePackage = true, isShowHotel = false }) {

    const resolveListByFoldStatus = function (list, foldBtnStatus) {
        if (!isArray(list, true)) return [];
        if (foldBtnStatus) {
            return list.slice(0, limit);
        }
        return [...list];
    };

    const [_list, updateList] = useState(resolveListByFoldStatus(list, list.length > limit));
    const [cacheList, updateCacheList] = useState(list);
    const [_storesInfo, updateStoresInfo] = useState(storesInfo);
    const [type] = useState('all');
    const [selfLat, setSelfLat] = useState({});
    const [switchCityVisible, updateSwitchCityVisible] = useState(false);
    const [currCity, updateCurrChooseCity] = useState({
        cityName: '选城市',
        cityId: ''
    });
    // 折叠按钮的初始化，如果大于limit个就展示，如果小于等于limit就不展示更多按钮
    const [foldBtnStatus, updateFoldBtnStatus] = useState(cacheList.length > limit);
    const [foldBtnVisible, updateFolbBtnVisible] = useState(cacheList.length > limit);
    const headerRef = useRef(null);
    const [isRelative, updateIsRelative] = useState(false);
    const [_storeNum, updateStoreNum] = useState('');
    const [isTouch, updataIsTouch] = useState(true);
    const moreBtnRef = useRef(null);

    useEffect(() => {
        // app 和 微信环境
        (isApp || isWechat || isAmapApp) && getLocation('all',)
            .then(headers => {
                headers = headers || {};
                if (!isObject(headers, true)) {
                    return null;
                }
                setSelfLat(headers);
                return requestStoreMapInfo(params, headers);  // 获取附近门店信息
            })
            .then(data => {
                data && updateStoresInfo(data);
            });
    }, []);

    useEffect(() => {
        // updateList(resolveListByFoldStatus(list));
    }, [list]);

    useEffect(() => {
        storeNum && updateStoreNum(storeNum);
    }, [storeNum]);

    useEffect(() => {
        if (_storesInfo !== storesInfo && isObject(storesInfo, true)) { updateStoresInfo(storesInfo) }
    }, [storesInfo, _storesInfo]);

    // 点击附近或者城市按钮切换
    const changeType = useCallback((type) => {
        if (type === 'local') {
            const scroll = (barHeight) => {
                const moveDom = document.querySelector('.cbkfe-storeMap-content');
                const height = barHeight + 44;
                new scrollTo().scrollTo({
                    positionY: moveDom.offsetTop - height
                });
            };
            isApp ? mb_fullScreen({
                isFull: true, interval: 0, success: (result) => {
                    scroll(result && result.barHeight || (isAndroid ? 74 : 64));
                }
            }) : scroll(0);
        }
    }, []);

    // 选择城市
    const chooseCity = useCallback((type) => {
        setTimeout(() => {
            updataIsTouch(true);
        }, 500);

        if (type === 'local') {
            updateSwitchCityVisible(false);
            CBKEmitter.emit('cardTemplatePackagesVisibleChange', false);
            setTimeout(() => {
                updateIsRelative(false);
            }, 200);
        } else {
            updateSwitchCityVisible(!switchCityVisible);// 展示切换城市组件
            CBKEmitter.emit('cardTemplatePackagesVisibleChange', !switchCityVisible);
            !switchCityVisible // 关闭遮盖层弹窗的时候延时0.2秒切换position
                ? updateIsRelative(!switchCityVisible)// 切换position
                : setTimeout(() => {
                    updateIsRelative(false);
                }, 200);
        }
    }, [switchCityVisible]);

    const beforeChangeCity = useCallback((nextCity) => {
        let nextCityName = nextCity.cityName === '全部' ? '选城市' : nextCity.cityName;
        if (currCity.cityName !== nextCityName) {
            chooseCity('chooseCity');
            updataIsTouch(false);
            requestPackagesByPage({ ...params, start: 0, limit: 9999, cityId: nextCity.cityId }, selfLat).then(data => {
                if (!data || !isArray(data.result, true)) {
                    return;
                }
                let newList = data.result;
                updateFolbBtnVisible(newList.length > 30);
                updateFoldBtnStatus(newList.length > 30);
                updateList(resolveListByFoldStatus(newList, newList.length > 30));
                updateCacheList(newList);
                updateCurrChooseCity(nextCity);
            });

        }
    }, [currCity.cityName, limit, resolveListByFoldStatus]);

    const showMorePackageHandle = function () {

        if (foldBtnStatus) {
            updateList(cacheList);
        } else {
            updateList(cacheList.slice(0, limit));
            if (moreBtnRef && moreBtnRef.current) {
                let timer = setTimeout(() => {
                    const scroll = (barHeight) => {
                        const moveDom = document.querySelector('.cbkfe-card-packages');
                        const height = barHeight + 1; // +1 是为了滑动等时候不要把导航弄出来
                        new scrollTo().scrollTo({
                            positionY: moveDom.offsetTop - height,
                            duration: 200
                        });
                    };
                    isApp ? mb_fullScreen({
                        isFull: true, interval: 0, success: (result) => {
                            scroll(result && result.barHeight || (isAndroid ? 74 : 64));
                        }
                    }) : scroll(0);
                    clearTimeout(timer);
                }, 0);
            }
        }
        updateFoldBtnStatus(!foldBtnStatus);
    };

    if (!isArray(_list, true)) {
        return null;
    }

    return <div className={`cbkfe-card-packages ${className}`}>
        <div ref={headerRef}>
            <CommonHeader
                handleClick={() => { }}
                classname="card-packages-header"
                title={<div className="card-packages-btns-layout">
                    <span className={`${isAndroid ? 'comment-title' : ''}`}>{title}</span>
                    {(_storeNum && combineType !== 2) && <span className="card-packages-titleLabel">
                        <span className={`card-packages-labelCount card-packages-labelCount--${browser.versions.android ? 'android' : 'ios'}`}>{_storeNum}</span>{storeNumDesc || '家门店可选'}
                    </span>}
                </div>}
                // combineType === 2时为组合券，组合券不展示还有几家门店，以及“选城市”“附近”
                rightText={
                    combineType !== 2 &&
                    <div className="card-packages-btns card-packages-btns-layout">
                        {/* <span onClick={chooseCity} >上海</span> */}
                        {isArray(cityList, true) && <div
                            onClick={() => {
                                isTouch && chooseCity();
                                updataIsTouch(false);
                            }}
                            className="card-packages-btn card-packages-btn--normal text-layout "
                        > <div className={`text-over ${currCity.cityName === '选城市' ? 'text-no-choose ' : ''}`}>{currCity.cityName}</div>
                            <i className={`iconfont icon--arrow ${switchCityVisible ? 'iconfont-up' : 'iconfont-down'}
                            ${currCity.cityName === '选城市' ? 'text-no-choose ' : ''}
                                `}></i>
                        </div>}
                        {(isObject(_storesInfo, true) && isArray(_storesInfo.stores, true)) && <div
                            dot-event-name="spk_page_ner_click"
                            data-item_id={params.dealCode}
                            onClick={() => { chooseCity('local'); setTimeout(() => { changeType('local') }, 300) }}
                            className={`card-packages-btn ${type === 'local' ? 'card-packages-btn--active' : ''}`}>
                            附近</div>}
                    </div>
                }
            />
        </div>
        {/* 如果页面offsetTop的父元素使用了relative，那么其参照就是这个父元素。所以需要获取距离页面顶部的距离的时候，把position改为static */}
        <div className={`card-packages-content ${isRelative ? 'card-packages-content-relative' : 'card-packages-content-normal'}`} >
            <SwitchCity
                anchorName={anchorName}
                headerRef={headerRef}
                visible={switchCityVisible}
                defaultCity={currCity.cityId}
                cityList={cityList}
                updateSwitchCityVisible={updateSwitchCityVisible}
                updateCurrChooseCity={beforeChangeCity}
                updateStoreNum={updateStoreNum}
                grouonNo={grouonNo}
                selfLat={selfLat}
                _list={_list}
                updateList={updateList}
            />
            <div style={{ overflow: 'visible', position: 'relative' }}>
                {_list.map((info, index) => {
                    if (isShowHotel) {
                        return <HotelCardPackage selectedCount={selectedCount} index={index} info={info} key={index} />;
                    } else {
                        return <CardPackage selectedCount={selectedCount} index={index} info={info} key={index} />;
                    }
                })}
                {foldBtnVisible && <div className="packages-moreBtn-container">
                    {foldBtnStatus && <div ref={moreBtnRef} onClick={showMorePackageHandle} className={`packages__moreBtnShow`}>
                        {`查看更多${cacheList.length - limit}种${itemPackagesTypeDesc}`}
                        <i className="iconfont icon--arrow--down" />
                    </div>}
                </div>}
            </div>
            {foldBtnVisible && <div className="packages-moreBtn-container">
                {!foldBtnStatus && <div ref={moreBtnRef} onClick={showMorePackageHandle} className={`card-packages__moreBtn card-packages__moreBtn--${foldBtnStatus}`}>
                    {'收起'}
                    <i className="iconfont icon--arrow--down" />
                </div>}
            </div>}
            {((isObject(_storesInfo, true) && combineType !== 2 && isShowStorePackage)) && <div
                dot-pv-name="spk_page_map_pv"
                dot-event-name="spk_page_map_click"
                data-item_id={params.dealCode}
                style={{ marginTop: foldBtnVisible ? '1rem' : '0' }}
            >
                <StoresMap
                    kilometers={_storesInfo.kilometers}
                    shoptext={_storesInfo.nearbyTitle}
                    shopinfo={_storesInfo.stores}
                    mapUrl={_storesInfo.mapUrl}
                    selflng={selfLat['x-app-lng']}
                    selflat={selfLat['x-app-lat']}
                    storeProps={{
                        'dot-pv-name': 'spk_page_shp_pv',
                        'dot-event-name': 'spk_page_shp_click',
                        'data-item_id': params.dealCode
                    }}
                />
            </div>}
            {children}
        </div>

    </div >;
}

CardPackages.CardPackageItem = CardPackage;
CardPackages.CardPackageHotel = HotelCardPackage;

