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

import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  ImageBackground,
  FlatList,
  findNodeHandle,
  UIManager,
  StatusBar,
  BackHandler,
  Button,
  DeviceEventEmitter
} from "react-native";
import Orientation from "react-native-orientation";
import AndroidUtil from "../../util/AndroidUtil";
import BasePage from "../BasePage";
import CourseTitle from "./CourseTitle";
import SharedDialog from "./SharedDialog";
import ScheduleFlatItem from "./ScheduleFlatItem";
import CusVideo from "./CusVideo";
import ScheduleUrl from '../services/schedule'


export default class SchedulePage extends BasePage {
  constructor(props) {
    super(props);
    this.state = {
      statusbar_hidden: false,
      video_show: false,
      x: 0.0,
      y: 0.0,
      videoImg_flex: 1,
      videoImage_width: 0,
      videoImage_height: 0,
      videoImage_x: 0.0,
      videoImage_y: 0.0,
      video_uri:
        "https://www.apple.com/105/media/cn/iphone-x/2017/01df5b43-28e4-4848-bf20-490c34a926a7/films/feature/iphone-x-feature-cn-20170912_1280x720h.mp4",
      title_height: "9%",
      video_frame_height: "32%",
      seat_height: "2%",
      flatlist_height: "60%",
      isFull: false,
      playing_key: 0,
      scheduleTitle: '',
      wareList: [],
      colorList: [
        '#FFBC3D',
        '#FB5B76',
        '#EC48E1',
        '#39D6B9',
        '#3397F0'
      ]
    };
  }

  render() {
    return (
      <View
        style={{
          flex: 1
        }}
      >
        <StatusBar
          // backgroundColor={"transparent"}
          barStyle={"dark-content"}
          backgroundColor={"white"}
          translucent={false}
          hidden={this.state.statusbar_hidden}
        />

        <View
          style={{
            flex: 1,
            backgroundColor: "#F3F3F3",
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <View
            style={{
              height: this.state.title_height,
              backgroundColor: "white"
            }}
          >
            <CourseTitle
              width={this.getWindowWidth()}
              title={this.state.scheduleTitle}
              lefttype={1}
              righttype={1}
              textcolor={"#231F20"}
              backPress={() => this.goBack()}
              // backPress={() => alert("左侧按钮")}
              rightPress={this.showSharedDialog.bind(this)}
            />
          </View>
          <View
            style={{
              height: this.state.video_frame_height,
              width: "100%"
            }}
          >
            <Image
              source={{
                uri:
                  "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556277324856&di=dc1548a0c5ba10481af922e174912937&imgtype=0&src=http%3A%2F%2Fwww.51pptmoban.com%2Fd%2Ffile%2F2012%2F05%2F12%2F82c4568a90055adcf8fbb896f0841c69.jpg"
              }}
              style={{
                width: "100%",
                height: "100%"
              }}
              ref={c => {
                this.video_image = c;
              }}
            />
          </View>
          <View
            style={{
              height: this.state.seat_height
            }}
          />
          <View
            style={{
              height: this.state.flatlist_height,
              justifyContent: "center",
              alignItems: "center",
              width: "100%"
            }}
          >
            <FlatList
              ItemSeparatorComponent={() => (
                <View
                  style={{
                    height: 10
                  }}
                />
              )}
              ListFooterComponent={() => (
                <View
                  style={{
                    height: 30
                  }}
                />
              )}
              renderItem={({ item }) => {
                return this.loadFlatItem(item);
              }}
              keyExtractor={(item, index) => item.id.toString()}
              horizontal={false}
              data={this.state.wareList}
            />
          </View>
        </View>
        <CusVideo
          show={this.state.video_show}
          uri={this.state.video_uri}
          ref={view => (this.video = view)}
          needback={false}
          videofullScreenPlayer={this.fullScreenPlayer.bind(this)}
          onError={this.onError.bind(this)}
          onEnd={this.onEnd.bind(this)}
          style={{
            left: this.state.x,
            top: this.state.y,
            width: this.state.video_width,
            height: this.state.video_height,
            overflow: "hidden",
            position: "absolute"
          }}
        />
        <SharedDialog ref={view => (this.shareddialog = view)} />
      </View>
    );
  }
  loadFlatItem(data) {
    return (
      <ScheduleFlatItem
        width={this.getWindowWidth() * 0.9}
        height={50}
        data={data}
        onPress={() => this.changeUrl(data)}
      />
    );
  }

  componentWillMount() {
    BackHandler.addEventListener("hardwareBackPress", this.onBackAndroid);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.onBackAndroid);
  }
  componentDidMount() {
    const { id } = this.props.navigation.state.params;
    alert(id)
    let colorTemp = '';
    let colorIndexTemp = 0;
    const colorList = this.state.colorList;
    ScheduleUrl.getSchedule('KINDERGARTEN').success(res => {
      res.data.wareList.forEach((item, index) => {
        if (index === 0) {
          colorTemp = item.subTitle;
        }
        if (item.subTitle === colorTemp) {
          item.subColor = colorList[colorIndexTemp];
        } else {
          colorIndexTemp++;
          if (colorIndexTemp > colorList.length - 1) {
            colorIndexTemp = 0
          }
          colorTemp = item.subTitle;
          item.subColor = colorList[colorIndexTemp];
        }
      })
      this.setState({
        scheduleTitle: res.data.category.title,
        wareList: res.data.wareList
      })
    })
  }
  showSharedDialog() {
    this.video.pause();
    this.shareddialog.setModalVisible(true);
  }
  onBackAndroid = () => {
    if (this.state.isFull) {
      return true;
    } else {
    }
  };
  onError() {
    alert("播放器异常");
    this.setState({
      video_show: false
    });
  }
  onEnd() {
    alert("播放结束");
    this.setState({
      video_show: false
    });
    this.video.refreshVideo();
  }
  fullScreenPlayer() {
    if (!this.state.isFull) {
      Orientation.lockToLandscape();
      this.setState({
        video_frame_height: "100%",
        statusbar_hidden: true,
        isFull: true,
        x: 0,
        y: 0,
        video_width: "100%",
        video_height: "100%"
      });
    } else {
      Orientation.lockToPortrait();
      this.setState({
        video_frame_height: "32%",
        x: this.state.videoImage_x,
        y: this.state.videoImage_y,
        video_width: this.state.videoImage_width,
        video_height: this.state.videoImage_height,
        statusbar_hidden: false,
        isFull: false
      });
    }
  }
  changeUrl(data) {
    //切换视频并且播放
    // alert(url);
    // if (this.state.playing_key == data.key) {
    //   return;
    // }
    const handle = findNodeHandle(this.video_image);
    setTimeout(() => {
      UIManager.measure(handle, (x, y, width, height, pageX, pageY) => {
        this.setState({
          x: pageX,
          y: pageY,
          video_width: width,
          video_height: height,
          videoImage_width: width,
          videoImage_height: height,
          videoImage_x: pageX,
          videoImage_y: pageY,
          video_show: true,
          video_uri: data.playUrl,
          playing_key: data.key
        });
      });
    }, 0);

    this.video.start();
  }
}