import * as React from 'react';
import { Props, State } from './type';
import * as Styled from './index.style';
import SaleRechargeItem from './saleRechargeItem';
import CountDown from '../common/countDown/index';
import {get, post} from './request';
import {initWxShare} from './wx-share';
import {loggerCors} from './logger';
import localParam from '../utils/localParam';
import getOffsetTop from '../utils/getOffsetTop';
import linearScrollTo from '../utils/linearScrollTo';
import NumberUtils from '../utils/numberUtils';
import Marquee from '../common/marquee/Marquee';

const RECHARGE_TYPE = {
  WX_JSAPI: 'WX_JSAPI',
  WX_NATIVE: 'WX_NATIVE',
  ALIPAY: 'ALIPAY'
}

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

  public constructor(props) {
    super(props);
    const urlData = localParam();
    const {targetUrl, shareUrl, ..._siteInfo} = urlData;
    this.siteInfo = {..._siteInfo, site: decodeURIComponent(_siteInfo.site)};
    this.targetUrl = urlData.targetUrl;
    this.originUrl = decodeURIComponent(shareUrl);
    this.kuxuanRootPath = this.getRootPath(this.originUrl);
    sessionStorage.setItem('N_recharge_rootPath', this.kuxuanRootPath);
    this.shareUrl = `${location.origin}/share/redirect.do?targetUrl=${shareUrl}`;

    this.activityId = urlData.actId;
    this.configWxShare();
  }

  /**
 * 获得根路径：http协议? + hostname
 */
