import * as React from 'react';
import { Props, State, BookType } from './type';
import * as Styled from './index.style';
import {rem} from '../style/function.style';
import HairH from '../common/hair-h';
import {jsonp} from '../utils/request';
// import {getEnv} from 'snail-helpers';
import {getLoginInstance} from 'snail-login';
import {handleScheme, handlePathQuery} from '../utils/snailTargetHandler';
import {showMessage} from '../common/toast/toast';

const isOnline = location.host === 'du.163.com';

export class SnailBook extends React.Component<Props, State> {
  static defaultProps = new Props();
  state = new State();
  componentDidMount(){
    // console.log('componentDidMount', this.props);
    const {discount, type, books} = this.props;
    if(discount && type === 1 && books && books.length === 1){
      this.refreshData(books[0].bookId);
    }
  }
  componentDidUpdate(){
    // console.log('componentDidUpdate', this.props);
    const {discount, type, books} = this.props;
    if(discount && type === 1 && !this.state.costCoins && books && books.length === 1){
      this.refreshData(books[0].bookId);
    }
  }

  async refreshData(bookId){
    // console.log('refresh book data');
    if(isOnline){
      const login = getLoginInstance();
      await login.isLogined();
      let response = await jsonp(`https://du.163.com/api/coin/exchange/discount.jsonp`, {
        bookId
      })
      // console.log('response', response);
      if(response.code === 0){
        const {costCoins, finalCostCoins} = response;
        this.setState({
          costCoins,
          finalCostCoins
        })
      }else{
        showMessage(response.msg);
      }
    }else{
      let response = await jsonp(`https://du.163.com/api/coin/exchange/discount.jsonp`, {
        bookId
      })
      // console.log('response', response);
      if(response.code === 0){
        const {costCoins, finalCostCoins} = response;
        this.setState({
          costCoins,
          finalCostCoins
        })
      }else{
        showMessage(response.msg);
      }
    }
  }
  linkClickHandler() {
    const {linkUrl, isEdit, type} = this.props;
    // console.log(this.props);
    if(isEdit){
      // console.log('Go link', linkUrl);
    }else{
      let logPointId, logQuery;
      if(type === 1){
        logPointId = 'acttemplate1-2';
        logQuery = {url: linkUrl};
      }else if(type === 2){
        logPointId = 'acttemplate1-10';
        logQuery = {url: linkUrl};
      }else{
        logPointId = 'acttemplate1-4';
        logQuery = {url: linkUrl};
      }
      handleScheme({
        target: linkUrl,
        logPointId,
        logQuery,
        isEdit
      })
    }
  }
  bookClickHandler(book: BookType, logPointId: string, index: number) {
    // console.log('book click', book);
    const {pos, isEdit} = this.props;
    let data = {
      path: 'bookdetail',
      query: {
        bookId: book.bookId
      },
      logPointId,
      logQuery : {
        category: 'acttemplate',
        pos: pos,
        bookId: book.bookId,
        pos2: undefined,
      },
      isEdit
    }
    if(typeof index === 'number'){
      data.logQuery.pos2 = index; 
    }
    handlePathQuery(data);
  }
  render() {
    // console.log('render', this.props, this.state);
    const {style, type, title, desc, linkText, books, isEdit, backgroundColor, titleColor, descColor, divider} = this.props;
    const {costCoins, finalCostCoins} = this.state;
    let singleBook = type === 1 && !!(books && books.length) && books[0];
    let firstBook, restBook;
    if(type === 2 && books && books.length){
      [firstBook, ...restBook] = books;
    }
    let listBook;
    if(type === 3 && books && books.length){
      listBook = books;
    }
    // console.log('singleBook', singleBook);
    // console.log('firstBook', firstBook, 'restBook', restBook);
    return (
      <Styled.Container style={{ backgroundColor, ...style }} data-mode={`mode-${type}`}>
        <Styled.Title style={{ color: titleColor }}>
          {title}
          <div className="link" style={{ color: descColor }} onTouchStart={() => {}} onClick={this.linkClickHandler.bind(this)}>
            {linkText}
          </div>
        </Styled.Title>
        {
          singleBook &&
          <Styled.SingleBook 
            onTouchStart={() => {}} 
            onClick={this.bookClickHandler.bind(this, singleBook, 'acttemplate1-3')}
          >
            <img src={singleBook.imageUrl} alt="书籍封面" className="cover"/>
            <div className="title" style={{ color: titleColor }}>{singleBook.title}</div>
            <div className="author" style={{ color: descColor }}>{singleBook.authorNames}</div>
            {
              costCoins && finalCostCoins && costCoins !== finalCostCoins && 
              <div className="discount" style={{ color: descColor }}>
                <span className="current" style={{ color: titleColor }}>{finalCostCoins/100}蜗牛壳</span>
                <span className="origin" style={{ color: descColor }}>{costCoins/100}蜗牛壳</span>
              </div>
            }
            <div className="desc" style={{ color: descColor }}>{desc || singleBook.description}</div>
          </Styled.SingleBook>
        }
        {
          firstBook &&
          <Styled.SingleBook
            onTouchStart={() => {}} 
            onClick={this.bookClickHandler.bind(this, firstBook, 'acttemplate1-11')}
          >
            <img src={firstBook.imageUrl} alt="书籍封面" className="cover"/>
            <div className="title" style={{ color: titleColor }}>{firstBook.title}</div>
            <div className="author" style={{ color: descColor }}>{firstBook.authorNames}</div>
            <div className="desc" style={{ color: descColor }}>{desc || firstBook.description}</div>
          </Styled.SingleBook>
        }
        {
          restBook &&
          <Styled.ListBook>
            <HairH style={{marginBottom: rem(34)}}/>
            {restBook.map((book, index) => (
              <Styled.ItemBook 
                key={book.bookId} 
                className={index % 3 === 2 && 'num-3th'}
                onTouchStart={() => {}} 
                onClick={this.bookClickHandler.bind(this, book, 'acttemplate1-12', index)}
              >
                <img src={book.imageUrl} alt="书籍封面" className="cover"/>
                <div className="title" style={{ color: titleColor }}>{book.title}</div>
              </Styled.ItemBook>
            ))}
          </Styled.ListBook>
        }
        {
          listBook &&
          <Styled.ListBook>
            {listBook.map((book, index) => (
              <Styled.ItemBook 
                key={book.bookId} 
                className={index % 3 === 2 && 'num-3th'}
                onTouchStart={() => {}} 
                onClick={this.bookClickHandler.bind(this, book, 'acttemplate1-5', index)}
              >
                <img src={book.imageUrl} alt="书籍封面" className="cover"/>
                <div className="title" style={{ color: titleColor }}>{book.title}</div>
              </Styled.ItemBook>
            ))}
          </Styled.ListBook>
        }
        {
          (!books || books && books.length == 0 )&& isEdit && <div>蜗牛书籍模块</div>
        }
        {
          books && books.length && divider && <Styled.Divider/>
        }
      </Styled.Container>
    )
  }
}
