import * as React from 'react';
import { Props, State } from './type';
import * as Styled from './index.style';
import {get, post} from '../utils/request';
import {rem} from '../style/function.style';
import {showMessage} from '../common/toast/toast';
import { getCouponData4Show, getPreferentialText } from '../utils/couponFormat'
import { redirectToLogin } from '../utils/login'
import { LofterTitle } from '../lofterTitle'
import { genSpmLink } from '../utils/statistics'
import throttle from '../utils/throttle';
import { BaseComponent } from '../base-component'

const isOnline = location.host === 'du.163.com';
const couponPageUrl = '//www.lofter.com/market/fe/html/couponProducts.html?couponId='
const textMap = {
  'has-own':'已领取',
  'empty-stock':'已抢完 '
}
export class LofterCoupon extends React.Component<Props, State> {
  static defaultProps = new Props();
  state = new State();
  componentDidMount(){
    const ids = this.props.coupons ? this.props.coupons.map(coupon => coupon.id).join(',') : ''
    const url = `//www.lofter.com/market/cms/coupons.json?couponIds=${ids}`
    get(url).then(res => {
      this.setState({
        couponsList: res.list
      })
      this.state.couponsList && this.state.couponsList.forEach(item=>{
        return this.state.btnStatusMap.set(item.couponId || item.id, item.userHasCoupon ? 'has-own' : '')
      })
      this.forceUpdate()
    })
  }

  private render1Column(coupon, index) {
    const couponshow = getCouponData4Show(coupon, 0)
    const styleColor = this.props.styleColor || 'red';
    const fontColor = this.props.fontColor || 'white';
    let statusType = this.state.btnStatusMap.get(couponshow.couponId)
    const text = statusType ? textMap[statusType] : `领 取`
    return (
      <Styled.Item1Coupon
        key={index}
        className={index % 3 === 2 && 'num-3th'}
        onClick={() => {}}
        styleColor={styleColor}
        fontColor={fontColor}
      >
        <div className="lpart">
          <div className="facevalue">{couponshow.facevalue}</div>
          <div className="doorsill">{couponshow.doorsill}</div>
        </div>
        <div className="mpart">
          <div className="top-circle"></div>
          <div className="line"></div>
          <div className="bottom-circle"></div>
        </div>
        <div className="rpart">
          <h4 className="ttl">{couponshow.name}</h4>
          <div className="validterm">有效期:{couponshow.startTime}至{couponshow.endTime}</div>
          <a className="pdlink" href="javascript:void(0);">查看更多活动商品
            <svg className="go-to-icon" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="10" cy="10" r="9.25" stroke={this.props.fontColor} strokeWidth="1.5"/>
              <path d="M9 6C11.3431 8.34315 13 10 13 10L9 14" stroke={this.props.fontColor} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </a>
          <a className="pdlink-hover" onClick={this.seeMoreActProduct.bind(this, couponshow.couponId)} href="javascript:void(0);"></a>
          <a className={`getbtn ${statusType? 'unable' : ''}`} href="javascript:void(0);" onClick={this.getCouponThrottle.bind(this, couponshow.couponId)}>{text}</a>
        </div>
      </Styled.Item1Coupon>
    )
  }

  private render2Column(coupon, index) {
    const couponshow = getCouponData4Show(coupon, 0)
    const styleColor = this.props.styleColor || 'red';
    const fontColor = this.props.fontColor || 'white';
    let statusType = this.state.btnStatusMap.get(couponshow.couponId)
    const text = statusType ? textMap[statusType] : `领取`
    return (
      <Styled.Item2Coupon
        key={index}
        className={index % 2 === 1 && 'num-2th'}
        onClick={this.seeMoreActProduct.bind(this, couponshow.couponId)}
        styleColor={styleColor}
        fontColor={fontColor}
      >
        <div className="part">
          <div className="facevalue">{couponshow.facevalue}</div>
          <div className="doorsill">{couponshow.doorsill}</div>
        </div>
        <div className="title">{couponshow.name}</div>
        <div className="divide">
          <div className="left-circle"></div>
          <div className="line"></div>
          <div className="right-circle"></div>
        </div>
        <div className="bottom">
          <div className={`getbtn ${statusType? 'unable' : ''}`} onClick={this.getCouponThrottle.bind(this, couponshow.couponId)}>{text}</div>
          <div className="border"></div>
          <a className="link" href="javascript:void(0);"><span>查看</span></a>
        </div>
      </Styled.Item2Coupon>
    )
  }

