/**
 * Dialog
 * @邠心vbe on 2021/02/20
 */
import React from 'react';
import * as Progress from 'react-native-progress';
import {Pressable, StyleSheet, Text, View, Image} from 'react-native';
import Toast from 'react-native-root-toast';
import utils from '../utils/utils';
import ModalPortal from './ModalPortal';
import Button from './Button';

const maxDef = isIOS ? 480 : 540;
var _maxWidth = isIOS ? $vw(75) : $vw(87);
const maxWidth = _maxWidth > maxDef ? maxDef: _maxWidth;

const BUTTON_OK = 'ok';
const BUTTON_CANCEL = 'cancel';

export const getDialogWidth = () => {
  return maxWidth;
}

/**
 * 显示一个弹窗
 * @param {*} props 参数{title, message, ok, cancel, showCancel, callback(button)}
 */
const showDialog = (props) => {
  var param = {
    align: props.align || 'left',
    title: props.title || '',
    message: props.message || '',
    ok: props.ok || 'OK',
    cancel: props.cancel || 'CANCEL',
    showCancel: props.showCancel != undefined ? props.showCancel : true,
    callback: props.callback
  }
  ModalPortal.show((
    isIOS ? <IOSDialog {...param}/>
          : <AndroidDialog {...param}/>
  ));
}

/**
 * 显示一个只有确认按钮的弹窗
 * @param {}} message 消息
 * @param {*} ok 按钮文字
 * @param {*} back callback(btn)
 */
const showResultDialog = (message, ok, back) => {
  var param = {
    title: isIOS ? message : '',
    message: !isIOS ? message : '',
    showCancel: false,
    ok: ok || 'I Known',
    callback: back
  }
  showDialog(param);
}

const showProgressDialog = (message='Loading...') => {
  //message = message ?? 'Waiting...';
  ModalPortal.showLoading((
    isIOS ? message//<IOSProgress message={message}/>
          : <AndroidProgress message={message}/>
  ));
}

const dismissDialog = () => {
  ModalPortal.dismiss();
}

const dismissLoading = () => {
  ModalPortal.dismissLoading();
}

const dismissAll = () => {
  ModalPortal.dismissAll();
}

const IOSDialog = (props) => {
  return (
    <View style={iosStyle.modalDialog}>
      { props.title != '' &&
        <Text style={iosStyle.modalTitle}>{props.title}</Text>
      }
      { props.message != '' &&
        <Text style={[
          iosStyle.message,
          {
            textAlign: props.align
          }
        ]}>
          {props.message}
        </Text>
      }
      <View style={iosStyle.modalFooter}>
        <Button
          text={props.ok}
          style={iosStyle.btnGroup}
          viewStyle={iosStyle.btnView}
          textStyle={iosStyle.btnConfirm}
          onClick={() => {
            dismissDialog();
            if (props.callback) {
              props.callback(BUTTON_OK);
            }
          }}/>
        { props.showCancel &&
          <Button
            text={props.cancel}
            style={[iosStyle.btnGroup, iosStyle.btnRight]}
            viewStyle={iosStyle.btnView}
            textStyle={iosStyle.btnText}
            onClick={() => {
              dismissDialog();
              if (props.callback) {
                props.callback(BUTTON_CANCEL);
              }
            }}/>
        }
      </View>
    </View>
  );
}

const AndroidDialog = (props) => {
  return (
    <View style={andStyles.modalDialog}>
      { props.title != '' &&
        <Text style={andStyles.title}>
          {props.title}
        </Text>
      }
      { props.message != '' &&
        <Text style={[
          andStyles.message,
          {
            textAlign: props.align
          }
        ]}>
          {props.message}
        </Text>
      }
      <View style={andStyles.modalFooter}>
        { props.showCancel &&
          <AndroidButton 
            title={props.cancel}
            onPress={() => {
              dismissDialog();
              if (props.callback) {
                props.callback(BUTTON_CANCEL);
              }
            }}
          />
        }
        <AndroidButton 
          title={props.ok}
          onPress={() => {
            dismissDialog();
            if (props.callback) {
              props.callback(BUTTON_OK);
            }
          }}
        />
      </View>
    </View>
  )
}

const AndroidButton = ({title, onPress}) => {
  return (
    <View style={andStyles.modalButton}>
      <Pressable
        style={andStyles.modalPress}
        android_ripple={ripple}
        onPress={onPress}>
        <Text style={andStyles.modalBtnText}>{title}</Text>
      </Pressable>
    </View>
  );
}

const IOSProgress = (props) => {
  return (
    <View style={iosStyle.modalProgress}>
      <Image
        style={iosStyle.loadingIcon}
        source={require('../images/icon/loading.gif')}/>
      <Text
        style={iosStyle.proMessage}
        onPress={() => {
          dismissLoading();
        }}>{props.message}</Text>
    </View>
  );
}

const AndroidProgress = (props) => {
  return (
    <View style={andStyles.progressDialog}>
      <View style={andStyles.progressView}>
        <View style={{
          width: 48,
          height: 48
        }}>
          <Progress.CircleSnail
            size={48}
            duration={667}
            thickness={4}
            color={[colorAccent]}
            direction={'clockwise'}
            spinDuration={2000}/>
        </View>
        <Text
          style={andStyles.proMessage}
          onPress={() => {
            dismissLoading();
          }}>{props.message}</Text>
      </View>
    </View>
  );
}

