import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'

import backIcon from './back.png';
import './header.scss'

/**
 * props属性
 */
interface IProps {
	/**
	 * 页面标题
	 */
  pageTitle: string;
	/**
	 * 右上角的图标及点击操作
	 */
  rightAction?: {
    text?: string;
    icon?: string;
    handleClick: () => any,
  };
	/**
	 * 样式类名
	 */
  headerClass?: string;
	/**
	 * 是否展示边框
	 */
  bordered?: boolean;
	/**
	 * 是否展示
	 */
  visible?: boolean;
}

/**
 * 组件内部属性
 */
interface IState {

}

/**
 * 示例：
 *
 * ```js
  <Header
    pageTitle='头部组件'
    visible
    bordered
  />
  ```
 */
export default class Header extends Component<IProps, IState> {

  /**
   * 当前页面栈长度 用于决定是否展示返回按钮
   */
  currentPagesLength: number;

  componentDidMount() {
    console.log('Taro.getCurrentPages()', );
    this.currentPagesLength = Taro.getCurrentPages().length
  }

  /**
   * 返回按钮点击
   */
  goBack = () => {
    Taro.navigateBack()
  }

  render() {
    const {
      pageTitle,
      rightAction,
      headerClass,
      bordered,
      visible
    } = this.props
    return (
      !visible ?
        null
        :
        <View className='com-header-box'>
          <View className={`com-header-container ${bordered && 'bordered'} ${headerClass && headerClass}`}>
            <View className='left'>
              {
                this.currentPagesLength > 1 &&
                <View className={`icon back`}
                  onClick={this.goBack.bind(this)}
                >
                  <Image src={backIcon}
                    className='backIcon'
                  />
                </View>
              }
            </View>
            <View className='center'>
              <View className='page-title'>
                {pageTitle}
              </View>
            </View>
            <View className='right'>

              {/* 自定义右上角文字/图标 */}
              {
                rightAction ?
                  <View className='action-area'
                    onClick={rightAction.handleClick}
                  >
                    {/* 自定义icon */}
                    {
                      rightAction.icon &&
                      <Image src={rightAction.icon} />
                    }
                    {/* 自定义文字 */}
                    {
                      rightAction.text ?
                        <Text className='text'>{rightAction.text}</Text>
                        : null
                    }
                  </View>
                  : null
              }
            </View>
          </View>
        </View>
    )
  }
}
