import React, {Component} from 'react';
import {View, Text, Image, FlatList} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Swiper from 'react-native-swiper';
import QRCode from 'react-native-qrcode-svg';
import Icon from 'react-native-vector-icons/Ionicons';
// import { connect } from 'react-redux';
import CounterMixins from './CounterMixins';
import NP from '../utils/np';
import Touch from '../components/Touch';
import logo from '../assets/Vertical/logo.png';
import counterText from '../assets/Vertical/counterText.png';
import img24h from '../assets/Vertical/24h.png';
import phone from '../assets/Vertical/phone.png';
import {login} from '../utils/config';
import {colors} from '../utils/common';
import WxFacepay from '../utils/WxFacepay';
import {width} from '../utils/screen';

let pageSize = 8; // 分页大小
window.pageSize = pageSize;

// const wait = t => new Promise(resolve => setTimeout(resolve, t));

// @connect(({ app }) => ({ app }))
class VerticalPage extends Component {
  state = {
    contact: '',
    maskVisible: true,
    visibleActive: false,
  };

  async componentWillMount() {
    let contact = await AsyncStorage.getItem('CONTACT');
    // let lock = await AsyncStorage.getItem('settingLock');
    // if (lock) this.props.dispatch({ type: 'app/lock', lock });
    this.setState({contact});
    this.storeKey = await AsyncStorage.getItem('KEY');
    if (!this.init) {
      this.init = await WxFacepay.init();
    }
  }

  authinfo = async () => {
    const rawdata = await WxFacepay.rawdata();
    const {data} = await this.props.dispatch({type: 'goods/faceinfo', rawdata});
    if (data.code !== 1) {
      return null;
    }
    return data.data;
  };

