import * as React from 'react'

import * as Styled from './index.style'
import { get, post } from '../../utils/request'
import log from '../../utils/lofter-log'
import {
  callHandler,
  support
} from 'nejsbridge/dist/bridge.lofter.es.js';
import { isLofter } from 'nw-detect';
import { openAppLofter } from 'nw-app-lofter';
import { LiveStatus, ActEventLiveRoomVO } from '../../template-activity-container/type'
import { showMessage } from '../../common/toast/toast';
import NumberUtils from '../../utils/numberUtils';

export interface BlogInfo {
  blogName: string;
  isVerify: boolean;
  blogNickName: string;
  bigAvaImg: string;
  blogId: number;
  isAuth: boolean;
  selfIntro: string;
}

interface Props {
  /** 直播展示模块数据 */
  data: ActEventLiveRoomVO[];
  status: LiveStatus[];
  isEdit?: boolean;
  loading?: boolean;
  type?: number; // 样式类型
  style: React.CSSProperties,
  nickNameColor?: string,
  titleColor?: string,
  descriptionColor?: string
}

class LiveList extends React.Component<Props> {
  state: {
    liveDisplay: [string, string, string][] // 三个参数分别是状态展示,背景颜色，字体颜色
    userInfo: BlogInfo[];
  } = {
      liveDisplay: [],
      userInfo: []
    }

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

  private computeLiveStatusShow(liveStatus: number, subscribed: boolean, canSubs: boolean, subEnds: boolean): [string, string, string] {
    console.log(liveStatus, subscribed, canSubs, subEnds)
    // liveStatus 0未开播，1正在直播，2已结束
    if (liveStatus === 1) return ['正在直播', '#FF6C93', '#FFFFFF']; // 状态展示,背景颜色，字体颜色
    if (!subEnds) {   // 是否预约结束,false 表示目前时间在开播前十分钟之前,还可以预约
      if (canSubs) {
        if (liveStatus === 0 && subscribed === false) return ['预约', '#14C4BC', '#FFFFFF'];
        if (liveStatus === 0 && subscribed === true) return ['已预约', '#F5F5F5', '#BFBFBF']
      }
      else {
        // 后台设置不可以预约，显示未开播
        return ['未开播', '#F5F5F5', '#BFBFBF'];
      }
    }
    else {
      // subEnds === true  预约时间已经结束了，不考虑预约
      if (liveStatus === 0) return ['未开播', '#F5F5F5', '#BFBFBF'];
      if (liveStatus === 2) return ['已结束', '#EDEDED', '#3F3F3F'];
    }
  }

  handleSubscribe = (activityId: string, roomId: number, index: number) => { // 直播预约
    if (!isLofter()) {
      openAppLofter({
        path: 'webview',
        query: {
          url: location.href
        }
      })
      return;
    }
    post('//www.lofter.com/spread/common/lives/subscribe', {
      activityId: activityId,
      roomId: roomId
    }).then(res => {
      if (res.code === 200) {
         // 新增直播预约打点
        log.capture(`cmszhibo-1`, {
          category: 'cmszhibo',
          action: 101,
          scene: 'cmszhibo',
          v: '1.0.0'
        })
        let temp = this.state.liveDisplay;
        temp[index] = ['已预约', '#F5F5F5', '#BFBFBF'];
        this.setState({
          liveDisplay: temp
        })
        
      }
      if (res.code === 401) {
        if (
          isLofter()
          && support('njb_login')
        ) {
          callHandler('njb_login')
        }
      }
    }
    )
  }


  // fetchliveDisplay(blogIds: string) {
  //   get('//www.lofter.com/spread/common/blogInfos', {
  //     blogIds
  //   }).then(res => {
  //     if (res.code === 200) {
  //       this.setState({
  //         liveDisplay: res.data?.blogInfos?.map((a: any) => a.blogInfo)
  //       })
  //     }
  //   })
  // }

  componentDidMount() {
    // if (this.props?.data.length > 0) {
    //   let blogids: string = this.props?.data?.map(a => a.anchor).join(',')
    //   // this.fetchliveDisplay(blogids)
    // }
    if (this.props.status.length > 0) {
      let temp: [string, string, string][] = []
      console.log('status', this.props.status)
      this.props.status.forEach((item: LiveStatus, index: number) => {
        temp[index] = this.computeLiveStatusShow(item.liveStatus, item.subscribed, this.props.data[index].canSubs, item.subEnds)
      })
      this.setState({
        liveDisplay: temp
      })
    }

  }