const iosStyle = StyleSheet.create({
  modalDialog: {
    width: maxWidth,
    marginLeft: 'auto',
    marginRight: 'auto',
    borderRadius: 12,
    overflow: 'hidden',
    backgroundColor: 'white'
  },
  modalProgress: {
    width: 180,
    overflow: 'hidden',
    alignItems: 'center',
    marginLeft: 'auto',
    marginRight: 'auto',
    borderRadius: 12,
    backgroundColor: 'white'
  },
  loadingIcon: {
    width: 80,
    height: 80,
    transform: [{scale: 1.3}]
  },
  title: {
    paddingTop: 18,
    paddingLeft: 16,
    paddingRight: 16,
    paddingBottom: 16
  },
  modalTitle: {
    color: '#111',
    fontSize: 18,
    paddingTop: 18,
    paddingLeft: 10,
    paddingRight: 10,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  message: {
    color: '#333',
    fontSize: 14,
    paddingTop: 4,
    paddingLeft: 20,
    paddingRight: 20
  },
  proMessage: {
    color: '#555',
    fontSize: 15,
    marginTop: -4,
    paddingBottom: 14
  },
  modalFooter: {
    width: maxWidth,
    marginTop: 18,
    borderTopWidth: 1,
    borderTopColor: '#EFF1F1',
    flexDirection: 'row'
  },
  btnGroup: {
    flex: 1,
    borderRadius: 0,
    backgroundColor: 'white'
  },
  btnRight: {
    borderLeftWidth: 1,
    borderLeftColor: '#EFF1F1'
  },
  btnView: {
    flex: 1,
    height: 45,
    alignItems: 'center',
    justifyContent: 'center'
  },
  btnText: {
    color: '#064FE1',
    fontSize: 14,
    textAlign: 'center'
  },
  btnConfirm: {
    color: '#064FE1',
    fontSize: 14,
    fontWeight: 'bold'
  }
})

const andStyles = StyleSheet.create({
  modalDialog: {
    width: maxWidth,
    zIndex: 100,
    paddingTop: 16,
    paddingLeft: 20,
    paddingRight: 20,
    paddingBottom: 8,
    borderRadius: 3,
    marginLeft: 'auto',
    marginRight: 'auto',
    backgroundColor: 'white'
  },
  progressDialog: {
    width: maxWidth,
    zIndex: 100,
    paddingTop: 16,
    paddingLeft: 24,
    paddingRight: 24,
    paddingBottom: 16,
    borderRadius: 3,
    marginLeft: 'auto',
    marginRight: 'auto',
    backgroundColor: 'white'
  },
  title: {
    color: '#000',
    paddingBottom: 8,
    fontSize: 18
  },
  message: {
    color: '#333',
    fontSize: 14,
    paddingBottom: 8,
  },
  proMessage: {
    flex: 1,
    color: '#333',
    fontSize: 15,
    paddingLeft: 24
  },
  modalFooter: {
    paddingTop: 8,
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  modalButton: {
    marginLeft: 8,
    borderRadius: 3,
    overflow: 'hidden'
  },
  modalPress: {
    padding: 8
  },
  modalBtnText: {
    fontSize: 14,
    color: colorPrimary
  },
  progressView: {
    alignItems: 'center',
    flexDirection: 'row'
  },
  endView: {
    paddingTop: 16
  }
});

export default Dialog = {
  BUTTON_OK: BUTTON_OK,
  BUTTON_CANCEL: BUTTON_CANCEL,
  isShowing: ModalPortal.isShowing,
  showDialog: showDialog,
  dismissAll: dismissAll,
  dismissDialog: dismissDialog,
  dismissLoading: dismissLoading,
  showResultDialog: showResultDialog,
  showProgressDialog: showProgressDialog,
  modalProps: {
    avoidKeyboard: true,
    animationIn: "fadeIn",
    animationOut: "fadeOut",
    propagateSwipe: true,
    useNativeDriver: true,
    hideModalContentWhileAnimating: true
  },
  styles: andStyles,
  IOSProgress: IOSProgress
}

//Toast显示位置
const toastPosition = isIOS ? 0 : -70;

const getStringMessage = (msg) => {
  if (typeof msg == 'object') {
    if (msg.err) {
      return "" + msg.err;
    } else if (msg.msg) {
      return "" + msg.msg;
    } else if (msg.message) {
      return "" + msg.message;
    } else {
      return JSON.stringify(msg);
    }
  } else {
    return "" + msg;
  }
}

export const InitSomething = () => {
  global.dialogId = undefined;
  global.EndView = () => <View style={andStyles.endView}/>

  global.toastShort = (msg) => {
    if (typeof msg !== 'string')
      msg = getStringMessage(msg);
    if (utils.isNotEmpty(msg)) {
      Toast.show(msg, {
        duration: Toast.durations.SHORT,
        position: toastPosition,
        shadow: false,
        opacity: 0.85,
        textStyle: {
          fontSize: 14
        },
        backgroundColor: '#222222',
        containerStyle: {
          paddingLeft: 16,
          paddingRight: 16,
          borderRadius: 50,
          maxHeight: $vh(80)
        }
      });
    }
  }

  global.toastLong = (msg) => {
    if (typeof msg !== 'string')
      msg = getStringMessage(msg);
    if (utils.isNotEmpty(msg)) {
      Toast.show(msg, {
        duration: Toast.durations.LONG,
        position: toastPosition,
        shadow: false,
        opacity: 0.85,
        textStyle: {
          fontSize: 14
        },
        backgroundColor: '#222222',
        containerStyle: {
          paddingLeft: 16,
          paddingRight: 16,
          borderRadius: 50,
          maxHeight: $vh(80)
        }
      });
    }
  }
}