import * as React from 'react';
import { isLofter, ios, isUpAppVersion } from 'nw-detect';
import { openAppLofter } from 'nw-app-lofter';
import { post } from '../utils/request';
import { Props, State } from './type';
import * as Styled from './style'
import { formatFullDate } from '../utils/format';
import { appNavigate } from '../utils/navigate';
import { showMessage } from '../common/toast/toast'
import { Tabs, TabPane } from '../common/tabs';
import HairH from '../common/hair-h';
import { formatImage } from '../utils/imgResize';
import log from '../utils/lofter-log'
import localParam from '../utils/localParam';

declare global {
  interface Window { 
    webkit: any;
    OMTAjax: any;
  }
}

const urlData = localParam();

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

  goActivity(item: any) {
    if (item.canGo && item.status === 0 || item.status === 1) {
      let url = `https://www.lofter.com/market/fe/html/cardHome.html?activityCode=${item.activityCode}`;
      if (item.fullscreen) {
        url += '&njb_navigator=false';
      }
      if (urlData.adTrace) {
        url += `&adTrace=${urlData.adTrace}`
      }
      appNavigate(url);
    }
  }

  doAppoint(item: any, event: React.MouseEvent<HTMLElement>) {
    event.stopPropagation();
    if (item.noticeFlag) return;
    if (!isLofter()){
      openAppLofter({
        path: 'webview',
        query: {
          url: location.href
        }
      })
      return;
    }
    post('//www.lofter.com/market/card/activity/addNotice.json', {
      activityCode: item.activityCode,
    }, null, 'json').then(res => {
      if (res.code === 200) {
        this.refreshData();
        showMessage('预约成功')
      } else {
        showMessage(res.msg)
      }
    }).catch(error => {
      console.log('Add notice error', error);
      showMessage('活动太火爆了，请稍后重试~')
    })
  }

  checkHookStatus = () => {
    if (isLofter() && ios()) {
      const hasHybirdBridge = window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.hybirdBridge;
      if (!window.OMTAjax) {
        log.capture('card-group-1', {
          action: '0',
          activityId: 'marketFront',
          method: 'get',
        })
      }
      if (!hasHybirdBridge) {
        log.capture('card-group-2', {
          action: '0',
          activityId: 'marketFront',
          method: 'get',
        })
      }
      if (!window.OMTAjax && !hasHybirdBridge) {
        log.capture('card-group-3', {
          action: '0',
          activityId: 'marketFront',
          method: 'get',
        })
      }
    }
  }
  
  refreshData() {
    const { isEdit, activityList_productList } = this.props;
    const activityCodes = activityList_productList.map(item => item.activityCode);
    const timer = setTimeout(() => {
      showMessage('网络较差或活动数据请求失败，请稍后重试~')
    }, 1500);
    this.checkHookStatus();
    post('//www.lofter.com/market/card/activity/getNoticeActivityInfos.json', activityCodes, null, 'json').then(res => {
      clearTimeout(timer);
      if (res.code === 200) {
        const serverActivityList = res.data.activityInfos;
        if (serverActivityList && serverActivityList.length) {
          this.setState({
            serverActivityList,
          })
        } else {
          // activityList长度为0的情况
          if (isLofter() && ios()) {
            log.capture('card-group-4', {
              action: '0',
              activityId: 'marketFront',
              method: 'get',
            })
          }
          showMessage('活动太火爆了，请稍后重试~~~');
        }
      } else {
        // code不为200的情况，大概率为iOS端post body丢失
        if (isLofter() && ios()) {
          log.capture('card-group-5', {
            action: '0',
            activityId: 'marketFront',
            method: 'get',
          })
          if (isUpAppVersion('7.1.6')) {
            log.capture('card-group-6', {
              action: '0',
              activityId: 'marketFront',
              method: 'get',
            })
          }
        }
        showMessage('活动太火爆了，请稍后重试~~');
      }
    }, error => {
      clearTimeout(timer);
      console.log('Get activity error', error);
      showMessage('活动太火爆了，请稍后重试~');
    })
  }

  onSearch = (e: React.SyntheticEvent) => {
    e.preventDefault();
    console.log('onsearch', this.state.searchValue);
  }

  matchSearch = (item: any) => {
    const { searchValue } = this.state;
    const { name, description } = item;
    if (!searchValue) return true;
    return name.indexOf(searchValue) > -1 || description.indexOf(searchValue) > -1;
  }

  componentDidMount() {
    this.refreshData();
  }

  public render() {
    const { activityList_productList, backgroundColor, topOffset, showFooter, isEdit, tab } = this.props;
    const { serverActivityList } = this.state
    // console.log('activityList', activityList_productList, serverActivityList);
    let newActivityList = activityList_productList;
    // activityList_productList为window.data或者编辑器内store存储的数据
    // serverActivityList为组件mount后发起的最新数据请求
    // 当卡牌后台配置卡牌数据更新后，activityList_productList的数据就比serverActivityList旧，需要遍历后用后者更新前者的item
    if (serverActivityList.length) {
      newActivityList = activityList_productList.map(storeItem => {
        const serverItem = serverActivityList.find((item: any) => item.activityCode === storeItem.activityCode);
        if (serverItem) {
          return {
            ...storeItem,
            ...serverItem,
          }
        }
        // 编辑器新增activiCode后，activityList_productList会增加一项，而本组件只在mount后请求一次服务端最新数据
        // 所以新增的item会匹配不到serverActivityList的数据，直接返回即可
        return storeItem
      })
    }
    // console.log('newActivityList', newActivityList);
    return (
      <Styled.CardGroupContainer backgroundColor={backgroundColor} topOffset={topOffset}>
        <form className="search" onSubmit={this.onSearch}>
          <input className="search-input" type="text" placeholder="请输入想要搜索的元气赏名称" onChange={e => { this.setState({
            searchValue: e.target.value
          }) }} />
          <button className="search-btn">搜索</button>
          <HairH />
        </form>
        <Styled.Group>
          <Tabs defaultValue="ing" value={isEdit ? tab : undefined} navHeight={54} itemHeight={44} activeColor="#2E2E2E">
            <TabPane value="ing" title="火热进行中">
              <ul className="list">
                {
                  newActivityList.filter(item => item.status === 1 && this.matchSearch(item)).map((item, index) => {
                    return (
                      <li
                        className="item" 
                        key={item.activityCode} 
                        onClick={this.goActivity.bind(this, item)}
                      >
                        <div 
                          className="cover" 
                          style={{ backgroundImage: `url(${formatImage(item.verticalImage, {
                            width: 339,
                            height: 312,
                            crop: true,
                          })})`}}
                        >
                          {
                            item.status === -1 && (
                              <div className="mask">
                                <div className="text">已结束</div>
                              </div>
                            )
                          }
                          {
                            item.status === 0 && <div className="time">{formatFullDate(parseInt(item.startTime), false)}开售</div>
                          }
                        </div>
                        <div className="info">
                          <div className="name">{item.name}</div>
                          <div className="desc">{item.description}</div>
                          <div className="detail">
                            <span className="price">¥{item.minPrice}</span>
                          </div>
                        </div>
                      </li>
                    )
                  })
                }
              </ul>
            </TabPane>
            <TabPane value="pre" title="待开启">
              <ul className="list">
                {
                  newActivityList.filter(item => item.status === 0 && this.matchSearch(item)).map((item, index) => {
                    return (
                      <li
                        className="item" 
                        key={item.activityCode} 
                        onClick={this.goActivity.bind(this, item)}
                      >
                        <div 
                          className="cover" 
                          style={{ backgroundImage: `url(${formatImage(item.verticalImage, {
                            width: 339,
                            height: 312,
                            crop: true,
                          })})`}}
                        >
                          {
                            item.status === -1 && (
                              <div className="mask">
                                <div className="text">已结束</div>
                              </div>
                            )
                          }
                          {
                            item.status === 0 && <div className="time">{formatFullDate(parseInt(item.startTime), false)}开售</div>
                          }
                        </div>
                        <div className="info">
                          <div className="name">{item.name}</div>
                          <div className="desc">{item.description}</div>
                          <div className="detail">
                            <span className="price">¥{item.minPrice}</span>
                            {
                              serverActivityList.length && item.needNotice && 
                                <button 
                                  className={`action ${ item.noticeFlag ? 'already' : ''}`}
                                  onClick={this.doAppoint.bind(this, item)}
                                >
                                  { item.noticeFlag ? '已预约' : '预约' }
                                </button>
                            }
                          </div>
                        </div>
                      </li>
                    )
                  })
                }
              </ul>
            </TabPane>
          </Tabs>
          
        </Styled.Group>
        {
          showFooter && <Styled.Bottom/>
        }
      </Styled.CardGroupContainer>
    )
  }
}