  componentDidUpdate(prevProps: any, prevState: any) {
    // if (this.props.data !== prevProps.data) {
    //   let blogids: string = this.props?.data?.map(a => a.anchor).join(',')
    //   this.fetchliveDisplay(blogids)
    // }
    if (this.props.status !== prevProps.status) {
      let temp: [string, string, string][] = []
      console.log('status', this.props.status)
      this.props.status.forEach((item: LiveStatus, index: number) => {
        temp[index] = this.computeLiveStatusShow(item.liveStatus, item.subscribed, this.props.data[index].canSubs, item.subEnds)
      })
      this.setState({
        liveDisplay: temp
      })
    }
    if (this.props.type !== prevProps.type) {
      console.log(this.props.type)
    }
  }

  public render() {
    const {
      data,
      status,
      type,
      style,
      descriptionColor,
      titleColor,
      nickNameColor
    } = this.props
    const {
      liveDisplay
    } = this.state
    console.log(titleColor)
    return (
      // <div style={style}>
      <Styled.Container>
        <Styled.ListContainer   className={`type-${type}`}>
          {
            data && liveDisplay?.length && data.length && data?.map((item: ActEventLiveRoomVO, index: number) => (
              <Styled.ListItem
                className={`type-${type}`}
                key={index}
                onClick={liveDisplay?.length > 0 && liveDisplay[index][0] !== '预约' ? () => window.location.href = status[index].roomUrl : null}>
                <Styled.ListItemDescImg
                  src={item.imageUrl}
                  className={`type-${type}`}
                >
                </Styled.ListItemDescImg>
                <Styled.Icon className={`type-${type}`} src='https://imglf5.lf127.net/bkimg/20211109143702/4a872cc4-4507-48e7-b687-17ced242b386.png' />
                <Styled.LiveInfo className={`type-${type}`} titleColor={titleColor}>
                  <Styled.LiveInfo className={`title-${type}`} titleColor={titleColor}>{
                    item.title
                  }</Styled.LiveInfo>
                  {
                    type !== 1 && liveDisplay?.length &&
                    <>
                      <Styled.Description className={`type-${type}`} descriptionColor={descriptionColor}>{item.description}</Styled.Description>
                      <Styled.UserImg
                        className={`type-${type}`}
                        src={status[index].blogInfo.bigAvaImg || 'https://imglf4.lf127.net/bkimg/20211116134858/35b22262-3b44-4075-8426-1b056dc9fe94.png'} />
                      <Styled.UserNickName className={`type-${type}`} nickNameColor={nickNameColor}>
                        {status[index].blogInfo.blogNickName}
                      </Styled.UserNickName>
                      {
                        liveDisplay?.length > 0 && type === 3 &&
                        <Styled.LiveStatusOther
                          className={`type-${type}`}
                          color={liveDisplay[index][2]}
                          background={liveDisplay[index][1]}
                          onClick={liveDisplay[index][0] === '预约' ? () => { this.handleSubscribe(item.activityId, item.roomId, index) } : null}>
                          {liveDisplay[index][0]}
                        </Styled.LiveStatusOther>
                      }
                    </>
                  }
                  {
                    liveDisplay?.length > 0 && type === 2 &&
                    <Styled.LiveStatus
                      className={`type-${type}`}
                      color={liveDisplay[index][2]}
                      background={liveDisplay[index][1]}
                      onClick={liveDisplay[index][0] === '预约' ? () => { this.handleSubscribe(item.activityId, item.roomId, index) } : null}>
                      {liveDisplay[index][0]}
                    </Styled.LiveStatus>
                  }
                </Styled.LiveInfo>
                {
                  status?.length && !status[index].liveStatus &&
                  <Styled.LiveTime className={`type-${type}`}>开播时间:{this.formatDate(item.liveTime)}</Styled.LiveTime>
                }
                {
                  liveDisplay?.length && type === 1 &&
                  <>
                    <Styled.UserImg
                      className={`type-${type}`}
                      src={status[index].blogInfo.bigAvaImg || 'https://imglf4.lf127.net/bkimg/20211116134858/35b22262-3b44-4075-8426-1b056dc9fe94.png'} />
                    <Styled.UserNickName
                       nickNameColor={nickNameColor}
                      className={`type-${type}`}>
                      {status[index].blogInfo.blogNickName}
                    </Styled.UserNickName>
                  </>
                }
                {
                  liveDisplay?.length > 0 && type === 1 &&
                  <Styled.LiveStatus
                    className={`type-${type}`}
                    color={liveDisplay[index][2]}
                    background={liveDisplay[index][1]}
                    onClick={liveDisplay[index][0] === '预约' ? () => { this.handleSubscribe(item.activityId, item.roomId, index) } : null}>
                    {liveDisplay[index][0]}
                  </Styled.LiveStatus>
                }
              </Styled.ListItem>
            ))
          }
          {
            !data?.length &&
            <Styled.EmptyContainer>
              未配置作品展示模块
            </Styled.EmptyContainer>
          }
        </Styled.ListContainer>
      </Styled.Container>
      // </div>
    )
  }
}

export default React.memo(LiveList)
