import React, { PureComponent } from 'react';
import {
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  Dimensions,
  Image,
  Platform,
  ScrollView,
} from 'react-native';
import TagInput from 'react-native-tag-input';
import { InputItem } from 'antd-mobile';
import { futch } from '../utils/polyfill';
import { getToken } from '../utils/auth';
import { encrypt } from '../utils/helper';
import config from '../utils/config';
import { userApi } from '../services/interfaces';
import { errors } from '../utils/error';

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  view_header_container: {
    height: 56,
    backgroundColor: 'white',
    flexDirection: 'row',
    alignItems: 'center',
  },
  text_right_title: {
    color: '#000',
    position: 'absolute',
    right: 16,
  },
  text_left_title: {
    color: '#000',
    position: 'absolute',
    left: 16,
  },
  text_title: {
    color: '#000',
    fontSize: 18,
  },
  // uploadImage: {
  //   height: Dimensions.get('window').height,
  //   width: Dimensions.get('window').width,
  // },
});
const inputProps = {
  keyboardType: 'default',
  placeholder: '如：身份证',
  autoFocus: true,
  style: {
    fontSize: 14,
    marginVertical: Platform.OS === 'ios' ? 10 : -2,
  },
};
class UploadPageComponent extends PureComponent {
  constructor(props) {
    console.info('未过滤之前');
    console.info(props);
    super(props);
    console.info('过滤之后');
    console.info(props);
    const { imageURI } = this.props.navigation.state.params;
    this.state = {
      imageURI,
      tags: ['身份证', '红本', '绿本'],
      text: '',
      imageName: '',
    };
  }

  onChangeTags = (tags) => {
    this.setState({ tags });
  };
  onChangeText = (text) => {
    this.setState({ text });

    const lastTyped = text.charAt(text.length - 1);
    const parseWhen = [',', ' ', ';', '\n'];

    if (parseWhen.indexOf(lastTyped) > -1) {
      this.setState({
        tags: [...this.state.tags, this.state.text],
        text: '',
      });
    }
  };

  onCancel = () => {
    this.props.onCancel();
  };
  onUploadPhoto = () => {
    let token;
    getToken().then((Apptoken) => {
      if (!Apptoken) {
        return Promise.reject(errors.tokenMissing());
      }
      token = encrypt(Apptoken);
      const uri = `${config.apiContextPath}/resource/${token}`;
      const formData = new global.FormData();
      const file = { uri: this.state.imageURI, type: 'image/jpg', name: this.state.imageName !== '' ? this.state.imageName : this.state.imageURI.split('/')[this.state.imageURI.split('/').length - 1] };

      formData.append('file', file);
      console.info(formData);
      futch(uri, {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        body: formData,
      }, (progressEvent) => {
        const progress = progressEvent.loaded / progressEvent.total;
      })
        .then(request => request.responseText)// response.text())
        .then((responseData) => {
          const response = JSON.parse(responseData);
          if (response.errorCode === 0) {
            const name = 'addTags';// 添加标签
            const PicUri = `${config.apiContextPath}/api/interface/user/${name}/invoke`;
            console.info(PicUri);
            const postjson = { uri: response.data[0], tags: ['当事人信息', '当事人信息'] };
            console.info(JSON.stringify(postjson));
            userApi.invokeInterface(name, postjson)
            // futch(PicUri, {
            //   method: 'POST',
            //   headers: {
            //     'Content-Type': 'application/json',
            //   },
            //   body: JSON.stringify(postjson),
            // }, (progressEvent) => {
            //   console.info(progressEvent);
            // })
              .then(request => console.info(request));// response.text())
            // 这里需要调用接口，对图片数据进行绑定，等待完善
            // 页面跳转，跳转到前面的详情的页面
            console.info('跳转');
            this.props.navigation.navigate('DSRInfoDetail', this.props.navigation.state.params.pID);
          }
        })
        .catch((error) => {
          console.info(error);
        });
    });
  };
  setImageName = (val) => {
    this.setState({ imageName: val });
  }
  labelExtractor = tag => tag;
  renderHeaderMenu() {
    return (
      <View style={[styles.view_header_container, { backgroundColor: 'lightgray' }]}>
        <TouchableOpacity
          onPress={this.onCancel}
        >
          <Text style={[styles.text_title, { color: this.props.titleColor }]}>取消</Text>
        </TouchableOpacity>
        <Text style={[styles.text_title, { color: this.props.titleColor }]}>传照片</Text>
        <TouchableOpacity
          onPress={this.onUploadPhoto}
        >
          <Text style={styles.text_right_title}>
            上传
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
  render() {
    return (
      <View style={styles.container}>
        {this.renderHeaderMenu()}
        <ScrollView>
          <Image
            style={{ height: 80, width: 80 }}
            source={{ uri: this.state.imageURI, isStatic: true }}
          />
          <InputItem
            placeholder="如：张三"
            data-seed="logId"
            onChange={this.setImageName}
          >照片名称
          </InputItem>
          <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: 'lightgray' }}>
            <Text>类型</Text>
            <TagInput
              value={this.state.tags}
              onChange={this.onChangeTags}
              labelExtractor={this.labelExtractor}
              text={this.state.text}
              onChangeText={this.onChangeText}
              tagColor="blue"
              tagTextColor="white"
              inputProps={inputProps}
              maxHeight={75}
            />
          </View>
        </ScrollView>
      </View>
    );
  }
}


export default UploadPageComponent;

