import React from 'react';
import {Image, PanResponder, View, Text, Dimensions} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import {connect} from 'react-redux';
import moment from 'moment';
import {width} from '../utils/screen';
import {colors} from '../utils/common';
import Modal from './Modal';
import Toast from './Toast';
import Touch from './Touch';
import {counterInterval} from '../utils/authInterval';
import {payTitle} from '../utils/config';

const weekdays = {
  0: '周日',
  1: '周一',
  2: '周二',
  3: '周三',
  4: '周四',
  5: '周五',
  6: '周六',
};

@connect(({app}) => ({app}))
class Layout extends React.Component {
  state = {
    count: window.defaultCount,
    contact: '',
    maskVisible: true,
    visibleActive: false,
    dateInfo: `${moment().format('YYYY-M-D HH:mm')}  ${
      weekdays[Number(moment().day())]
    }`,
  };

  async componentWillMount() {
    window.count = window.defaultCount;
    window.login = this.counterLogin;
    this.panResponder = PanResponder.create({
      // 要求成为响应者：
      onStartShouldSetPanResponder: this.handleStartShouldSetPanResponder,
    });
    let contact = await AsyncStorage.getItem('CONTACT');
    let lock = await AsyncStorage.getItem('settingLock');
    if (lock) {
      this.props.dispatch({type: 'app/lock', lock});
    }
    this.setState({contact});
  }

  componentDidMount() {
    this.timer = setInterval(() => {
      this.setState({
        dateInfo: `${moment().format('YYYY-M-D HH:mm')}  ${
          weekdays[Number(moment().day())]
        }`,
      });
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  handleStartShouldSetPanResponder = () => {
    window.count = window.defaultCount;
  };

  showCounterLogin = async () => {
    const key = await AsyncStorage.getItem('KEY');
    Modal.prompt(
      '门店授权',
      '门店收银台授权认证',
      [{text: '取消'}, {text: '登录', onPress: this.counterLogin}],
      // (login, password) => console.log(`login: ${login}, password: ${password}`),
      'login-password',
      key,
      ['请填写门店标识', '请填写门店密钥'],
    );
  };

  loginError = async msg => {
    Toast.fail(msg, 1);
  };

  counterLogin = async (key, secret) => {
    if (!key) {
      await this.loginError('请输入门店标识');
      return;
    }
    if (!secret) {
      await this.loginError('请输入门店密钥');
      return;
    }
    await Toast.loading('授权认证中');
    const action = {type: 'admin/auth', key, secret, login: 'counter'};
    const {dispatch} = this.props;
    const res = await dispatch(action);
    if (res.code === 1) {
      Toast.success('授权认证成功，正在重启应用...', 2, async () => {
        await counterInterval(dispatch, res.data.expiresIn, true);
      });
    }
  };

  stepOne = async () => {
    await this.setState({
      visibleActive: true,
    });
    setTimeout(() => {
      this.setState({
        visibleActive: false,
      });
    }, 3000);
  };

  stepTwo = () => {
    let {visibleActive} = this.state;
    if (visibleActive) {
      this.setState({
        maskVisible: false,
      });
      setTimeout(() => {
        this.setState({
          visibleActive: false,
          maskVisible: true,
        });
      }, 5000);
    }
  };

  render() {
    const {width, height} = Dimensions.get('window');
    const {children} = this.props;
    let {contact, maskVisible, dateInfo, visibleActive} = this.state;
    contact = contact || '未授权';
    return (
      <View
        {...this.panResponder.panHandlers}
        style={{flex: 1, backgroundColor: '#333'}}>
        <View style={styles.navBar}>
          <View style={{flex: 1, flexDirection: 'row', alignItems: 'center'}}>
            {width > height ? (
              <Image
                source={require('../assets/logo.png')}
                style={{
                  width: 70,
                  height: 70,
                  marginLeft: 15,
                }}
              />
            ) : (
              <Image
                source={require('../assets/zmgo_icon.png')}
                style={styles.navLogo}
              />
            )}
            <View
              style={{
                justifyContent: 'flex-end',
                height: 80,
                flex: 1,
                alignItems: 'center',
              }}>
              <View
                style={{
                  width: 200,
                  height: 40,
                  backgroundColor: '#000000',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginBottom: 1,
                }}>
                <Text style={{color: '#ffffff', fontSize: 16}}>{dateInfo}</Text>
              </View>
            </View>
          </View>
          {width > height ? (
            <Text style={{color: 'white', fontSize: 40, fontWeight: '700'}}>
              {payTitle}
            </Text>
          ) : (
            <Image
              style={{width: 325, height: 36, resizeMode: 'contain'}}
              source={require('../assets/zmgo_title.png')}
            />
          )}
          <View style={styles.navRight}>
            <Image
              source={require('../assets/phone_icon.png')}
              style={{
                width: 36,
                height: 36,
                marginRight: 5,
                resizeMode: 'contain',
              }}
            />
            <Text
              style={{
                color: '#F5AB61',
                fontSize: 32,
                fontWeight: 'bold',
                marginRight: 20,
              }}>
              {contact}
            </Text>
          </View>
        </View>
        {maskVisible ? (
          <View style={styles.navMask}>
            <Touch
              onPress={() => this.stepOne()}
              style={{
                width: 150,
                height: 80,
                backgroundColor: visibleActive ? colors.bg : 'transparent',
              }}>
              <View />
            </Touch>
            <View style={{flex: 1, alignItems: 'center'}} />
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'flex-end',
              }}>
              <Touch
                onPress={() => this.stepTwo()}
                style={{width: 50, height: 80}}>
                <View />
              </Touch>
              <View style={{opacity: 0}}>
                <Text
                  style={{
                    color: '#F5AB61',
                    fontSize: 32,
                    fontWeight: 'bold',
                    marginRight: 20,
                  }}>
                  {contact}
                </Text>
              </View>
            </View>
          </View>
        ) : (
          <View style={{display: 'none'}} />
        )}
        <View style={{flexDirection: 'row', flex: 1, zIndex: 9}}>
          <View style={{flex: 1, margin: 10}}>{children}</View>
        </View>
      </View>
    );
  }
}

const styles = {
  navMask: {
    width,
    height: 80,
    position: 'absolute',
    top: 0,
    left: 0,
    backgroundColor: 'transparent',
    alignItems: 'center',
    flexDirection: 'row',
  },
  navBar: {
    width,
    height: 80,
    backgroundColor: colors.bg,
    alignItems: 'center',
    flexDirection: 'row',
  },
  navLogo: {
    width: 81,
    height: 35,
    marginLeft: 15,
  },
  navTextL: {
    color: '#ffffff',
    marginLeft: 10,
    fontSize: 28,
  },
  navRight: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-end',
  },
  navTextR: {
    color: '#ffffff',
    marginRight: 20,
    fontSize: 20,
  },
  footer: {
    width: width - 20,
    height: 50,
    borderRadius: 3,
    flexDirection: 'row',
    backgroundColor: 'white',
    margin: 10,
    marginTop: 0,
  },
  contLine: {
    width: 20,
    backgroundColor: colors.bg,
  },
  navTime: {
    fontSize: 16,
    color: '#ffffff',
  },
};

export default Layout;
