import * as React from 'react'
import { LofterTitle } from '../lofterTitle'
import log from '../utils/lofter-log'
import { BaseComponent } from '../base-component'
import { imgResize } from '../utils/imgResize'
import { showMessage } from '../common/toast/toast';
import LazyLoad from 'react-lazy-load'
import debounce from 'lodash.debounce';
import { get, post } from '../utils/request'
import { genSpmLink } from '../utils/statistics'

import {
  Props,
  State
} from './type'

import * as Styled from './index.style'

enum StatusMap {
  立即领取,
  已领取
}

export class LofterProductCoupon extends React.Component<Props, State> {
  static defaultProps = new Props();
  
  state = new State()

  getCoupon = async(shelfData: any) => {
    const couponsIdList:any = []
    shelfData.filter((shelf: any) => { 
      if (shelf.couponsId && shelf.productId) {
        couponsIdList.push(shelf.couponsId) 
      }
    })
    // 固定新人礼包-第三天接口，后期再换成通用的
    if (this.props.type === 2) {
      const mockUrl = 'https://nei.hz.netease.com/api/apimock-v2/c6da9202198a943efec7f11c8a937f16/newweb/giftPacks/receiveStatus.json?itemId=&itemType='
      const url = '//www.lofter.com/newweb/giftPacks/receiveStatus.json'
      let res = await get(url, {
        itemId: couponsIdList.join(','),
        itemType: 2
      })
      if (res.code === 0) {
        this.setState({
          statusList: res.data.receiveStatus
        })
        const { statusList } = this.state
        for (let i = 0; i < statusList.length; i++) {
          this.props.shelfData.map((shelf: any) => {
            if (typeof shelf.status === "undefined" && statusList[i]?.itemId === Number(shelf?.couponsId)) {
              shelf.status = statusList[i].status
            }
          })
        }
        this.forceUpdate();
        return res.data.peripheralProducts;
      }
      else return null;
    }
  }

  initData = () => {
    if (this.props.shelfData) {
      this.getCoupon(this.props.shelfData);
    }
  }
  componentDidMount() {
    this.initData();
  }

  postReceive = debounce(async (productId: number, couponId: number, attrGroupId: number, index: number, link: string, e) => {
    e.stopPropagation();
    if (this.props.type === 2) {
      const mockUrl = 'https://nei.hz.netease.com/api/apimock-v2/c6da9202198a943efec7f11c8a937f16/newweb/giftPacks/receive.json'
      const url = '//www.lofter.com/newweb/giftPacks/receive.json'
      post(url, {
        type: 2,
        id: couponId,
        productId
      }).then(res => {
        if (res.code !== 0) {
          return showMessage(res.msg)
        }
        if (res.data.res) {
          if (this.props.type === 2) {
            log.capture(`newusergift-6`, {
              category: 'newusergift',
              action: 101,
              scene: 'newusergift',
              v: '1.0.0',
              coupon_id: couponId,
              activityId: 'newusergif'
            })
          }
          showMessage('商品兑换券已经发放至市集账户，请在期限内进行兑换哦！')
          this.props.shelfData[index].status = 1
          this.forceUpdate()
          setTimeout(() => {
            if (link) {
              return window.location.href = link;
            }
            return window.location.href = `https://www.lofter.com/market/fe/html/directTrade.html?productId=${productId}&attrGroupId=${attrGroupId}&num=1`
          }, 1800)
        } else {
          showMessage('商品库存不足，等待补货中');
        }
      })
    }
  }, 1000, {
    leading: true,
    tailing: false,
  })

   seeMoreActProduct = (productId: number) => {
    const spmLink = genSpmLink({url: `https://www.lofter.com/market/fe/html/product.html?productId=${productId}&njb_navigator=false`, name: 'spmCmspageProduct'})
    setTimeout(() => {
      location.href = spmLink;
    }, 200)
  }

  render() {
    let { style, marginTop, title, shelfData} = this.props

    return <Styled.productCouponListContainer style={style}>
      <BaseComponent {...this.props}>
        <div className={marginTop && 'f-before'}>
          {
            title &&
            <LofterTitle title={title}/>
          }
          <div className="product-list-wrap" style={{marginTop: `${marginTop}rem`}}>
            <div className="list">
              {
                shelfData && shelfData.map((shelf:any, index: number) =>
                  <div 
                    key={index} 
                    className="product-item" 
                    data-productid={shelf.productId}
                    onClick={this.seeMoreActProduct.bind(this, shelf.productId)}
                  >
                    <Styled.ProductCouponContainer>
                      <div className='content'>
                        <LazyLoad className="imgwrap" offsetVertical={900}>
                          <img src={imgResize(shelf.productImage ? shelf.productImage.url : '',750,750,1,true)} />
                          {/* <img src={imgResize(productImage.url,750,750,1,true)} /> */}
                        </LazyLoad>
                        <p className='name'>{shelf.name}</p>
                        {
                          shelf.status !== undefined ? (
                            <button
                              className={`button ${shelf.status === 1 ? 'disabled' : ''}`}
                              style={{backgroundColor: `${shelf.status === 1 ? '' : shelf.reciveColor}`, borderColor: `${shelf.status === 1 ? '' : shelf.reciveColor}`}}
                              onClick={this.postReceive.bind(this, shelf.productId, shelf.couponsId, shelf.attrGroupId, index, shelf.link)}
                              disabled={shelf.status === 1}
                            >
                              {StatusMap[shelf.status]}
                            </button>
                          ) : (
                            <button
                            className='button'
                            style={{backgroundColor: `${shelf.reciveColor}`, borderColor: `${shelf.status === 1 ? '' : shelf.reciveColor}`}}
                            onClick={this.postReceive.bind(this, shelf.productId, shelf.couponsId, shelf.attrGroupId, index, shelf.link)}
                          >
                            {StatusMap[0]}
                            </button>
                          )
                        }
                      </div>
                    </Styled.ProductCouponContainer>
                  </div>
                )
              }
            </div>
          </div>
        </div>
      </BaseComponent>
    </Styled.productCouponListContainer>
  }
}