import React from 'react';
import { 
  complete, 
  isBrowseMission,
  isShareMission,
  isShareCardMission,
  isNavigateMission,
  isInviteMission,
} from 'nw-mission';
import debounce from 'lodash.debounce'
import { parse } from 'query-string-for-all';
import { isLofter } from 'nw-detect'
import { callHandler } from 'nejsbridge/dist/bridge.lofter.es';
import { MissionInfo, MissionActivityVO } from '@type/missions';
import {
  MissionTitle,
  MissionDescContainer,
} from './index.style'
import { BlogInfo } from '../type';
import * as Styled from './index.style'
import { getShareData } from '../../share/index';
import { showMessage } from '../../common/toast/toast'
import { UnionIcon } from '../../common/icons'
import { receiveAward } from '../actions';
import { goToLogin } from '../../utils/login';
import { isCardChannel }  from '../../utils/card-utils'
import log from '../../utils/lofter-log';

const isAndroid5_1 = /android 5\.1/i.test(navigator.userAgent);

const urlData = parse(location.search);
interface MissionListProps {
  isEdit: boolean,
  activityCode: string,
  list: MissionInfo[],
  missionData: MissionActivityVO,
  innerRef?: any,
  pointsIcon: string,
  refreshData: ({
    time,
    callback,
  } : {
    time?: number,
    callback?: () => void
  }) => void,
  blogInfo: BlogInfo,
  color: string,
}
interface MissionItemProps {
  activityCode: string,
  missionInfo: MissionInfo,
  missionData: MissionActivityVO,
  refreshData: ({
    time,
    callback,
  } : {
    time?: number,
    callback?: () => void
  }) => void,
  color: string,
  pointsIcon: string,
  blogInfo: BlogInfo,
}

interface MissionDescProps {
  color?: string,
  points?: number,
  icon?: string,
  children: React.ReactNode,
}


const computeActionText = (mission: MissionInfo) => {
  const { missionStatus, showMissionType, showStatus, actionCopyWriting } = mission;
  let text = '未知';
  if (showStatus === -1) {
    return '未开始';
  }
  if (showStatus === 1) {
    return '已结束';
  }
  switch (missionStatus) {
    case -1:
      // 任务期内，未完成的任务可以直接使用服务端返回的actionCopyWriting
      text = actionCopyWriting;
      // if (showMissionType === 2) {
      //   // 分享任务，按钮文字特殊
      //   text = '分享'
      // } else if (showMissionType === 8) {
      //   // 邀请任务，按钮文字特殊
      //   text = '邀请'
      // } else {
      //   text = '前往'
      // }
      break;
    case 0:
      text = '领取'
      break;
    case 1:
      text = '已领取'
      break;
    case 2:
      text = '抢光啦'
      break;
  
    default:
      break;
  }
  return text;
}

