/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import {
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';

import FastImage from 'react-native-fast-image';
import { TabBar, TabView } from 'react-native-tab-view';
import { LargeList } from 'react-native-largelist-v3';
import { CommonLottieHeader } from 'react-native-spring-scrollview/Customize/CommonLottieHeader';
import { push } from '../../BasicNavigator/actions';
import decorator from '../../utils/decorator';
import { queryInsuranceProducts } from '../InsuranceList/InsuranceAPI';
import TabBarIndicatorLinear from '../../components/TabBarIndicator';
import {
  renderPolicyHeader,
  renderPolicyTab,
  headerHeight,
  tabHeight,
} from './policyRenderUtil';

type Props = {};
const tabWidth = global.SCREEN_WIDTH / 4;
const listItemHeight = (global.SCREEN_WIDTH - 10) * 255 / 365
const listItemWidth = global.SCREEN_WIDTH - 10;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  tab: {
    width: tabWidth,
  },
  label: {
    fontWeight: 'bold',
    fontSize: 16,
    //color: '#666',
  },
});

const typeArr : Array<> = [
  { key: 'ALL', title: '全部', type: 1 },
  { key: 'SAVE', title: '人寿', type: 41 },
  { key: 'EXPIRED', title: '财险', type: 10 },
  { key: 'EXPIRED2', title: '养老', type: 20 },
];

const typeData = {
  index: 0,
  routes: typeArr,
};

@decorator
class PolicyPage extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      type: typeData,
    };
  }

  componentDidMount() : void {
    this.queryList();
  }

  _handleIndexChange = (index) => {
    const type = {
      index,
      routes: typeArr,
    };
    this.setState({ type });
  };

  renderIndexPath = ({ section, row }) => {
    const { theme, pushTo } = this.props;
    const item = this.state.data[section].items[row];
    console.log('renderIndexPath:', item)
    return (
      <TouchableOpacity
        onPress={() => pushTo('ProductDetailPage', item)}
      >
        <FastImage
          style={{
            width: listItemWidth,
            height: listItemHeight,
          }}
          source={{
            uri: item.iconUrl,
            priority: FastImage.priority.normal,
          }}
          resizeMode={FastImage.resizeMode.stretch}
        />
      </TouchableOpacity>
    );
  };

  queryList = async () => {
    const list = await queryInsuranceProducts({});
    console.log('queryInsuranceProducts:', list);
    if (list) {
      this.setState({
        data: [
          {
            items: list,
          },
        ],
      });
    }
  };

  onRefresh = async () => {
    await this.queryList();
    this.scrollView.endRefresh();
  };

  endRefresh = () => {

  };

  _renderScene = ({ route, jumpTo }) => (
    <LargeList
      ref={(com) => {
        this.scrollView = com;
      }}
      style={{
        backgroundColor: '#F4F5F5',
      }}
      contentStyle={[
        { height: global.SCREEN_HEIGHT - headerHeight - tabHeight, backgroundColor: '#F4F5F5' },
      ]}
      data={this.state.data}
      onRefresh={this.onRefresh}
      endRefresh={this.endRefresh}
      refreshHeader={CommonLottieHeader}
      heightForIndexPath={() => listItemHeight}
      heightForSection={() => 0}
      renderIndexPath={this.renderIndexPath}
    />
  );

  _renderTabBar = item => (
    <TabBar
      {...item}
      scrollEnabled
      indicatorStyle={{ width: tabWidth }}
      style={{ backgroundColor: '#fff', height: 50 }}
      tabStyle={styles.tab}
      labelStyle={[styles.label]}
      activeColor={this.props.theme.ThemeColor}
      inactiveColor="#666"
      renderIndicator={(props) => (
        <TabBarIndicatorLinear {...props} />
      )}
    />
  )


  render() {
    return (
      <View style={[styles.container, { backgroundColor: '#fff' }]}>
        {renderPolicyHeader(this.props)}
        {renderPolicyTab(this.props)}
        <View style={{ height: 43 }} />
        <TabView
          navigationState={this.state.type}
          renderScene={this._renderScene}
          renderTabBar={this._renderTabBar}
          onIndexChange={this._handleIndexChange}
          lazy
          swipeEnabled={false}
          swipeDistanceThreshold={global.SCREEN_WIDTH / 10}
          initialLayout={{ width: global.SCREEN_WIDTH }}
        />
      </View>
    );
  }
}


function actionMapping(dispatch) {
  return {
    pushTo: compose(dispatch, push),
  };
}

function propsMapping({ theme }) {
  return {
    theme,
  };
}

export default connect(propsMapping, actionMapping)(PolicyPage);