public getRootPath(url){
    let rootPath;
    const urlArr = url.split('/');
    if (url.indexOf('://') > -1) {
        rootPath = `${urlArr[0]}//${urlArr[2]}`;
    }
    else {
        [rootPath] = urlArr;
    }
    return rootPath;
}

  public configWxShare() {
      initWxShare({
          shareData: {
              title: '充值特惠',
              link: this.shareUrl,
              desc: '充值福利来啦~数量有限，先到先得哦！'
          },
          reqParams: {
              siteId: this.siteInfo.siteId
          },
          shareAble: true
      });
  }

  public formatDate(totalMs) {
      if(isNaN(parseInt(totalMs))) return'';
      let _date = new Date(parseInt(totalMs));
      return `${_date.getFullYear()}年${_date.getMonth() + 1}月${_date.getDate()}日${_date.getHours()}:${NumberUtils.padLeft(_date.getMinutes(), 2)}`
  }

  public handleRuleClick(){
    loggerCors({dot: 'pthd-2', message: {id: this.siteInfo.userId, activityId: this.activityId}}, this.siteInfo);
    linearScrollTo(getOffsetTop(this.rulerRef, document.body));
  }

  public composeParams(params={}) {
    return {...this.siteInfo, ...params}
  }

  public componentWillReceiveProps(props) {
    props.novelfestival_activityKey && props.novelfestival_activityKey != this.props.novelfestival_activityKey && this.getFestival(props)
    !props.isEdit && props.backgroundColor && props.backgroundColor != this.props.backgroundColor && (document.body.style.backgroundColor = props.backgroundColor)
  }

  public componentDidMount(){
    this.props.novelfestival_activityKey && this.getFestival(this.props)
    if(!this.props.isEdit){
      this.props.backgroundColor && (document.body.style.backgroundColor = this.props.backgroundColor)
      loggerCors({dot: 'pthd-1', message: {id: this.siteInfo.userId, activityId: this.activityId}}, this.siteInfo);
      setTimeout(() => {
          location.replace(this.originUrl);
      }, 290000); //290秒后重刷页面
    }
  }

  public getFestival(props){
    const url = `http://${localParam().host || 'pay.wending.yuedu.163.com'}/festival/get.json?akey=${props.novelfestival_activityKey}`
    const questUrl = this.props.isEdit && location.protocol == 'http:' ? `${url}` :
      this.props.isEdit && location.protocol == 'https:' ?
      `/proxy/commonProxy?url=${encodeURIComponent(url)}` :
      `/recharge/activity/${this.siteInfo.userId}/show.json`;
    const param =  this.props.isEdit ? {} : this.composeParams({akey: this.activityId});
    get(questUrl, param)
      .then((res) => {
        let now = new Date().getTime();
        const { activity } = res.activityInfo;
        const { startTime, endTime } = activity || {};
        //代理自定义页面title
        document.title != activity.name && (document.title = activity.name);
        this.setState({
          activityInfo: activity,
          productList: res.productList,
          startTime,
          endTime,
          hasStart: now >= startTime,
          hasEnd: now > endTime
        })
      })
  }

  public render() {
    const {productList, startTime, endTime, hasStart, hasEnd} = this.state;
    const {targetUrl, siteInfo, kuxuanRootPath} = this;
    const isEmpty = hasStart && productList && productList.length === 0;
    let rules = this.state.activityInfo.rules ? this.state.activityInfo.rules.replace(new RegExp('\n', "gm"), '<br/>') : '';
    let kefuHtml = `<a class="link-qiyu" href="${kuxuanRootPath}/route/kefu.do" data-log=${JSON.stringify({dot:"hd6-2"})}>在线客服</a>`;
    rules = rules ? rules.replace('${contact}', kefuHtml) : '';
    const countDownLeft = (document.documentElement.getBoundingClientRect().width - 1145)/2 + 380;

    const { backgroundColor, backgroundImage, isBackgroundImageRepeat, ruleColor, ruleButColor, isEdit} = this.props;
    return (
      <Styled.Container
        ref={(ref)=>{this.containerRef = ref}}
        id={this.props.instanceKey}
        style={{
          ...this.props.style,
          backgroundColor: backgroundColor,
          backgroundImage: backgroundImage ? `url(${backgroundImage.url})` : 'unset',
          backgroundRepeat: isBackgroundImageRepeat ? 'repeat' : 'no-repeat'
        }}>
        {
          productList ?
          <div>
            <div style={{left: isEdit ?  `${countDownLeft}px` : 0}} className={isEdit ? "is-edit count-down-wrap" : "count-down-wrap"}>
              {hasStart && !hasEnd && (<CountDown startTime={this.state.startTime} endTime={this.state.endTime}/>)}
              {!hasStart && (<Marquee className="m-notice" textList={[`活动尚未开始，活动时间为${this.formatDate(startTime)}~${this.formatDate(endTime)}，敬请期待哦~`]}/>)}
              {hasEnd && (<Marquee className="m-notice" textList={['活动已结束，敬请期待下次活动哦。若有疑问，请联系客服咨询。']}/>)}
            </div>

            {isEmpty ? (<div className="m-header empty" style={{color: ruleColor}}>
                <p>抱歉，活动名额已抢完<br/>敬请期待下次活动</p>
            </div>) : (<div className="m-header">
              <a className="btn-rule" href="javascript:;" onClick={this.handleRuleClick.bind(this)} style={{color: ruleButColor}}>活动规则 <span className="gt">›</span></a>
            </div>)}

            <div>
              <SaleRechargeItem
                config={{ hasStart: this.state.hasStart, hasEnd: this.state.hasEnd }}
                rechargeItem={{ type: RECHARGE_TYPE.WX_JSAPI }}
                rechargeProductMap={productList}
                targetUrl={targetUrl}
                siteInfo={{...siteInfo, kuxuanRootPath}}
                parentProps={this.props}
                activityId={this.activityId}
              />
            </div>
            {
            rules &&
            <Styled.Rules ref={ref=>{this.rulerRef = ref}} style={{color: ruleColor}}>
              <div className="title">活动规则</div>
              <div dangerouslySetInnerHTML={{ __html: rules }}>
              </div>
            </Styled.Rules>
            }
          </div> :
          <div>{!isEdit ? '' : '小说分站平台活动'}</div>
        }
      </Styled.Container>
    )
  }
}
