
import * as React from 'react';
import { Props, State } from './type';
import log from '../utils/lofter-log'
import LofterProductDefault from '../lofterProductDefault'
import LofterProductLarge from '../lofterProductLarge'
import { LofterTitle } from '../lofterTitle'
import {get} from '../utils/request'
import globalRequestProxy from '../utils/globalRequestProxy'
import * as Styled from './index.style'
import { BaseComponent } from '../base-component'
import { ProductItemType } from '../lofterProductLarge'

export const trackingClickEvent = (id:string) => {
  return new Promise((resolve) => {
    log.capture(`w2-14`, {
      category: 'market_shelfpage',
      action: 101,
      scene: 'cmsShelf',
      itemId: id,
      itemType: 'PRODUCT',
      useAppTrack: true
    },{
      callback: resolve
    })
  })
}
export class LofterProduct extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();

  static getDerivedStateFromProps (props, state) {
    let { productList } = state
    if(productList === null || props.isEdit){
      //productSearch_productList_excel是对老数据的兼容
      let { productSearch_productList_excel, productSearch_productList } = props
      productList = productSearch_productList.length == 0 && productSearch_productList_excel.length > 0 ? productSearch_productList_excel : productSearch_productList
      return {
        productList: productList || []
      }
    }
  }

  trackingExposureEvent(productId:string) {
    log.capture(`w2-13`, {
      useAppTrack: true,
      category: 'market_shelfpage',
      action: 0,
      scene: 'cmsShelf',
      itemId: productId,
      itemType: 'PRODUCT'
    })
  }

  initObserver() {
    const expThreshold = 0.1

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry:IntersectionObserverEntry) => {
        // console.log(entry.intersectionRatio);

        const data = (entry.target as HTMLDivElement).dataset
        if (!data.exposetime && entry.intersectionRatio >= expThreshold) {
          // console.log(entry.target,'记录时间',entry.time);
          entry.target.setAttribute('data-exposetime', entry.time+'')
        }
        if (
          data.exposetime &&
          (entry.time - parseInt(data.exposetime)) > 500 // 距离上一次显示时间大于500毫秒则上报
        ) {
          this.trackingExposureEvent(data.productid)
          // console.log(entry.target,'上报一次');
          delete (entry.target as HTMLDivElement).dataset.exposetime
        }
      })
    },{
      threshold:0.1,
    });
    Array.prototype.forEach.call(document.querySelectorAll('.tracking-item'),(item=>{
      observer.observe(item)
    }))

  }
  public componentDidMount() {
    !this.props.isEdit && this.initObserver()
    let { productList } = this.state
    let productIds = productList.map((product:ProductItemType) => product.productId).join(',')
    let url = '//www.lofter.com/market/cms/products.json'
    if(!this.props.isEdit){
      //组件中调用该方法发出的请求，会在全局聚合后再请求
      globalRequestProxy(url, 'productIds', productIds, (event) => {
        let urlKey = event.detail.url
        if(urlKey != url){
          return
        }
        let globalProductList = event.detail.responese.products || []
        let globalProducts = {}
        globalProductList.forEach(item => {
          globalProducts[item.productId] = item
        })
        let productListNew = []
        productList.forEach((product, index) => {
          let productInfo = globalProducts[product.productId]
          if(productInfo){
            productListNew.push({
              desc: product.desc,
              shop: product.shop,
              shopUrl: product.shopUrl,
              ...globalProducts[product.productId]
            })
          }
        })
        this.setState({
          productList: productListNew
        })
      })
    }
  }
  componentWillUnmount() {
    Array.prototype.forEach.call(document.querySelectorAll('.tracking-item'),(item=>{
      if(item.dataset.exposetime) { // 处理只触发一次observer cb的未上报商品
        this.trackingExposureEvent(item.productId)
      }
    }))
  }

  public render() {
    let { style, type, title, marginTop} = this.props
    let { productList } = this.state
    let firstProductIndex = 0

    //第一个有效商品的index
    for(let i = 0; i < 4; i++){
      if(productList[i] && productList[i].name){
        firstProductIndex = i
        break;
      }
    }


    return <Styled.ProductListContainer style={style}>
      <BaseComponent {...this.props}>
        <div className={marginTop && 'f-before'}>
          <div className="product-list-wrap" style={{marginTop: `${marginTop}rem`}}>
            <div className={`list-${type} list`}>
              {
                title &&
                <LofterTitle title={title}/>
              }
              {
                type == 4 ?
                productList.map((product:ProductItemType, index:number) =>
                  product.name ?
                  <div key={product.productId} className="product-item tracking-item" data-productid={product.productId}>
                  {
                    index == firstProductIndex ?
                    <LofterProductLarge product = {product}></LofterProductLarge> :
                    <LofterProductDefault product = {product} size= 'small'></LofterProductDefault>
                  }
                  </div> : null
                ) :
                type == 3 ?
                productList.map((product:ProductItemType) =>
                  product.name ?
                  <div key={product.productId} className="product-item tracking-item" data-productid={product.productId}>
                    <LofterProductDefault product = {product} size= 'small'></LofterProductDefault>
                  </div> : null
                ) :
                type == 2 ?
                productList.map((product:ProductItemType) =>
                  product.name ?
                  <div key={product.productId} className="product-item tracking-item" data-productid={product.productId}>
                    <LofterProductDefault product = {product}></LofterProductDefault>
                  </div> : null
                ) :
                type == 1 ?
                productList.map((product:ProductItemType) =>
                  product.name ?
                  <div key={product.productId} className="product-item-1 tracking-item" data-productid={product.productId}>
                    <LofterProductLarge product = {product}></LofterProductLarge>
                  </div> : null
                ) :
                null
              }
            </div>
          </div>
        </div>
      </BaseComponent>
    </Styled.ProductListContainer>
  }
}