  private render3Column(coupon, index) {
    const couponshow = getCouponData4Show(coupon, 0)
    const styleColor = this.props.styleColor || 'red';
    const fontColor = this.props.fontColor || 'white';
    let statusType = this.state.btnStatusMap.get(couponshow.couponId)
    const text = statusType ? textMap[statusType] : `领取`
    return (
      <Styled.Item3Coupon
        key={index}
        className={index % 3 === 2 && 'num-3th'}
        onClick={this.seeMoreActProduct.bind(this, couponshow.couponId)}
        styleColor={styleColor}
        fontColor={fontColor}
      >
        <div className="facevalue">{couponshow.facevalue}</div>
        <div className="doorsill">{couponshow.doorsill}</div>
        <div className="title">{couponshow.name}</div>
        <div className="divide">
          <div className="left-circle"></div>
          <div className="line"></div>
          <div className="right-circle"></div>
        </div>
        <div className="bottom">
          <div className={`getbtn ${statusType? 'unable' : ''}`} onClick={this.getCouponThrottle.bind(this, couponshow.couponId)}>{text}</div>
          <div className="border"></div>
          <a className="link" href="javascript:void(0);"><span>查看</span></a>
        </div>
      </Styled.Item3Coupon>
    )
  }
  private setBtnStatus(couponId,status){
    this.setState((preState)=>{
      preState.btnStatusMap.set(couponId,status)
      return {
        btnStatusMap:preState.btnStatusMap
      }
    })
  }
  private getCoupon(couponId,e){
    console.log(this.state.btnStatusMap);
    e.stopPropagation();
    if(!!this.state.btnStatusMap.get(couponId)){
      return showMessage({text:'重复领取～(°ー°〃)'});
    }
    console.log(couponId);
    if (this.props.activeType === 2) {
      post('//www.lofter.com/newweb/giftPacks/receive.json', {
        type: 3,
        id: couponId,
      }).then(res => {
        if (res.code !== 0) {
          return showMessage(res.msg)
        }
        if (res.data.res) {
          this.setBtnStatus(couponId,'has-own')
          showMessage({text:'领取成功～o(*≧▽≦)o'});
        } else {
          showMessage('商品库存不足，等待补货中');
        }
      }).catch(error => {
        showMessage({text:'出了点小错，请重试～(°ー°〃) '})
      })
      return
    }
    post('//www.lofter.com/market/coupon/fetch.json', {
      couponId: couponId
    }).then(resp => {
      if (resp.code === 401) {
        redirectToLogin()
      } else if (resp.code === 200) {
        this.setBtnStatus(couponId,'has-own')
        showMessage({text:'领取成功～o(*≧▽≦)o'});
      } else {
        if(resp.code === -240){ // 领过
          this.setBtnStatus(couponId,'has-own')
        }
        if(resp.code === -251){ // 领完
          this.setBtnStatus(couponId,'empty-stock')
        }
        showMessage({text:`${resp.msg}～(°ー°〃)`})
      }
    }).catch(error => {
      showMessage({text:'出了点小错，请重试～(°ー°〃) '})
    })
  }
  private getCouponThrottle = throttle(this.getCoupon,1000);

  private seeMoreActProduct(couponId, e){
    const spmLink = genSpmLink({url: `${couponPageUrl}${couponId}`, name: 'spmCmspageCoupon'})
    setTimeout(() => {
      location.href = spmLink;
    }, 200)
  }
  public render() {
    // console.log('render', this.props, this.state);
    const {style, color, title, coupons=[], type, isEdit, marginTop} = this.props;

    return (  
      <Styled.Container style={style} className={marginTop > 0 && 'f-before'}>
        <BaseComponent {...this.props}>
          <Styled.Inner style={{marginTop: `${marginTop}rem`}}>
          {
            title &&
            <LofterTitle title={title}/>
          }
            <Styled.ColumnBox
              onTouchStart={() => {}}
              onClick={() => {}}
            >
              {coupons.map((coupon, index) => (
                this[`render${type}Column`](coupon, index)
              ))}
            </Styled.ColumnBox>
          {
            (!coupons || coupons && coupons.length == 0 )&& isEdit && <div>lofter优惠券模块</div>
          }
          </Styled.Inner>
        </BaseComponent>
      </Styled.Container>
    )
  }
}
