/** @jsx createElement */
import { createElement, Component, render } from 'rax';
import View from 'nuke-view';
import Text from 'nuke-text';
import Image from 'nuke-image';
import Touchable from 'nuke-touchable';
import Button from 'nuke-button';
import QAPCaller from '@weex-module/qapcaller';
import Icon from 'nuke-icon';
import Tabbar from 'nuke-tabbar';
import ListView from 'nuke-list-view';
import Iconfont from 'nuke-iconfont';

const uuid = function () {
  let begin = Date.now();
  return function (prefix) {
    return `${prefix || 'UUID'}-${(begin++).toString(16).toUpperCase()}`;
  };
};


const listData = [];
for (var i = 0; i < 300; i++) {
  listData.push({ key: i, pic: '//img.alicdn.com/bao/uploaded/i1/TB1gdT4KVXXXXcpXFXXwu0bFXXX.png', text: `近三个月订单${i}` });
}

const listData1 = [];
for (var i = 0; i < 300; i++) {
  listData1.push({ key: i, pic: '//img.alicdn.com/bao/uploaded/i1/TB1gdT4KVXXXXcpXFXXwu0bFXXX.png', text: `已完成订单${i}` });
}

const styles = {
  icon1: { fontFamily: 'iconfont1', fontSize: '36rem', color: 'blue', alignItems: 'center' },
  tabContent: { flex: 1, alignItems: 'center' },
  tabText: { color: 'white', margin: 50 },
  container: { flex: 1 },
  text: { color: 'white', margin: 50 },
  customRender: { fontSize: '10rem', color: 'blue' },
  view: { flex: 1 },
  top: { height: 60, paddingLeft: 10, paddingRight: 10, marginBottom: 20, flexDirection: 'row' },
};

const app = {
  activeBorder: { borderBottomWidth: '4rem', borderBottomStyle: 'solid', borderBottomColor: '#454545' },
  inactiveBorder: { borderBottomWidth: '4rem', borderBottomStyle: 'solid', borderBottomColor: '#eeeeee' },
  listHeader: { height: '300rem', display: 'flex', alignItems: 'center', flexDirection: 'column', justifyContent: 'center' },
  listHeaderText: { fontSize: '60rem', color: '#333333' },
  listHeaderSub: { fontSize: '30rem', color: '#888888' },
  listContainer: { flex: 1, backgroundColor: '#f8f8f8' },
  footer: { paddingTop: '50rem', paddingBottom: '50rem', backgroundColor: '#efefef', textAlign: 'center' },
  link: { fontSize: '32rem' },
  titleLink: { backgroundColor: '#ff4200', display: 'block', padding: '10rem' },
  img: { width: '100rem', height: '100rem', backgroundColor: '#ff4200' },
  cellItemIndex: { backgroundColor: '#ffffff', height: '130rem', display: 'flex', paddingLeft: '20px', alignItems: 'center', flexDirection: 'row' },
  cellItemList: { flex: 1, backgroundColor: '#ffffff', height: '110rem', borderBottom: '1px solid #e8e8e8', display: 'flex', alignItems: ' center', flexDirection: 'row' },
  itemTextList: { flex: 13, fontSize: '30rem', color: '#333333' },
  itemIcon: { width: '60rem', height: '60rem', flex: 2, justifyContent: 'center' },
  cellTextView: { flex: 13, display: 'flex' },
  itemMainTitle: { fontSize: '34rem', color: '#333333', marginBottom: '10px' },
  itemSubTitle: { fontSize: '24rem', color: '#333333' },
  itemArrow: { flex: 1, width: '18px', height: '18px' },
  customTitle: { width: 200 },
};

class Gray extends Component {
  press() {
    this.changeTo('3');
  }

  onFocus(status) {
    console.log('gray:', status);
  }

  render() {
    return (
      <View style={[styles.tabContent, { backgroundColor: '#888888' }]}>
        <Text style={styles.text}>Blue Tab 大家好我是nv色的区域</Text>
        <Button onPress={this.press.bind(this)} type="normal">切换为m3</Button>
      </View>
    );
  }
}

class Sub extends Component {
  press() {
    this.props.change('m3');
  }

  render() {
    return (
      <View style={[{ backgroundColor: '#eeeeee', height: '200rem' }]}>
        <Text>子容器</Text>
        <Button onPress={this.press.bind(this)} type="normal">切换为m3</Button>
      </View>
    );
  }
}

