index.js 21.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
import Taro, {Component, login} 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 goYohoBuy from '../../assets/images/goYohoBuy@3x.png';
import goOnLine from '../../assets/images/goOnLine@3x.png';
import storeLocation from '../../assets/images/store-location@3x.png';
import router from '../../router/index.js';
const urlParse = require('url');
const queryString = require('querystring');
import getPrivateKey from '../../libs/request/getPrivateKey.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'
import { getQRCodeSource } from '../../libs/miniQRCodeRoute'
import Yas from '../../utils/yas';

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';

let yas;

@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: {},
            skup: '',
            storeId: -1,
            isLogin: false,
            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',
            'login-bg': '../../components/login/login-bg/login-bg'
        }
    }

    componentDidShow() {
        let that = this;
        let {id} = this.state;
        event.emit('judge-user-is-login', function () {}, function () {
            that.getFavoriteState(id);
        });
    }

    componentWillMount() {
        yas = new Yas(this.$scope);
        yas.pageOpenReport();
        let options = this.$router.params;
        if (options && options.q) {
          let url = decodeURIComponent(options.q);
          let urlObj = urlParse.parse(url);
          if (urlObj.host === 'o.yohobuy.com' && urlObj.pathname === '/ufo') {
            const queryObj = queryString.parse(urlObj.query);
            const p = queryObj.p;
            const storeArr = p.split(',') || [];
            const storeId = storeArr[1];
            if (queryObj.skup) {
              this.skupMustLogin(queryObj.skup, storeId);
            } else {
              this.loadElement({ id: queryObj.productId || queryObj.skn  });
            }
          }
        } else {
          if (options && options.scene) {
            let code = options.scene;
            getQRCodeSource(code).then(json => {
              if (json) {
                if (json.skup) {
                  this.skupMustLogin(json.skup, json.storeId);
                } else {
                  this.loadElement(json);
                }
              }
            })
              .catch(error => {
              });
          } else if(options.storeId && options.skup) {
            this.skupMustLogin(options.skup, options.storeId);
          }
          else {
            this.loadElement(options);
          }
        }
    }
    skupMustLogin(skup, storeId) {
      wx.hideShareMenu();
      this.setState({
        skup,
        storeId
      });
      // event.emit('user-is-login', () => {
      //   this.loadStoreProductInfo(skup, storeId);
      // }, () => {
      //   Taro.redirectTo({
      //     url: `/pages/productDetail/index?skup=${skup}&storeId=${storeId}`,
      //   });
      // });
      event.emit('judge-user-is-login', this.isLogined.bind(this), this.isLoginCallBack.bind(this, skup, storeId));
    }

    isLogined(isLogin) {
      this.setState({
        isLogin
      })
    }

    isLoginCallBack(skup, storeId) {
      this.loadStoreProductInfo(skup, storeId);
    }

    loginSuccess(isLogin) {
      this.setState({
        isLogin
      })
      let { skup, storeId } = this.state;
      this.loadStoreProductInfo(skup, storeId);
    }

    async loadStoreProductInfo(skup, storeId) {
      await getPrivateKey();
      productDetailModel.getStoreProductDetail(skup, storeId).then(res => {
        console.log(res);
        if (res && res.code === 200) {
          let data = res.data || {};
          let image_list = data.image_list;
          let goodsList = { image_list }
          let imageSize = image_list.length;
          let default_image = imageSize > 0 ? image_list[0] : '';
          let productInfo = data;
          let seriesObj = {
            text: '系列',
            value: data.series_name
          };
          seriesObj = data.series_name ? [seriesObj] : [];
          this.setState({
            productInfo,
            id: data.product_id,
            imageSize: imageSize,
            goodsList: goodsList,
            swiperNum: `1 | ${imageSize}`,
            productDec: [
              {
                text: '颜色',
                value: data.color_name
              }, {
                text: '尺码',
                value: data.size_name
              }, {
                text: '品牌',
                value: data.brand_name
              },
              ...seriesObj
              , {
                text: '发售时间',
                value: data.sale_time
              }, {
                text: '货号',
                value: data.product_code
              }, {
                text: '库存编号',
                value: data.skup
              }
            ]
          })
        }
      });
    }

    loadElement(options) {
        let productId = options.id

        if (options && options.scene && options.scene.length > 0) {
            var scene = decodeURIComponent(options.scene)
            var arr = scene ? scene.split("&") : [];
            console.log('============333333==================');
            console.log(scene);
            console.log(arr);
            console.log('============333333==================');

            if (arr.length == 1) {
                productId = scene;
            }
        }
        this.setState({
            id: productId
        });

        this.getProductData(productId);
        this.getRecommendGoods(productId);

        let that = this;
        event.one(SHARE_CANCEL, () => {
            that.onCancelSharesheetCallback();
        });
        event.one(SHARE_MOMENTS, () => {
            that.shareMomentsCallback();
        });
        event.one(SHARE_CANCEL_MOMENTS, () => {
            that.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
                }

                let seriesObj = {
                  text: '系列',
                  value: productInfo.series_name
                }
                seriesObj = productInfo.series_name ? [seriesObj]: []

                this.setState({
                    productInfo: productInfo,
                    imageSize: imageSize,
                    goodsList: goodsList,
                    swiperNum: `1 | ${imageSize}`,
                    snapshootShareData: shareData,
                    productDec: [
                        {
                            text: '颜色',
                            value: goodsList.color_name
                        }, {
                            text: '品牌',
                            value: productInfo.brand_name
                        },
                        ...seriesObj
                        , {
                            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) {
        if(!id){
          return;
        }
        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) {//添加收藏
            yas.report('YB_GDS_COLLECT_C', {PRD_ID: productId});
            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
                    });
                }
            });
        }
    }

    reportStoreId(storeId) {
        console.log(storeId);
        productDetailModel.storeIdLoginReport(storeId, 'OfflineStore').then(ret => {});
    }

    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);
    }

    confirmSelect(skup) {
      const params = {
        PRD_SKUP: skup
      };

      yas.report('YB_GDS_ADD_TO_CART_C', params);
    }

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

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

    onStoreBuyNow() {
      let { skup, productInfo, storeId } = this.state;
      event.emit('user-is-login', () => {
        this.judgeCanBuy(skup, productInfo, storeId);
      }, () => {
        this.judgeCanBuy(skup, productInfo, storeId);
      })
    }

    judgeCanBuy(skup, productInfo, storeId) {
      productDetailModel.createPaymentinfo(skup).then(data => {
        if (data && data.code === 200) {
          let { product_id } = productInfo;
          Taro.navigateTo({
            url: `/pages/order/orderConfirm/orderConfirm?is_store=1&skup=${skup}&product_id=${product_id}&store_id=${storeId}`,
          })
        } else {
          Taro.showToast({
            title: data.message,
            icon: 'none'
          })
        }
      }).catch(error => {
        Taro.showToast({
          title: error.message,
          icon: 'none'
        })
      })
    }

    goYohoBuyMinApp() {
        wx.navigateToMiniProgram({
          appId: 'wx084ab813d88c594b',
          success(res) {

          }
        })
    }

    goOnLineProuduct(id) {
      let params = {
        id
      }
      router.go('productDetail', params)
    }

    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);
        }
        event.removeAll('SHARE_FRIENDS');
        event.removeAll('SHARE_MOMENTS');
        event.removeAll('SHARE_CANCEL');
        event.removeAll('SHARE_CANCEL_MOMENTS');
    }

    render() {
        let {productInfo, recommendList, goodsList, productDec, id, skup, isLogin, storeId} = this.state;
        let imageList =  goodsList.image_list || [];
        let status = productInfo.status;
        let isShowLogin = !isLogin && storeId !== -1;
        
        return (
          <View>
            { !isShowLogin && (<View className="product-page">
                <View className="swiperNum">{this.swiperNum}</View>
                <Swiper className='product-swiper' autoplay onChange={this.onChangeSwiper}>
                    {
                        !skup && imageList.map((item, index) => {
                            return (
                                <SwiperItem key={index}>
                                    <Image src={getImgUrl(item.image_url, 750, 750)} class="swiper-img" mode="aspectFill"/>
                                </SwiperItem>
                            )
                        })
                    }
                    {
                        skup && imageList.map((item, index) => {
                            return (
                                <SwiperItem key={index}>
                                    <Image src={getImgUrl(item, 750, 750)} class="swiper-img" mode="aspectFill"/>
                                </SwiperItem>
                            )
                        })
                    }
                </Swiper>

                {
                  !skup && (<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>)
                }

                {
                  skup && (
                    <View className="product-ctr">
                      <View className="store-title">
                        <Image className="store-image" src={storeLocation}></Image>{productInfo.store_name}
                      </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={item.text==='发货时间' ? "value number" : "value"}>{item.value}</Text>
                            </View>
                        )
                    })
                }
                <View className={ skup ? "product-dec margin-bottom" : "product-dec"}>
                    正品保障<Text className="c"></Text> 专业鉴定<Text className="c"></Text> 银联担保
                </View>
                {
                  !skup && (<View className="recommend-goods">
                    <View className="title">相关推荐</View>
                    <ProductList list={recommendList}></ProductList>
                  </View>)
                }

                {
                  !skup && (<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>)
                }

                {
                  skup && status === 1 && (<View className="product-buy">
                    {/* <View className="sell-btn">出售</View> */}
                    <View className="buy-btn store-info" onClick={this.onStoreBuyNow.bind(this)}>店内闪购
                      {productInfo.price && <Text className="price">¥{productInfo.price}</Text>}
                    </View>
                  </View>)
                }

                {
                  skup && (status === 2 || status === 0) && (<View className="product-buy product-none-top">
                    {/* <View className="sell-btn">出售</View> */}
                    <View className="buy-btn disable">
                      { status === 2 ? '已售出' : ''}
                      { status === 0 ? '已下架' : '' }
                    </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} onConfirmSelect={this.confirmSelect.bind(this)}></SelectSize>
                }

                {
                  skup ? <Image className="goYohoBuy" onClick={this.goOnLineProuduct.bind(this, id)} src={goOnLine} mode="aspectFill" /> : <Image className="goYohoBuy" onClick={this.goYohoBuyMinApp.bind(this)} src={goYohoBuy} mode="aspectFill" />
                }
            </View>) 
            }
            {
              isShowLogin && (<login-bg catchtouchmove='true' onReportStoreId={this.reportStoreId.bind(this, storeId)} onLoginSuccess={this.loginSuccess}></login-bg>)
            }
          </View>
        )
    }
}