/**
 * Edit Profile页面
 * @邠心vbe on 2021/05/07
 */
import React, { Component } from 'react';
import { View, Text, StyleSheet, Pressable, Image, TextInput } from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';
import Modal from 'react-native-modal';
import apiUpload from '../../api/apiUpload';
import apiUser from '../../api/apiUser';
import { host } from '../../api/http';
import { ModalProps } from '../../components/BottomModal';
import Button, { ViewHeight } from '../../components/Button';
import { CountryDropNum, GetCountryList } from '../../components/CountryIcon';
import Dropdown from '../../components/Dropdown';
import { UploadThemes } from '../../components/ThemesConfig';
import utils from '../../utils/utils';
import { DialogMaxWidth } from '../charge/InfoDialog';
import { PageList } from '../Router';

//Image Picker参数
const options = {
  cropping: true,
  multiple: false,
  minFiles: 1,
  maxFiles: 3,
  mediaType: 'photo',
  compressImageQuality: 0.8,
  cropperCircleOverlay: true,
  ...UploadThemes
}

//向右的箭头
const ArrowRight = () => {
  return (
    <Entypo
      size={16}
      color='#999'
      name='chevron-thin-right'
      style={{
        marginLeft: 16
      }}
    />
  );
}

//分割线
const Divide = () => {
  return (
    <View style={{
      paddingLeft: 16,
      paddingRight: 16
    }}>
      <Text style={{
        height: 1,
        backgroundColor: '#eee'
      }}></Text>
    </View>
  );
}

//编辑弹窗
const EditDialog = ({visible, title, value, keyType, countryList, areaNo, showCalling=false, onChangedText}) => {
  var changedText = value;
  var callingCode = areaNo;
  return (
    <Modal
      isVisible={visible}
      {...ModalProps}
      onBackdropPress={() => onChangedText('')}
      onBackButtonPress={() => onChangedText('')}>
      <View style={styles.dialog}>
        <Text style={styles.editNickname}>{title}</Text>
        <View style={ui.flexc}>
          { showCalling &&
            <Dropdown
              title='Country'
              prefixText="+"
              list={countryList}
              value={callingCode}   
              nameKey='countryNum'
              valueKey='countryNum'
              style={styles.countryView}
              textStyle={styles.selectText}
              onChange={(value, index)=> {
                callingCode = value;
              }}
              customerItemView={
                (item, index, onClick) => 
                <CountryDropNum
                  key={index} 
                  country={item}
                  value={callingCode}
                  onClick={onClick}/>
              }
            />
          }
          <TextInput
            style={styles.nickInput}
            defaultValue={value}
            keyboardType={keyType}
            onChangeText={text => {
              changedText = text;
            }}/>
        </View>
        <View style={styles.modalButtons}>
          <Button
            style={styles.btnCancel}
            viewStyle={ViewHeight(42)}
            textColor={textCancel}
            text='Cancel'
            onClick={() => {
              onChangedText('');
            }}/>
          <Button
            style={styles.btnOk}
            viewStyle={ViewHeight(42)}
            text='Save'
            onClick={() => {
              onChangedText(changedText, callingCode);
            }}/>
        </View>
        {/* <Ionicons
          name='close'
          size={28}
          color={'#999'}
          style={styles.closeIcon}
          onPress={() => {
            onChangedText('');
          }} /> */}
      </View>
    </Modal>
  );
}

