index.js 12.2 KB
import Taro, {Component} from '@tarojs/taro';
import {View, Swiper, SwiperItem, Image} from '@tarojs/components';
import {productDetail as productDetailModel} from '../../models';
import {getImgUrl} from '../../utils';
import {ProductList, SelectSize} from '../../components';
import { connect } from '@tarojs/redux';
import { showSizeBox, showSharesheet, showSnapshot } from '../../actions/productDetail'
import config from '../../config.js'


import share from '../../static/images/share.png';
import collect from '../../static/images/collect.png';
import collectOff from '../../static/images/collect-off.png';
import './index.scss';
import event from '../../utils/event'

const SHARE_FRIENDS = 'user-share-friends';
const SHARE_MOMENTS = 'user-share-moments';
const SHARE_CANCEL = 'user-canel-share';
const SHARE_CANCEL_MOMENTS = 'user-canel-share-moments';

@connect(({ productDetail }) => ({
    productDetail
}), (dispatch) => ({
    showSizeBox (isShow) {
        dispatch(showSizeBox(isShow))
    },
    showSharesheet (isShow) {
        dispatch(showSharesheet(isShow))
    },
    showSnapshot (isShow) {
        dispatch(showSnapshot(isShow))
    }
}))

export default class ProductDetail extends Component {
    constructor() {
        this.state = {
            id: '',
            productInfo: {},
            goodsList: {},
            swiperNum: '1 | 1',
            recommendList: [],
            collectTitle: '收藏',
            isFavorite: false,
            snapshootShareData: {},
            productDec: {
                color: {
                    text: '颜色',
                    value: ''
                },
                brand: {
                    text: '品牌',
                    value: ''
                },
                series: {
                    text: '系列',
                    value: ''
                },
                saleTime: {
                    text: '发货时间',
                    value: ''
                },
                productCode: {
                    text: '货号',
                    value: ''
                }
            }
        };
    }

    config = {
        usingComponents: {
            'share-sheet' : '../../components/shareSheet/shareSheet',
            'snapshoot-share' : '../../components/shareSheet/snapshootShare/snapshootShare'
        }
    }
    componentDidMount() {
        let id = this.$router.params.id;

        this.setState({
            id: id
        });

        this.getProductData(id);
        this.getRecommendGoods(id);
        this.getFavoriteState(id);

        event.on(SHARE_CANCEL, () => {
            this.onCancelSharesheetCallback();
        });
        event.on(SHARE_MOMENTS, () => {
            this.shareMomentsCallback();
        });
        event.on(SHARE_CANCEL_MOMENTS, () => {
            this.hiddenSnaphotSheet();
        });
    }

    getProductData(id) {
        productDetailModel.getProductData(id).then(ret => {
            if (ret && ret.code === 200) {
                let data = ret.data || {};
                let productInfo = data && data.product_info || {};
                let goodsList = productInfo.goods_list && productInfo.goods_list.length > 0 && productInfo.goods_list[0] || {};
                let imageSize = goodsList.image_list.length;      
                let default_image = imageSize > 0 ? goodsList.image_list[0]['image_url'] : '';
                var product_qrCode = ''
               
                let param = {
                    id: productInfo.product_id
                }   
                product_qrCode = config.domains.yohoApi + '/wechat/miniapp/img-check.jpg?param=' + encodeURIComponent(JSON.stringify(param)) + '&miniQrType=23&miniapp_type=63';

                console.log('====================================');
                console.log(product_qrCode);
                console.log('====================================');

                var shareData = {
                    product_name : productInfo.product_name,
                    product_price: '¥'+productInfo.max_price,
                    product_mprice: (productInfo.min_price === '0' || productInfo.max_price == productInfo.min_price ? '0' : '¥' + productInfo.min_price),
                    default_image,
                    product_qrCode,
                    product_skn: productInfo.product_id
                }
                
                this.setState({
                    productInfo: productInfo,
                    imageSize: imageSize,
                    goodsList: goodsList,
                    swiperNum: `1 | ${imageSize}`,
                    snapshootShareData: shareData,
                    productDec: [
                        {
                            text: '颜色',
                            value: goodsList.color_name
                        }, {
                            text: '品牌',
                            value: productInfo.brand_name
                        }, {
                            text: '系列',
                            value: productInfo.series_name
                        }, {
                            text: '发货时间',
                            value: productInfo.sale_time
                        }, {
                            text: '货号',
                            value: productInfo.product_code
                        }
                    ]
                });
            }
        });
    }

    getRecommendGoods(id) {
        productDetailModel.getRecommendGoods(id).then(ret => {
            if (ret && ret.code === 200) {
                this.setState({
                    recommendList: ret.data && ret.data.product_list
                });
            }
        });
    }

    getFavoriteState(id) {
        productDetailModel.getFavoriteState(id).then(ret => {
            if (ret && ret.code === 200) {
                this.setState({
                    isFavorite: ret.data,
                    collectTitle: ret.data ? '已收藏' : '收藏'
                });
            }
        });
    }
    
    onChangeSwiper(e) {
        this.setState(prevState => ({
            swiperNum: `${e.detail.current + 1} | ${prevState.imageSize}`
        }));
    }