class Green extends Component {
  constructor(props) {
    super(props);
    console.log('green constructor');
  }
}

class App extends Component {
  constructor() {
    super();
    this.state = {
      notifCount: 3,
      presses: 0,
      data: listData,
      data1: listData1,
      stop: false,
      activeKey: { key: '0' },
      test: 1,
    };
    this.index = 0;
    this.tracker = {
      startTime: 0,
      transferTime: 0,
      nativeStartTime: 0,
      nativeEndTime: 0,
      endTime: 0,
      uuid: '',
    };
    Iconfont({ name: 'iconfont1', url: 'http://at.alicdn.com/t/font_1474198576_7440977.ttf' });
  }
  getFocus(status) {
    //   console.log('green:', status, this)
    // Modal.toast(status)
  }
  componentWillReceiveProps(nextProps) {
    // console.log(nextProps)
  }
  shouldComponentUpdate(nextProps, nextState) {
    if (this.hasInit) {
      // console.log('green: shouldComponentUpdate', this)
      return true;
    }
    return false;

    // console.log('QAPCaller constructor')
  }

  render() {
    return (
      <View style={[styles.tabContent, { backgroundColor: '#ffffff' }]}>
        <Sub change={this.press.bind(this)} />
        <Text style={styles.text}>Blue Tab 大家好我是nv色的区域</Text>
        <Button onPress={this.press.bind(this, 'm4')} type="normal">切换为m4</Button>
      </View>
    );
  }

  endSuccess(args) {
    console.log('endSuccess');
    console.log(args);

    this.tracker.nativeEndTime = args.ti;
    this.tracker.endTime = Date.now();
    // 全链路时间
    console.log('[tracker] allTime: ', this.tracker.endTime - this.tracker.startTime);
    console.log('[tracker] nativeTime: ', this.tracker.nativeEndTime - this.tracker.nativeStartTime);
    console.log('[tracker] transferTime: ', this.tracker.endTime - this.tracker.startTime - this.tracker.nativeEndTime + this.tracker.nativeStartTime);
  }

  componentWillUpdate(nextProps, nextState) {
    this.tracker.startTime = Date.now();
    this.tracker.uuid = uuid();
    console.log('QAPCaller componentDidUpdate');
    // 向native发出打点请求，并携带uuid作为任务唯一标识
    QAPCaller.call('NukeUI', 'performance', { action: 'start', taskId: this.tracker.uuid }, this.startSuccess, () => {}, () => {});
  }

  componentDidUpdate(prevProps, prevState) {
    // this.tracker.transferTime = Date.now();
    // this.tracker.uuid = uuid();
    // console.log('QAPCaller componentDidUpdate')
    // // 向native发出打点请求，并携带uuid作为任务唯一标识
    QAPCaller.call('NukeUI', 'performance', { action: 'end', taskId: this.tracker.uuid }, this.endSuccess, () => {}, () => {});
    // QAPCaller.call('NukeUI', 'performance', {action: 'start', taskId: uuid()}, this.notifySuccess, this.notifyError, this.notify);
  }

  press() {
    this.setState({ test: 11111111 });
    // 注册性能打点
    // QAPCaller.call('NukeUI', 'performance', {action: 'start', taskId: uuid()}, this.notifySuccess, this.notifyError, this.notify);
  }
  changeTab(tab) {
    this.setState({ activeKey: tab });
  }

  _renderContent(color, pageText, num) {
    return (
      <View style={[styles.tabContent, { backgroundColor: color }]}>
        <Text style={styles.tabText}>{pageText}</Text>
        <Text style={styles.tabText}>{num} re-renders of the {pageText}</Text>
      </View>
    );
  }