//页面
export default class EditProfile extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editDialog: {
        key: '',
        value: '',
        title: '',
        visible: false
      },
      userInfo: {},
      countryNums: []
    };
    this.editAddress = false;
  }

  componentDidMount() {
    /*this.props.navigation.addListener('beforeRemove', e => {
      if (this.canUpdate) {
        e.preventDefault();
        //console.log('----update---', userInfo);
      }
    });*/
    this.props.navigation.addListener('focus', e => {
      if (this.editAddress && userInfo.editAddress) {
        this.updateProfile(global.userInfo);
      }
      this.editAddress = false;
    });
    this.setState({
      userInfo: userInfo
    })
    GetCountryList(list => {
      this.setState({
        countryNums: list
      })
    })
  }

  updateProfile(_userInfo) {
    apiUser.setProfile(_userInfo).then(res => {
      toastShort('Update profile successfully');
      userInfo = _userInfo;
      this.setState({
        userInfo: _userInfo
      });
      //this.canUpdate = false;
      //goBack();
    }).catch(err => {
      //this.canUpdate = false;
      toastShort(err);
    });
  }

  hideDialog() {
    this.state.editDialog.visible = false;
    this.setState({
      editDialog: this.state.editDialog
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Pressable
          style={styles.profileView}
          android_ripple={ripple}
          onPress={() => {
            ImagePicker.openPicker({
              width: 200,
              height: 200,
              ...options
            }).then(image => {
              if (image.path) {
                apiUpload.uploadImage(image.path, image.mime, 'USER_PROFILE').then(res => {
                  if (res.success && res.data.picturePath) {
                    //this.canUpdate = true;
                    this.state.userInfo.photoUrl = res.data.picturePath
                    /*this.setState({
                      userInfo: userInfo
                    });*/
                    this.updateProfile(this.state.userInfo);
                  } else {
                    toastShort('Upload failed, please retry');
                  }
                }).catch(err => {
                  toastShort(err);
                });
              }
            }).catch(err => {

            });
          }}>
          <Text style={styles.label}>Avatar</Text>
          <Text style={ui.flex1}></Text>
          { userInfo.photoUrl
          ? <Image
              style={styles.avatar}
              source={{uri: host + userInfo.photoUrl}}/>
          : <Image
              style={styles.avatar}
              source={require('../../images/user/ic-avatar-default.png')}/>
          }
          <ArrowRight/>
        </Pressable>
        <Divide/>
        <Pressable
          style={styles.profileView}
          android_ripple={ripple}
          onPress={() => {
            this.setState({
              editDialog: {
                key: 'nickName',
                title: 'Update Nickname',
                value: this.state.userInfo.nickName,
                visible: true
              }
            });
          }}>
          <Text style={styles.label}>Nickname</Text>
          <Text style={styles.infoText}>{this.state.userInfo.nickName}</Text>
          <ArrowRight/>
        </Pressable>
        <Divide/>
        <Pressable
          style={styles.profileView}
          android_ripple={ripple}
          onPress={() => {
            this.setState({
              editDialog: {
                key: 'phone',
                visible: true,
                showCalling: true,
                title: 'Update Phone Number',
                value: this.state.userInfo.phone,
                areaNo: this.state.userInfo.callingCode
              }
            });
          }}>
          <Text style={styles.label}>Phone Number</Text>
          <Text style={styles.infoText}>{(utils.isNotEmpty(this.state.userInfo.callingCode) && "+" + this.state.userInfo.callingCode)} {this.state.userInfo.phone}</Text>
          <ArrowRight/>
        </Pressable>
        <Divide/>
        <Pressable
          style={[styles.profileView, {
            paddingRight: 48
          }]}>
          <Text style={styles.label}>Email</Text>
          <Text style={styles.infoText}>{userInfo.email}</Text>
          {/*<ArrowRight/>*/}
        </Pressable>
        <Divide/>
        <Pressable
          style={styles.profileView}
          android_ripple={ripple}
          onPress={() => {
            /*this.setState({
              editDialog: {
                key: 'addressLine',
                title: 'Update Address',
                value: userInfo.addressLine,
                visible: true
              }
            });*/
            this.editAddress = true;
            startPage(PageList.editAddress);
          }}>
          <Text style={styles.label}>Address</Text>
          <Text style={styles.infoText}>{userInfo.addressLine}</Text>
          <ArrowRight/>
        </Pressable>
        <Divide/>
        <Pressable
          style={[styles.profileView, {
            paddingRight: 48
          }]}>
          <Text style={styles.label}>User Type</Text>
          <Text style={styles.infoText}>{userInfo.userType}</Text>
          {/*<ArrowRight/>*/}
        </Pressable>
        <Divide/>
        <Pressable
          style={[styles.profileView, {
            paddingRight: 48
          }]}>
          <Text style={styles.label}>Registration Date</Text>
          <Text style={styles.infoText}>{"-"}</Text>
          {/*<ArrowRight/>*/}
        </Pressable>
        <EditDialog
          title={this.state.editDialog.title}
          visible={this.state.editDialog.visible}
          value={this.state.editDialog.value}
          areaNo={this.state.editDialog.areaNo}
          countryList={this.state.countryNums}
          showCalling={this.state.editDialog.showCalling}
          keyType={this.state.editDialog.key == 'phone' ? 'phone-pad' : 'default'}
          onChangedText={(text, areaNo) => {
            if (text) {
              var info = Object.assign({}, userInfo);
              if (this.state.editDialog.key == 'phone') {
                if (!/^[0-9\+]\d{6,15}$/.test(text)) {
                  toastShort('Phone Number is incorrect format');
                  return;
                }
                info.callingCode = areaNo;
              }
              info[this.state.editDialog.key] = text;
              /*this.setState({
                userInfo: userInfo
              });
              this.canUpdate = true;*/
              this.updateProfile(info);
            }
            this.hideDialog();
          }}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: pageBackground
  },
  profileView: {
    padding: 16,
    alignItems: 'center',
    flexDirection: 'row'
  },
  label: {
    color: '#666',
    fontSize: 14
  },
  infoText: {
    flex: 1,
    color: textPrimary,
    fontSize: 14,
    paddingLeft: 16,
    textAlign: 'right'
  },
  avatar: {
    width: 62,
    height: 62,
    borderRadius: 80,
  },
  dialog: {
    width: DialogMaxWidth,
    paddingTop: 16,
    paddingLeft: 20,
    paddingRight: 20,
    paddingBottom: 16,
    marginLeft: 'auto',
    marginRight: 'auto',
    backgroundColor: colorLight,
    borderRadius: isIOS ? 20 : 3
  },
  editNickname: {
    color: '#000',
    fontSize: 18,
    textAlign: 'center'
  },
  nickInput: {
    flex: 1,
    color: textPrimary,
    fontSize: 14,
    paddingTop: 8,
    paddingLeft: 16,
    paddingRight: 16,
    paddingBottom: 8,
    borderRadius: 4,
    marginTop: 24,
    backgroundColor: '#F6F6F6'
  },
  modalButtons: {
    marginTop: 32,
    paddingBottom: 12,
    alignItems: 'center',
    flexDirection: 'row'
  },
  btnCancel: {
    flex: 1,
    borderWidth: 1,
    borderColor: colorCancel,
    backgroundColor: pageBackground
  },
  btnOk: {
    flex: 1,
    marginLeft: 16,
    borderWidth: 1,
    borderColor: colorAccent,
  },
  closeIcon: {
    top: 12,
    right: 12,
    position: "absolute"
  },
  countryView: {
    width: 80,
    marginTop: 24,
    marginRight: 8,
    minHeight: 43,
    borderRadius: 4,
    flexDirection: 'row',
    backgroundColor: '#F6F6F6'
  },
  selectText: {
    color: textPrimary,
    fontSize: 15,
    ...$padding(11, 10),
  },
});
