import * as React from 'react'
import { isLofter } from 'nw-detect';
import { openAppLofter } from 'nw-app-lofter';
import { callHandler } from 'nejsbridge/dist/bridge.lofter.es';
import debounce from 'lodash.debounce';
import log from '../utils/lofter-log'
import { BaseComponent,handleComponentClickLog } from '../base-component'
import { showMessage } from '../common/toast/toast';
import { get, post } from '../utils/request'
import { formatAvatar, formatImageSize } from '../utils/format';

import {
  Props,
  State,
  BlogFollowData,
  AvatarBoxData
} from './type'

import { rem } from "../style/function.style";
import * as Styled from './index.style'

enum StatusMap {
  已删除 = -2,
  已过期,
  领取,
  已领取,
}
export class AvatarBox extends React.Component<Props, State> {
  static defaultProps = new Props()

  state = new State()

  follow = debounce((event: any) => {
    event.stopPropagation();
    log.capture(`avatar-box-follow`, {
      category: 'cmsact',
      action: 0,
      scene: 'cmsact',
      v: '1.0.0'
    })
    if (!isLofter()) {
      openAppLofter({
        path: 'webview',
        query: {
          url: location.href
        }
      })
      return;
    }
    const { blogFollowData }  = this.state;
    if (blogFollowData.follow) {
      return;
    }
    post('//www.lofter.com/spread/common/follow', {
      blogId: blogFollowData.blogInfo.blogId
    }).then(res => {
      if (res.code === 200) {
        showMessage({ text: '关注成功' });
        this.setState({
          blogFollowData: {
            ...blogFollowData,
            follow: true,
          }
        })
      } else {
        if (res.code === 401) {
          callHandler('njb_login', () => {
            this.initData();
          })
        } else {
          showMessage({ text: res.msg });
        }
      }
    })
  }, 1000, {
    leading: true,
    tailing: false,
  })
  goBlog = () => {
    log.capture(`avatar-box-blog`, {
      category: 'cmsact',
      action: 0,
      scene: 'cmsact',
      v: '1.0.0'
    })
    setTimeout(() => {
      const { blogFollowData } = this.state;
      if (blogFollowData) {
        location.href = `https://${blogFollowData.blogInfo.blogName}.lofter.com`
      }
    }, 300);
  }
  receive = debounce(async (event: any) => {
    event.stopPropagation();
    log.capture(`avatar-box-receive`, {
      category: 'cmsact',
      action: 0,
      scene: 'cmsact',
      v: '1.0.0'
    })
    if (!isLofter()) {
      openAppLofter({
        path: 'webview',
        query: {
          url: location.href
        }
      })
      return;
    }
    const { avatarData, blogFollowData }  = this.state;
    if (avatarData.status !== 0) {
      return;
    }
    try {
      let res;
      if (blogFollowData) {
        // 有前置关注条件
        res = await post('//www.lofter.com/spread/common/avatarBox/getAvatarBoxWithFollow', {
          blogId: blogFollowData.blogInfo.blogId,
          avatarBoxId: avatarData.avatarBoxInfo.id,
        })
      } else {
        // 没有关注，直接领取
        res = await post('//www.lofter.com/spread/avatarBox/operate.json', {
          type: 0,
          avatarBoxId: avatarData.avatarBoxInfo.id,
        })
      }
      if (res.code === 200) {
        showMessage('领取成功，请前往【我的——头像框中心】查看并佩戴~');
        this.setState({
          avatarData: {
            ...this.state.avatarData,
            status: 1,
          }
        })
      } else {
        if (res.code === 401) {
          callHandler('njb_login', () => {
            this.initData();
          })
        } else {
          showMessage(res.msg);
        }
      }
    } catch (error) {
      showMessage('领取失败，请重试~');
      console.log('领取头像框失败', error);
    }
  }, 1000, {
    leading: true,
    tailing: false,
  })
  getUserInfo = debounce (async(blogName: string) => {
    if (!blogName.trim()) {
      this.setState({
        blogFollowData: null,
      })
      return;
    };
    const params = {
      blogName: blogName,
      withFollow: true
    }
    let res = await get('//www.lofter.com/spread/common/blogInfo', params)
    if (res.code === 200) {
      this.setState({
        blogFollowData: res.data.blogInfos[0]
      })
      return res.data.blogInfos;
    }
    else return null;
  }, 1000, {
    leading: true,
    tailing: false,
  })
  getAvatarBox = debounce (async(avatarBoxId: string) => {
    if (!avatarBoxId.trim()) return;
    let res = await get('//www.lofter.com/spread/common/avatarBox/getAvatarBoxStatus', {
      avatarBoxId,
    })
    if (res.code === 200) {
      this.setState({
        avatarData: res.data
      })
      return res.data;
    }
    else return null;
  }, 1000, {
    leading: true,
    tailing: false,
  })
  initData() {
    this.getUserInfo(this.props.blogName);
    this.getAvatarBox(this.props.avatarBoxId);
  }
  componentDidMount() {
    this.initData();
  }
  componentDidUpdate(preProps: any) {
    if (this.props.blogName !== preProps.blogName) {
      if (this.props.blogName.indexOf('，') > 0) {
        showMessage({ text: '不能出现中文逗号' });
        return;
      }
      this.getUserInfo(this.props.blogName);
    }
    if (this.props.avatarBoxId !== preProps.avatarBoxId) {
      this.getAvatarBox(this.props.avatarBoxId);
    }
  }

  render() {
    const { 
      style,
      blogAvatar,
      blogNickName,
      blogDesc,
    } = this.props
    const { blogFollowData, avatarData } = this.state;
    return (
      <div style={{
        ...style,
        left: 0,
        width: '10rem',
      }}>
        <BaseComponent {...this.props}>
            <Styled.Container>
              {blogFollowData && blogFollowData.blogInfo && <Styled.FocusContainer onClick={this.goBlog}>
                <div className="content">
                  <div className="img">
                    <img src={formatAvatar(blogAvatar && blogAvatar.url || blogFollowData.blogInfo.bigAvaImg)} alt="头像" className="avatar" />
                  </div>
                  <div className="info">
                    <div className="name">{blogNickName || blogFollowData.blogInfo.blogNickName}</div>
                    <div className="desc">{blogDesc || blogFollowData.blogInfo.selfIntro}</div>
                  </div>
                  <button className={`action ${blogFollowData.follow ? 'already' : ''}`} onClick={this.follow}>{blogFollowData.follow ? '已关注' : '关注TA'}</button>
                </div>
              </Styled.FocusContainer>}
              {avatarData && avatarData.avatarBoxInfo && <Styled.AvatarContainer>
                <div className="content">
                  <div className="img">
                    <img src={formatImageSize(avatarData.avatarBoxInfo.image, 600, 0)} alt="头像框" className="avatar" />
                  </div>
                  <div className="info">
                    <div className="name">{avatarData.avatarBoxInfo.name}</div>
                    <div className="desc">{avatarData.avatarBoxInfo.description}</div>
                  </div>
                  <button className={`action ${avatarData.status === 0 ? '' : 'already'}`} onClick={this.receive}>{StatusMap[avatarData.status]}</button>
                </div>
              </Styled.AvatarContainer>}
            </Styled.Container>
        </BaseComponent>
      </div>
    )
  }
}