class MissionItem extends React.Component<MissionItemProps> {
  timer : number | undefined 
  refreshInterval = (time: number) => {
    if (this.timer) {
      window.clearTimeout(this.timer);
      this.timer = undefined;
    }
    const refresh = () => {
      this.props.refreshData({time: new Date().getTime()});
      this.timer = setTimeout(() => {
        refresh();
      }, time);
    }
    refresh();
  }
  handle = debounce(() => {
    const { missionData, missionInfo, refreshData, activityCode, blogInfo } = this.props;
    // 未登录也可以看到任务列表，点击直接唤起登录
    console.log('handle mission', missionData, blogInfo);
    if (!blogInfo.blogNickName) {
      goToLogin(refreshData, 'default', true)
      return;
    }
    const { missionActivityCode } = missionData;
    // console.log('handle mission', missionActivityCode, missionInfo);
    const { missionStatus, showStatus } = missionInfo;
    if (showStatus === -1) {
      showMessage('任务还没开始哦~')
      return;
    }
    if (showStatus === 1) {
      showMessage('任务已经结束啦~')
      return;
    }
    if (missionStatus === 2) {
      showMessage('任务奖励抢光啦~')
      return;
    }
    if (missionStatus === -1) {
      // 任务未完成
      // 浏览任务
      if (isBrowseMission(missionInfo)) {
        console.log('浏览任务', isAndroid5_1);
        // android 5.1设备不支持visibilitychange 事件，直接使用轮训
        if (isAndroid5_1) {
          this.refreshInterval(3000);
        }
        complete({
          activityCode,
          missionActivityCode,
          missionInfo
        })
      }

      // 分享当前页任务，从share component获取分享参数
      if (isShareMission(missionInfo)) {
        // 活动分享任务的分享行为不在当前页，关闭当前WebView
        showMessage('点击右上角按钮完成分享，即可获得积分哦~')
        setTimeout(() => {
          callHandler('njb_closeCurrentWebview');
        }, 1000);
      }
      // 分享卡牌任务，设置localstorage并跳转抽卡页
      if (isShareCardMission(missionInfo)) {
        console.log('卡牌分享任务');
        // 2022-04-15 卡牌分享任务改造，不再通过missionActivityCode来存储分享任务信息
        // 而是通过与抽卡首页一样的activityCode来存储分享任务信息，所以任务sdk同步也有修改
        complete({
          activityCode,
          missionInfo,
          missionActivityCode: missionActivityCode
        })
      }
      if (isNavigateMission(missionInfo)) {
        console.log('直接跳转任务');
        if (missionInfo.showMissionType === 12) {
          // 任务-创作新设定作品-点击前往
          log.capture('cpnote-10', {
            category: 'cpnote',
            action: 101,
            scene: 'cpnote',
            activityId: 'cpnote-' + activityCode,
          })
        }
        if (missionInfo.showMissionType === 13) {
          // 任务-投稿作品单篇热度-点击前往
          log.capture('cpnote-12', {
            category: 'cpnote',
            action: 101,
            scene: 'cpnote',
            activityId: 'cpnote-' + activityCode,
          })
        }
        complete({
          activityCode: missionActivityCode,
          missionInfo,
        })
      }
      if (isInviteMission(missionInfo)) {
        console.log('邀请任务');
        complete({
          activityCode,
          missionActivityCode,
          missionInfo,
          errorCallback: res => {
            showMessage(res.msg);
          }
        })
      }
    } else if (missionStatus === 0) {
      // 任务已完成，可领取奖励
      log.capture('cpnote-14', {
        category: 'cpnote',
        action: 101,
        scene: 'cpnote',
        activityId: 'cpnote-' + activityCode,
        type: missionInfo.showMissionType,
        title: missionInfo.title,
      })
      receiveAward({
        activityCode,
        missionActivityCode,
        missionCode: missionInfo.code,
      }).then( res => {
        refreshData({time: new Date().getTime()});
      })
    }
  }, 1000, {
    leading: true,
    tailing: false,
  }) 
  render() {
    const { missionInfo, missionData, color, pointsIcon, } = this.props;
    // console.log('missionInfo', missionInfo);
    const { title, highlightWords, awardName, awardNum, totalProgress, currentProgress, awardIcon, showMissionType } = missionInfo;
    const progressHtmlStr = totalProgress > 1 && showMissionType !== 12 ? `<br><span class="highlight">(${currentProgress}/${totalProgress})` : '';
    // missionInfo.showStatus !== 0 任务未开始或已结束
    // missionInfo.missionStatus === 2 任务奖励抢光了
    // missionInfo.showMissionType === 9 && missionInfo.currentProgress < missionInfo.totalProgress 阶段总任务未完成
    const isMissionDisable = missionInfo.showStatus !== 0 || missionInfo.missionStatus === 2 || (missionInfo.showMissionType === 9 && missionInfo.currentProgress < missionInfo.totalProgress);
    return(
      <Styled.MissionItem color={color} >
        <div className="name" dangerouslySetInnerHTML={{
          __html: title.replace(/\d+/g, s => {
            // 2022-04-15 不再接收服务端的高亮词字段，改为自动高亮所有数字
            return `<span class="highlight">${s}</span>`
          }) + progressHtmlStr
        }}></div>
        <div className="info">
          <span className="unit">{awardName}</span>
          <img src={awardIcon} alt="图标" className="icon" />
          <span className="count">
            <UnionIcon className="count-icon" />{awardNum}
          </span>
        </div>
        <button className={`action ${missionInfo.missionStatus === 1 ? 'already' : ''} ${ isMissionDisable ? 'disable' : ''}`} onClick={this.handle}>{computeActionText(missionInfo)}</button>
      </Styled.MissionItem>
    )
  }
}

class MissionListCom extends React.Component<MissionListProps> {
  render() {
    const { innerRef, isEdit, ...resetProps } = this.props;
    let { list } = this.props;
    // console.log('list', list);
    if (!list || !list.length) {
      list = [];
    }
    // 如果是渠道，则过滤掉channelShow为false的任务
    const renderList = !isCardChannel || isEdit ? list : list.filter( item => item.channelShow );
    return(
      <Styled.MissionList ref={innerRef}>
        {
          renderList && renderList.map(item => (
            <MissionItem 
              missionInfo={item}
              key={item.code}
              {
                ...resetProps
              }
            />
          ))
        }
      </Styled.MissionList>
    )
  }
}


const MissionList = React.forwardRef((props: MissionListProps, ref: any) => {
  return <MissionListCom {...props} innerRef={ref} />
})

class MissionDesc extends React.Component<MissionDescProps> {
  render() {
    const { points, icon, children, color } = this.props;
    return (
      <MissionDescContainer color={color}>
        {children}
        {
          icon && points && <span className="points">
            <img src={icon} alt="图标" className="icon" />
            x{points}
          </span>
        }
      </MissionDescContainer>
    )
  }
}

export {
  MissionTitle,
  MissionList,
  MissionDesc,
}