    onClickCollect(id, e) {
        let {isFavorite} = this.state;
        let that = this;
        isFavorite = !isFavorite;

        event.emit('user-is-login',function () {
            that.handleCollectAction(id, isFavorite);
        },function () {
            that.handleCollectAction(id, isFavorite);
        })
    }
    
    handleCollectAction(productId, isFavorite) {
        if (isFavorite) {//添加收藏
            productDetailModel.addFavorite(productId).then(ret => {
                if (ret && ret.code === 200) {
                    this.setState({
                        collectTitle: '已收藏',
                        isFavorite: true
                    });
                }
            });
        } else {//取消收藏
            productDetailModel.cancelFavorite(productId).then(ret => {
                if (ret && ret.code === 200) {
                    this.setState({
                        collectTitle: '收藏',
                        isFavorite: false
                    });
                }
            });
        }
    }

    onShareAppMessage(res) {
        console.log(res);
        
        if (res.from === 'menu') {
            // 用户点击右上角分享
            return {
              title: '', // 分享标题
              desc: '', // 分享描述
              path: '',
              imageUrl: '',
              success: function() {},
              fail: function() {}
            };
          } else if (res.from === 'button') {
            // 用户点击分享按钮
            return {
              title: '', // 分享标题
              desc: '', // 分享描述
              path: '',
              imageUrl: '',
              success: function() {},
              fail: function() {}
            };
          }
    }

    //点击分享按钮
    onClickShare(id, e) {
        let {showSharesheet} = this.props;
        showSharesheet(true);
    }

    //点击组件的取消回调处理
    onCancelSharesheetCallback() {
        let {showSharesheet} = this.props;
        showSharesheet(false);
    }

    //点击组件的分享朋友圈回调
    shareMomentsCallback() {
        let {showSnapshot} = this.props;
        showSnapshot(true);
    }

    //取消分享朋友圈回调
    hiddenSnaphotSheet() {
        let {showSnapshot} = this.props;
        showSnapshot(false);
    }

    onClickBuy() {
        let {showSizeBox} = this.props;

        event.emit('user-is-login',function () {
          showSizeBox(true);
        },function () {
          showSizeBox(true);
        })
    }

    componentWillUnmount() {
        if (this.props.productDetail.showSharesheet) {
            this.onCancelSharesheetCallback();
        }

        if (this.props.productDetail.showSnapshot) {
            this.hiddenSnaphotSheet();
        }

        if (this.props.productDetail.showSizeBox) {
            let {showSizeBox} = this.props;
            showSizeBox(false);
        }
    }

    render() {
        let {productInfo, recommendList, goodsList, productDec, id} = this.state;
        let imageList =  goodsList.image_list || [];

        return (
            <View className="product-page">
                <View className="swiperNum">{this.swiperNum}</View>
                <Swiper className='product-swiper' autoplay onChange={this.onChangeSwiper}>
                    {
                        imageList.map((item, index) => {
                            return (
                                <SwiperItem key={index}>
                                    <Image src={getImgUrl(item.image_url, 750, 750)} class="swiper-img" mode="aspectFill"/>
                                </SwiperItem>
                            )
                        })
                    }
                </Swiper>

                <View className="product-ctr">
                    <View className="collect" onClick={this.onClickCollect.bind(this, id)}>
                        <Image src={isFavorite ? collect : collectOff} className="collect-icon"/>
                        <Text className="text">{collectTitle}</Text>
                    </View>
                    <View className="share" onClick={this.onClickShare.bind(this, id)}>
                        <Image src={share} className="share-icon"/>
                        <Text className="text">分享</Text>
                    </View>
                </View>

                <View className="product-name">{productInfo.product_name}</View>

                {
                    productDec.map(item => {
                        return (
                            <View className="product-info" key={item.text}>
                                <Text className="lable">{item.text}</Text>
                                <Text className="value">{item.value}</Text>
                            </View>
                        )
                    })
                }

                <View className="product-dec">
                    正品保障<Text className="c"></Text>专业鉴定<Text className="c"></Text>银联担保
                </View>

                <View className="recommend-goods">
                    <View className="title">相关推荐</View>
                    <ProductList list={recommendList}></ProductList>
                </View>

                <View className="product-buy">
                    {/* <View className="sell-btn">出售</View> */}
                    <View className="buy-btn" onClick={this.onClickBuy}>购买
                      { productInfo.least_price && <Text className="price">¥{productInfo.least_price}</Text>}
                    </View>
                </View>

                {
                    this.props.productDetail.showSharesheet &&
                    <share-sheet></share-sheet>
                }

                {
                    this.props.productDetail.showSnapshot &&
                    <snapshoot-share isShow={this.props.productDetail.showSnapshot} shareData={snapshootShareData} bindhiddenSnaphotSheet='hiddenSnaphotSheet'></snapshoot-share>   
                }

                {
                    this.props.productDetail.showSizeBox &&
                    <SelectSize sizeList={goodsList.size_list} product_id={id}></SelectSize>
                }
            </View>
        )
    }
}