  // 生成不重复的key
  keyExtractor = (item: any, index: number) => {
    return String(index);
  };

  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);
    }
  };

  wxFacepay = async () => {
    const {goodsArr} = this.props;
    if (goodsArr.length === 0) {
      this.props.speak('请先扫描商品条码，再刷脸支付', true);
      return;
    }
    const auth = (await this.authinfo()) || {};
    let params = null;
    if (auth.bizCode === '0000') {
      // 随行付支付
      params = {
        appid: auth.subAppId,
        mch_id: auth.subMchId,
        store_id: this.storeKey,
        authinfo: auth.authInfo,
        ask_face_permit: 1,
        face_code_type: '1',
      };
    } else if (auth.sub_mchid_info) {
      // 扫呗支付
      const info = JSON.parse(auth.sub_mchid_info);
      params = {
        appid: info.sub_serv_appid,
        mch_id: info.sub_serv_no,
        store_id: this.storeKey,
        authinfo: auth.authinfo,
        face_authtype: 'FACEPAY',
        sub_appid: info.sub_appid,
        sub_mch_id: info.sub_mch_id,
        out_trade_no: auth.out_trade_no,
        ask_face_permit: 1,
        face_code_type: auth.auth_no_type,
      };
    }
    if (!params) {
      if (this.faceRetry) {
        this.faceRetry = false;
        this.props.speak('刷脸支付启动失败，请重新刷脸或扫码支付', true);
      } else {
        this.faceRetry = true;
        this.wxFacepay(); // 重试一次
      }
      return;
    }
    const res = await WxFacepay.facepay(params);
    if (res.face_code) {
      await this.props.barcodepay(res.face_code, true);
      // const ret = await this.props.barcodepay(res.face_code, true);
      // const result = { ...params, payresult: ret };
      // if (ret !== 'SUCCESS') result.payresult = 'ERROR';
      // WxFacepay.update(result);
      this.faceRetry = false;
    }
  };

  renderHeader = () => {
    return (
      <View style={{flex: 1, flexDirection: 'column'}}>
        <View style={{backgroundColor: '#fff'}}>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'center',
            }}>
            <View style={styles.firstThStyle}>
              <Text style={styles.ThText}>商品名称</Text>
            </View>
            <View style={styles.ThStyle}>
              <Text style={styles.ThText}>单价</Text>
            </View>
            <View style={styles.ThStyle}>
              <Text style={styles.ThText}>数量</Text>
            </View>
            <View style={styles.ThStyle}>
              <Text style={styles.ThText}>金额</Text>
            </View>
          </View>
        </View>
        <View style={{height: 20, backgroundColor: '#F0F0F0'}} />
      </View>
    );
  };

  // 显示数据
  renderCell = (item, index) => (
    <View style={index % 2 === 0 ? styles.oddCell : styles.evenCell}>
      <View style={styles.firstTdStyle}>
        <Text style={styles.TdText} numberOfLines={1}>
          {item.spec ? `${item.name}(${item.spec})` : item.name}
        </Text>
      </View>
      <View style={styles.TdStyle}>
        {item.price ? (
          <Text style={styles.TdText}>
            {' '}
            ￥{NP.round(item.price, 2).toFixed(2)}/{item.unit}{' '}
          </Text>
        ) : (
          <Text style={styles.TdText}>
            {' '}
            ￥{NP.round(item.prePrice, 2).toFixed(2)}/{item.unit}{' '}
          </Text>
        )}
      </View>
      <View style={styles.TdStyle}>
        {item.numChange ? (
          <Icon
            onPress={() =>
              this.props.numRemove(
                item.num,
                index + (this.props.current - 1) * pageSize,
              )
            }
            name="ios-remove-circle"
            color={item.num === 1 ? '#909090' : '#00c670'}
            size={35}
          />
        ) : (
          <View />
        )}
        <Touch
          viewWrap={false}
          onPress={() =>
            item.numChange &&
            this.props.numChange(index + (this.props.current - 1) * pageSize)
          }>
          <Text style={styles.TdText}> {item.num} </Text>
        </Touch>
        {item.numChange ? (
          <Icon
            name="ios-add-circle"
            color="#00c670"
            size={35}
            onPress={() =>
              this.props.numAdd(
                item.num,
                index + (this.props.current - 1) * pageSize,
              )
            }
          />
        ) : (
          <View />
        )}
      </View>
      <View style={styles.TdStyle}>
        {item.price ? (
          <Text style={styles.TdText}>
            {NP.round(item.price * item.num, 2).toFixed(2)}
          </Text>
        ) : (
          <Text style={styles.TdText}>
            {NP.round(item.prePrice * item.num, 2).toFixed(2)}
          </Text>
        )}
        <Icon
          style={{marginLeft: 10}}
          name="ios-close-circle"
          size={35}
          color={colors.bg}
          onPress={() =>
            this.props.removeIndex(index + (this.props.current - 1) * pageSize)
          }
        />
      </View>
    </View>
  );

  render() {
    let {admin, goods, goodsArr, qrHost, current} = this.props;
    let {contact} = this.state;
    pageSize = goods && goods.bags.length > 0 ? 7 : pageSize;
    window.pageSize = pageSize;
    contact = contact || '未授权';
    let goodsLength = Math.ceil(parseFloat(goodsArr.length / pageSize));
    let gaTemp = goodsArr.slice((current - 1) * pageSize, current * pageSize);
    let total = 0; // 总数量
    let totalPrice = 0; // 总价
    let totalCount = 0; // 总优惠
    goodsArr.map(item => {
      total += item.num;
      if (item.price) {
        totalPrice += item.price * item.num;
        totalCount += (item.prePrice - item.price) * item.num;
      } else {
        totalPrice += item.prePrice * item.num;
      }
    });
    this.totalPrice = totalPrice;
    this.totalCount = totalCount;
    return (
      <View style={styles.main}>
        <View style={styles.header}>
          <View style={styles.left}>
            <Image source={logo} />
            <Image style={styles.counterText} source={counterText} />
            <Image source={img24h} />
          </View>
          <View style={styles.right}>
            <Image style={styles.phone} source={phone} />
            <Text style={styles.number}>{contact}</Text>
          </View>
        </View>
        <View style={styles.container}>
          <View style={{flexDirection: 'row', flex: 1}}>
            <View style={{width: '90%'}}>
              <FlatList
                style={styles.goodsStyle}
                ListHeaderComponent={this.renderHeader}
                keyExtractor={this.keyExtractor}
                horizontal={false}
                data={gaTemp}
                renderItem={({item, index}) => this.renderCell(item, index)}
              />
            </View>
            <View style={{width: '10%', flexDirection: 'column'}}>
              <View style={{height: 81, backgroundColor: '#fff'}} />
              <View style={{height: 8}} />
              <View style={styles.pagination}>
                <Touch
                  disabled={current <= 1}
                  onPress={() => this.props.dropUp()}>
                  <Image
                    source={
                      current > 1
                        ? require('../assets/Vertical/arrowu01.png')
                        : require('../assets/Vertical/arrowu02.png')
                    }
                    style={styles.imgPagination}
                  />
                </Touch>
                <Text style={styles.paginationText}>
                  {goodsLength === 0 ? 0 : current}/{goodsLength}
                </Text>
                <Touch
                  disabled={current >= goodsLength}
                  onPress={() => this.props.dropDown(goodsLength)}>
                  <Image
                    source={
                      current < goodsLength
                        ? require('../assets/Vertical/arrowd01.png')
                        : require('../assets/Vertical/arrowd02.png')
                    }
                    style={styles.imgPagination}
                  />
                </Touch>
              </View>
            </View>
          </View>
          <View
            style={
              goods && goods.bags.length > 0
                ? styles.btnLowStyle
                : styles.btnHighStyle
            }>
            <Touch
              onPress={() => this.props.handleBarcode()}
              style={{backgroundColor: '#fc4000', marginRight: 50}}>
              <Text style={styles.btnText}>输入条码</Text>
            </Touch>
            <Touch
              onPress={() => this.props.handleCodeless()}
              style={{
                backgroundColor: '#fc4000',
                marginRight: 50,
                marginLeft: 50,
              }}>
              <Text style={styles.btnText}>无码商品</Text>
            </Touch>
            <Touch
              onPress={this.props.clearList}
              style={{backgroundColor: '#fc4000', marginLeft: 50}}>
              <Text style={styles.btnText}>清除商品</Text>
            </Touch>
          </View>
          <View style={styles.bag}>
            {goods.bags.map((v, k) => {
              return (
                <Touch key={k} onPress={() => this.props.pushBag(k)}>
                  <View style={styles.btnBag}>
                    <Image
                      source={require('../assets/Vertical/buy.png')}
                      style={styles.btnImage}
                    />
                    <Text style={styles.textBag}>{v.name}</Text>
                    <Text style={styles.textBag}>{v.price}</Text>
                  </View>
                </Touch>
              );
            })}
          </View>
          <View style={styles.payment}>
            <View style={styles.paymentLeft}>
              <View style={styles.barcode}>
                <Text style={styles.leftText1}>合计:</Text>
                <Text style={styles.leftText1}>数量:</Text>
                <Text style={styles.leftText1}>优惠:</Text>
                <View style={styles.leftLine1} />
                <Text style={styles.leftText1}>金额:</Text>
              </View>
              <View style={styles.amount}>
                <Text style={styles.leftText2}>
                  {' '}
                  {NP.round(Number(totalPrice) + Number(totalCount), 2).toFixed(
                    2,
                  )}
                </Text>
                <Text style={styles.leftText2}>
                  {NP.round(total, 2).toFixed(2)}
                </Text>
                <Text style={styles.leftText2}>
                  {' '}
                  -{NP.round(totalCount, 2).toFixed(2)}
                </Text>
                <View style={styles.leftLine2} />
                <Text style={styles.total}>
                  {NP.round(totalPrice, 2).toFixed(2)}
                </Text>
              </View>
            </View>
            <View style={styles.faceScan}>
              <Touch onPress={this.wxFacepay}>
                <View>
                  <Image
                    source={require('../assets/Vertical/face.gif')}
                    style={styles.faceGif}
                    alt=""
                  />
                  <View style={styles.facePay}>
                    <Image
                      source={require('../assets/Vertical/wxpay.png')}
                      style={styles.payImage}
                      alt=""
                    />
                    <Text style={styles.payText}>点击刷脸支付</Text>
                  </View>
                </View>
              </Touch>
            </View>
            <View style={styles.paymentRight}>
              <View style={styles.paymentRightTitle}>
                <View style={styles.paymentRightContents}>
                  <Text style={styles.paymentRightText}>扫码</Text>
                  <Text style={styles.paymentRightText}>支付</Text>
                  <Image
                    source={require('../assets/Vertical/alipay01.png')}
                    style={styles.paymentRightImage}
                    alt=""
                  />
                  <Image
                    source={require('../assets/Vertical/wx.png')}
                    style={styles.paymentRightImage}
                    alt=""
                  />
                </View>
                <View style={styles.paymentRightCode}>
                  <QRCode
                    logoSize={50}
                    // logoBackgroundColor="#fc4000"
                    logo={require('../assets/logo2.png')}
                    size={200}
                    value={`${qrHost || login}/#/counter-order-${admin.socket}`}
                  />
                </View>
              </View>
            </View>
          </View>
          <View style={styles.explain}>
            <Text style={styles.explainText1}>付款流程：</Text>
            <View style={styles.step}>
              <Text style={styles.explainText2}>1</Text>
            </View>
            <Text style={styles.code}>扫描商品条码</Text>
            <View style={styles.step}>
              <Text style={styles.explainText2}>2</Text>
            </View>
            <Text style={styles.explainText1}>
              微信/支付宝扫二维码或付款码付款
            </Text>
          </View>
        </View>
        <View style={styles.footer}>
          <Swiper
            style={styles.swiper} // 样式
            loop // 如果设置为false，那么滑动到最后一张时，再次滑动将不会滑到第一张图片。
            autoplay // 自动轮播
            autoplayTimeout={10} // 每隔4秒切换
            horizontal // 水平方向，为false可设置为竖直方向
            showsButtons={false} // 为false时不显示控制按钮
            showsPagination={false} // 为false不显示下方圆点
          >
            <Image
              source={require('../assets/Vertical/first.jpg')}
              style={styles.swiperImg}
            />
            <Image
              source={require('../assets/Vertical/second.jpg')}
              style={styles.swiperImg}
            />
            <Image
              source={require('../assets/Vertical/third.jpg')}
              style={styles.swiperImg}
            />
          </Swiper>
        </View>
      </View>
    );
  }
}