  handleLoadMore() {
    const self = this;
    // 这里进行异步操作
    setTimeout(() => {
      self.index++;
      if (self.index == 5) {
        self.state.stop = true; // 加载5次后会停止加载，并去掉菊花
      }
      self.state.data.push({ key: 'x', pic: '//img.alicdn.com/bao/uploaded/i1/TB1O9eAKVXXXXaPaXXXwu0bFXXX.png', text: 'xx订单' }, { key: 'loadmore 2', pic: '//img.alicdn.com/bao/uploaded/i1/TB1O9eAKVXXXXaPaXXXwu0bFXXX.png', text: 'xx订单' }, { key: 'loadmore 2', pic: '//img.alicdn.com/bao/uploaded/i1/TB1O9eAKVXXXXaPaXXXwu0bFXXX.png', text: 'xx订单' }, { key: 'loadmore 2', pic: '//img.alicdn.com/bao/uploaded/i1/TB1O9eAKVXXXXaPaXXXwu0bFXXX.png', text: 'xx订单' }, { key: 'loadmore 2', pic: '//img.alicdn.com/bao/uploaded/i1/TB1O9eAKVXXXXaPaXXXwu0bFXXX.png', text: 'xx订单' });
      self.setState(self.state);
    }, 1000);
  }
  linkTo(item, e) {
    console.log(e);
  }
  renderItem(item, index) {
    return (<Touchable style={app.cellItemList} onPress={this.linkTo.bind(this, item)}>
      <Icon src={item.pic} style={app.itemIcon} />
      <Text style={app.itemTextList}>{item.text}</Text>
      <Icon style={app.itemArrow} src="//img.alicdn.com/tfs/TB1EU2rMVXXXXcpXXXXXXXXXXXX-64-64.png" />
    </Touchable>);
  }
  renderHeader() {
    return <View style={app.listHeader}><Text style={app.showTitleText}>list</Text></View>;
  }
  renderFooter() {
    return <View style={app.loading}><Text style={app.loadingText}>加载中...</Text></View>;
  }
  onChange(status) {
    console.log('status', status);
  }

  switchCustomTitle(status, key) {
    const textStyle = {
      textAlign: 'center',
    };
    status ? Object.assign(textStyle, { color: '#3f08ee' }) : null;
    switch (key) {
      case '1':
        return <View style={app.customTitle}><Text style={textStyle}>自定义title1</Text></View>;
      case '2':
        return <View style={app.customTitle}><Text style={textStyle}>自定义title1</Text></View>;
      default:
        return <View style={app.customTitle}><Text style={textStyle}>key</Text></View>;
    }
  }

  other() {
    this.setState({ test: 999 });
  }

  render() {
    return (
      <View style={styles.container}>
        <Button onPress={this.press.bind(this)} type="normal">setState</Button>
        <View>{this.state.test}</View>
        <View>{this.state.test}</View>
        <View>{this.state.test}</View>
        <View style={styles.view}>
          <Tabbar slider={false} asContainer={false} navTop navScrollable iconBar={false} navStyle={{ active: app.activeBorder, inactive: app.inactiveBorder }} activeKey={this.state.activeKey} onChange={this.onChange.bind(this)} customChange="changeTo" customFocus="getFocus">
            <Tabbar.Item
              render={this.switchCustomTitle.bind(this)}
              tabKey="1"
            >
              <Green />
            </Tabbar.Item>
            <Tabbar.Item
              render={this.switchCustomTitle.bind(this)}
              tabKey="2"
              onPress={() => { console.log('something'); }}
            >
              <Gray changeTab={this.changeTab.bind(this)} />
            </Tabbar.Item>
            <Tabbar.Item
              tabKey="3"
              render={this.switchCustomTitle.bind(this)}
            >
              {this._renderContent('#783E33', `Red Tab 大家好我是红色的区域${this.state.notifCount}`, this.state.notifCount)}
            </Tabbar.Item>
            <Tabbar.Item
              render={this.switchCustomTitle.bind(this)}
              tabKey="4"
            >
              <ListView
                renderHeader={this.renderHeader.bind(self)}
                renderFooter={this.renderFooter.bind(self)}
                renderRow={self.renderItem.bind(self)}
                dataSource={self.state.data}
                style={app.listContainer}
                onEndReached={self.handleLoadMore.bind(self)}
              />
            </Tabbar.Item>
            <Tabbar.Item
              tabKey="5"
              render={this.switchCustomTitle.bind(this)}
            >
              <ListView
                renderHeader={this.renderHeader.bind(self)}
                renderFooter={this.renderFooter.bind(self)}
                renderRow={self.renderItem.bind(self)}
                dataSource={self.state.data1}
                style={app.listContainer}
                onEndReached={self.handleLoadMore.bind(self)}
              />
            </Tabbar.Item>
          </Tabbar>
        </View>
      </View>
    );
  }
}

render(<App />);