const styles = {
  main: {
    backgroundColor: '#F0F0F0',
    height: '100%',
  },
  header: {
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: '#fc4000',
    height: '6%',
    paddingRight: 40,
    paddingLeft: 40,
  },
  left: {
    flexDirection: 'row',
    width: '60%',
  },
  counterText: {
    marginLeft: 40,
    marginRight: 40,
  },
  right: {
    flexDirection: 'row',
  },
  phone: {
    width: 60,
    height: 60,
    marginRight: 10,
    marginLeft: 20,
  },
  number: {
    fontSize: 45,
    color: '#ffffff',
  },
  navMask: {
    width,
    height: '6%',
    position: 'absolute',
    top: 0,
    left: 0,
    backgroundColor: 'transparent',
    alignItems: 'center',
    flexDirection: 'row',
  },
  container: {
    height: '62%',
  },
  goodsStyle: {
    width: '100%',
    backgroundColor: '#fff',
  },
  pagination: {
    flex: 1,
    backgroundColor: '#fff',
    marginTop: '12%',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
  paginationText: {
    fontSize: 40,
  },
  imgPagination: {
    width: 50,
    height: 50,
  },
  btnHighStyle: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff',
    paddingBottom: 20,
    paddingTop: 20,
    marginBottom: 35,
    borderBottomWidth: 1,
    borderBottomColor: '#959595',
    elevation: 3,
    shadowColor: '#F5F5F5',
    shadowOffset: {
      height: 0,
      width: 0,
    },
    shadowOpacity: 0.3,
    shadowRadius: 5,
  },
  btnLowStyle: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff',
    paddingBottom: 20,
    paddingTop: 20,
    marginBottom: 30,
    borderBottomWidth: 1,
    borderBottomColor: '#959595',
    elevation: 5,
    shadowColor: '#F5F5F5',
    shadowOffset: {
      height: 0,
      width: 0,
    },
    shadowOpacity: 0.3,
    shadowRadius: 5,
  },
  btnText: {
    fontSize: 25,
    color: '#fff',
    paddingTop: 10,
    paddingBottom: 10,
    paddingRight: 20,
    paddingLeft: 20,
  },
  bag: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#F0F0F0',
    // paddingBottom: 20,
  },
  btnBag: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#4D4D4D',
    padding: 10,
    marginBottom: 20,
    marginLeft: 20,
    marginRight: 20,
    // borderBottomWidth: 1,
    // borderBottomColor: '#959595',
    overflow: 'hidden',
    elevation: 3,
    shadowColor: '#888888',
    shadowOffset: {
      height: 0,
      width: 0,
    },
    shadowOpacity: 0.3,
    shadowRadius: 5,
  },
  btnImage: {
    height: 25,
    width: 25,
    marginLeft: 5,
    marginRight: 5,
  },
  textBag: {
    fontSize: 20,
    color: '#fff',
    marginLeft: 5,
    marginRight: 5,
  },
  payment: {
    display: 'flex',
    flexDirection: 'row',
    alignContent: 'space-around',
    marginBottom: 10,
  },
  paymentLeft: {
    width: '40%',
    display: 'flex',
    flexDirection: 'row',
    alignContent: 'space-around',
    borderLeftWidth: 1,
    borderTopWidth: 1,
    borderBottomWidth: 1,
    borderLeftColor: '#959595',
    borderTopColor: '#959595',
    borderBottomColor: '#959595',
    // borderWidth: 1,
    // borderColor: '#959595',
    backgroundColor: '#fff',
    paddingTop: 15,
    paddingBottom: 15,
    // marginRight: 10,
    // overflow: 'hidden',
    elevation: 3,
    shadowColor: '#888888',
    shadowOffset: {
      height: 0,
      width: 0,
    },
    shadowOpacity: 0.3,
    shadowRadius: 5,
  },
  barcode: {
    width: '50%',
    display: 'flex',
    flexDirection: 'column',
    alignContent: 'center',
    alignItems: 'flex-end',
  },
  leftLine1: {
    width: '80%',
    borderWidth: 1,
    borderColor: '#959595',
    height: 1,
  },
  amount: {
    width: '40%',
    display: 'flex',
    flexDirection: 'column',
    alignContent: 'center',
    alignItems: 'center',
  },
  total: {
    color: 'red',
    fontSize: 40,
  },
  leftLine2: {
    width: '100%',
    borderWidth: 1,
    borderColor: '#959595',
    height: 1,
  },
  leftText1: {
    fontSize: 40,
    marginRight: 30,
  },
  leftText2: {
    fontSize: 40,
  },
  faceScan: {
    width: '20%',
    display: 'flex',
    justifyContent: 'center',
    flexDirection: 'column',
    borderWidth: 1,
    borderColor: '#00BBFF',
    backgroundColor: '#fff',
    elevation: 3,
    shadowColor: '#888888',
    shadowOffset: {
      height: 0,
      width: 0,
    },
    shadowOpacity: 0.5,
    shadowRadius: 5,
  },
  faceGif: {
    width: '100%',
    height: 180,
  },
  facePay: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 10,
  },
  payImage: {
    width: 30,
    height: 30,
  },
  payText: {
    fontSize: 25,
    marginLeft: 10,
  },
  paymentRight: {
    width: '40%',
    display: 'flex',
    justifyContent: 'center',
    // overflow: 'hidden',
    flexDirection: 'column',
    borderRightWidth: 1,
    borderTopWidth: 1,
    borderBottomWidth: 1,
    borderRightColor: '#959595',
    borderTopColor: '#959595',
    borderBottomColor: '#959595',
    // borderWidth: 1,
    // borderColor: '#959595',
    backgroundColor: '#fff',
    height: 260,
    // marginLeft: 10,
    elevation: 3,
    shadowColor: '#888888',
    shadowOffset: {
      height: 0,
      width: 0,
    },
    shadowOpacity: 0.5,
    shadowRadius: 5,
  },
  paymentRightTitle: {
    display: 'flex',
    flexDirection: 'row',
    // alignContent: 'center',
    alignItems: 'center',
    justifyContent: 'center',
  },
  paymentRightContents: {
    display: 'flex',
    flexDirection: 'column',
    // alignContent: 'center',
    // alignItems: 'center',
    marginRight: 40,
  },
  paymentRightText: {
    fontSize: 35,
    // marginRight: 5,
  },
  paymentRightImage: {
    width: 50,
    height: 50,
    marginTop: 5,
    marginBottom: 5,
    // marginLeft: 5,
  },
  paymentRightCode: {
    display: 'flex',
    flexDirection: 'row',
    // alignContent: 'center',
    // alignItems: 'center',
  },
  firstThStyle: {
    width: '40%',
    alignItems: 'flex-start',
    paddingTop: 20,
    paddingBottom: 20,
    paddingLeft: 10,
    paddingRight: 10,
  },
  ThStyle: {
    width: '20%',
    alignItems: 'center',
    paddingTop: 20,
    paddingBottom: 20,
    paddingLeft: 10,
    paddingRight: 10,
  },
  ThText: {
    fontSize: 30,
  },
  oddCell: {
    flexDirection: 'row',
    backgroundColor: '#fff',
  },
  evenCell: {
    flexDirection: 'row',
    backgroundColor: '#F0F0F0',
  },
  firstTdStyle: {
    width: '40%',
    // alignItems: 'center',
    alignItems: 'flex-start',
    paddingTop: 20,
    paddingBottom: 20,
    paddingLeft: 10,
    paddingRight: 10,
  },
  TdStyle: {
    flexDirection: 'row',
    width: '20%',
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 20,
    paddingBottom: 20,
    paddingLeft: 10,
    paddingRight: 10,
  },
  TdText: {
    fontSize: 25,
  },
  explain: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fc4000',
    padding: 20,
    // paddingTop: 20,
    // paddingRight: 20,
    // paddingBottom: 20,
    // paddingLeft: 20,
  },
  explainText1: {
    fontSize: 30,
    color: '#fff',
    marginRight: 3,
  },
  step: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    width: 40,
    height: 40,
    backgroundColor: '#fff',
    borderRadius: 20,
    marginRight: 5,
  },
  explainText2: {
    color: '#fc4000',
    fontSize: 30,
  },
  code: {
    fontSize: 30,
    color: '#fff',
    marginRight: 50,
  },
  footer: {
    height: '32%',
    backgroundColor: '#0f0f0f',
    width: '100%',
  },
  swiper: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  swiperImg: {
    justifyContent: 'center',
    alignItems: 'center',
    width: '90%',
    height: '90%',
    marginLeft: '5%',
    marginTop: '2.5%',
    marginRight: '5%',
    marginBottom: '2.5%',
  },
};

export default CounterMixins(VerticalPage);
