import AsyncStorage from '@react-native-community/async-storage';
import React, {Component} from 'react';
import {Image, Text, View} from 'react-native';
import QRCode from 'react-native-qrcode-svg';
import Icons from 'react-native-vector-icons/MaterialIcons';
import {connect} from 'react-redux';
import phone from '../assets/Vertical/phone.png';
import LoadingModal from '../components/LoadingModal';
// import OrderDetailsModal from '../components/OrderDetailsModal';
import OrderDetailMini from '../components/OrderDetailMini';
import PhoneModal from '../components/PhoneModal';
import Screensaver from '../components/Screensaver';
import TipsModal from '../components/TipsModal';
import Toast from '../components/Toast';
// import RtcEngine from 'react-native-agora';
import Touch from '../components/Touch';
import VerifyCodeModal from '../components/VerifyCodeModal';
import {leaveTalkCall, onTalkCall} from '../utils/agora';
import AutoClick from '../utils/AutoClick';
import {qrHost} from '../utils/config';
import delay from '../utils/delay';
import {scaleSize, setSpText, width} from '../utils/screen';
import Smilepay from '../utils/Smilepay';
import Speech from '../utils/Speech';
import validity from '../utils/validity';
import WxFacepay from '../utils/WxFacepay';
import Restart from '../utils/Restart';

window.restart = Restart.restartApp;

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

@connect(({admin}) => ({admin}))
class FacePage extends Component {
  state = {
    phoneModal: false, // 显示输入电话号码弹窗
    verifyCodeModal: false, // 显示输入验证码弹窗
    orderDetailsModal: false, // 显示订单详情弹窗
    orderDetailMini: false,
    goodsArr: [],
    talkCall: 2, // 0请求通话，1通话中，2，已挂断通话，待机状态
    contact: '',
    storeName: '',
    customerPhone: '',
    current: 1,
    tip: '',
    tipsModal: false,
    faceType: 'wxpay',
    sleep: true, // 屏保模式
    loadingModal: false,
    qrCode: '',
    goTipsModal: false,
    type: '',
    code: 1,
    setting: false,
  };

  phone = ''; // 监听用户输入手机
  // 设备类型
  // sense = true; // 测试即拿刷脸设备

  async componentWillMount() {
    this.storeKey = await AsyncStorage.getItem('KEY');
    let contact = await AsyncStorage.getItem('CONTACT');
    let storeName = await AsyncStorage.getItem('NAME');
    let stype = await AsyncStorage.getItem('STYPE');
    this.setState({contact, storeName, stype});
    if (!this.init) {
      this.init = await WxFacepay.initialize(10000, {
        perform_mode: 'LOW_PERFORM',
      });
      if (!this.init) {
        // 微信刷脸失败，启动支付宝刷脸
        this.init = true;
        this.setState({faceType: 'alipay'});
      } else {
        const getAuth = async () => {
          const auth = await this.authinfo();
          if (!this.rawinfo) this.rawinfo = {};
          if (auth) this.rawinfo = auth;
        };
        getAuth();
        clearInterval(this.rawinfoInterval);
        this.rawinfoInterval = setInterval(getAuth, 30 * 60 * 1000);
      }
    }
    const setting = await AutoClick.isSettingsOn();
    if (!setting) this.setState({setting: true}); // 展示按钮
    // AutoClick.on('wxpayfaceRegister', async () => {
    //   await AutoClick.clickBackKey();
    //   if (this.faceBusy) return;
    //   this.faceBusy = true;
    //   await this.face(); // 点击开通重新调用
    //   this.faceBusy = false;
    // });
    // 监听微信输入手机号事件
    AutoClick.on('AccessibilityClick', ({text}) => {
      if (!text) return;
      const match = /^\[(.+)]$/.exec(text);
      if (!match) return;
      text = match[1];
      if (text === '删除')
        this.phone = this.phone.substr(0, this.phone.length - 1);
      else if (/^\d$/.test(text)) this.phone += text;
      if (this.phone.length > 11) this.phone = this.phone.substr(-11);
      clearTimeout(this.clearPhoneTimeout); // 输入号码超过1分钟，自动清除号码，防止绑定错误号码
      this.clearPhoneTimeout = setTimeout(() => {
        this.phone = '';
      }, 60000);
    });
  }

  setting = async () => {
    await AutoClick.goSetting(); // 按钮跳转设置
  };

  async componentDidMount() {
    this.listen();
  }

  onSubmit = async _phone => {
    const res = await this.props.dispatch({
      type: 'store/sendsms',
      phone: _phone,
      faceType: this.state.faceType,
    });
    if (res.code === 1) {
      if (/^\d+$/.test(res.msg)) {
        Speech.speak(res.msg.split('').join(' '));
      } else {
        Speech.speak('请输入验证码');
      }
      this.phone = _phone;
      this.setState({
        loadingModal: false,
        phoneModal: false,
        verifyCodeModal: true,
      });
    } else {
      Speech.speak(res.msg);
    }
  };

  onCodeSubmit = async code => {
    const res = await this.props.dispatch({
      type: 'store/verifysms',
      code,
      phone: this.phone,
      userId: this.userId,
      faceType: this.state.faceType,
    });
    if (res.code === 1) {
      this.setState({
        verifyCodeModal: false,
      });
      this.loading(true);
      const ret = await this.props.dispatch({
        type: 'store/wxdoor',
        userId: res.data,
      });
      this.loading(false);
      this.handleDoorLogin(ret);
    } else {
      Speech.speak(res.msg);
    }
  };

  handleOrderClose = () => {
    this.setState({
      orderDetailsModal: false,
    });
  };
  /**
   * 用于控制订单详情弹窗，当参数为Number时为弹窗显示时间，当参数为boolean时关闭弹窗
   * @param {Number} timeout 超时时间
   */
  orderDetailMiniPop = timeout => {
    if (timeout === false) {
      this.setState({
        orderDetailMini: false,
        goodsArr: [],
      });
      clearTimeout(this.goodsCounterTimer);
      clearInterval(this.goodsCounterInter);
      return;
    } else if (timeout === true) {
      this.setState({
        orderDetailMini: true,
      });
      return;
    }
    this.setState({
      orderDetailMini: true,
    });
    this.goodsCounterTimer = setTimeout(() => {
      clearInterval(this.goodsCounterInter);
      this.setState({
        orderDetailMini: false,
        goodsArr: [],
      });
    }, timeout);
  };
  /**
   * 拉取数据，同步至state
   */
  getOrderDetailMiniCounter = async () => {
    try {
      const {data} = await this.props.dispatch({
        type: 'goods/getOrderCounter',
      });
      if (data && data.length) {
        this.setState({
          goodsArr: data,
        });
      } else {
        this.setState({
          goodsArr: [],
        });
      }
    } catch (error) {
      Toast.show('当前网络存在异常');
    }
  };

  listen = async () => {
    try {
      while (!window.socket) {
        await delay(1000);
      }
      if (!window.socket.hasListeners('doorLogin')) {
        // 扫码验证成功
        window.socket.on('doorLogin', this.handleDoorLogin);
      }
      if (!window.socket.hasListeners('doorOpen')) {
        // 按钮开门事件
        window.socket.on('doorOpen', this.doorOpen);
      }
      if (!window.socket.hasListeners('scale')) {
        // 重力感应变化
        window.socket.on('scale', this.handleScaleChange);
      }
      if (!window.socket.hasListeners('talkCall')) {
        // 语音通话中
        window.socket.on('talkCall', this.handleTalkCall);
      }
      if (!window.socket.hasListeners('talkLeave')) {
        // 断开语音通话
        window.socket.on('talkLeave', this.leaveC);
      }
    } catch (e) {
      console.log(e);
    }
  };
  /**
   *  按下按钮开门
   */
  doorOpen = async ({action, sense}) => {
    if (action) this.action = action;
    if (!this.sense && sense) this.sense = sense;
    if (action === '进店') this.action = 'leave';
    else if (action === '出店') this.action = 'enter';
    this.loading(false);
    // 即拿迷你店，唤醒屏幕时间为1分钟
    this.wakeUp();
    if (this.sense) {
      // 进门自动调起刷脸
      if (this.action === 'enter') this.face();
      else if (this.action === 'leave') {
        // 出门身份识别提示
        Speech.speak('正在进行安全检查');
        if (this.state.goodsArr.length === 0) {
          Speech.speak('请点击无购物出店按钮出门');
          return;
        }
        this.setState({orderDetailMini: false});
        const facepay =
          this.state.faceType === 'wxpay' ? this.wxFacepay : this.smilepay;
        await facepay();
        // await facepay();
        // this.getOrderDetailMiniCounter();
        // this.orderDetailMiniPop(30000);
        // this.loading(true, 30000);
      }
    }
  };

  handleTalkCall = async () => {
    try {
      // 加入语音通话
      clearInterval(this.noTalkCall);
      clearInterval(this.callTimeout);
      const {data} = await this.props.dispatch({
        type: 'agora/agora',
      });
      await onTalkCall(data);
      clearTimeout(this.onCallTimeout);
      this.onCallTimeout = setTimeout(() => {
        this.leaveC();
      }, 5 * 60 * 1000);
      await this.setState({
        talkCall: 1,
      });
    } catch (e) {
      console.log(e);
    }
  };

  leaveC = async () => {
    try {
      clearInterval(this.noTalkCall);
      clearInterval(this.callTimeout);
      await leaveTalkCall();
      // if (this.engine) {
      //   await this.engine.leaveChannel();
      // }
      await this.props.dispatch({
        type: 'agora/talkLeave',
      });
      this.setState({
        talkCall: 2,
      });
    } catch (e) {
      console.log(e);
    }
  };

  face = async () => {
    if (this.faceWait) return;
    this.faceWait = true; // 防止重复点击
    setTimeout(() => {
      this.faceWait = false;
    }, 5000);
    await this.setState({
      tipsModal: false,
      goTipsModal: false,
      orderDetailMini: false,
    });
    this.orderDetailMiniPop(false);
    const {faceType} = this.state;
    if (faceType === 'wxpay') {
      this.wechatFace();
    } else {
      // 支付宝刷脸
      this.smileFace();
    }
  };

  // device 代表当前打开的门
  handleScaleChange = async ({count}) => {
    if (count === -1) {
      // 重力感应开始识别
      this.face();
      clearTimeout(this.wakeUpTimeout);
      this.setState({sleep: false});
    } else if (count === 0) {
      // 重力感应归零
      this.leaveC();
      this.setState({
        orderDetailsModal: false,
        phoneModal: false,
        verifyCodeModal: false,
        current: 1,
        tipsModal: false,
        goTipsModal: false,
        loadingModal: false,
        sleep: true,
        tip: '',
      });
    }
  };

  handleDoorLogin = async ret => {
    this.setState({
      type: ret.type,
      code: ret.code,
    });
    if (ret) {
      if (ret.code === 1 && ret.action === 'leave') {
        this.orderDetailMiniPop(false);
      }
      if (ret.code < 0 || ret.code === 401) {
        // 未授权，提示用户扫码验证
        let tipText = ret.msg;
        // 判断扣款方式使用支付分还是代扣
        this.payscoreEnable = !!ret.payscoreEnable;
        Speech.speak(tipText);
        this.userId = ret.userId;
        if (ret.code === 401) {
          // 需要验证手机号
          this.setState({
            phoneModal: true,
            loadingModal: false,
          });
          return;
        }
        if (ret.code === -10 && this.sense) {
          // 无感设备
          this.setQrcode({action: ret.action, tip: tipText, qrcode: true}); // 扫码开通免密支付
          return;
        }
        // else if (ret.orders && ret.orders.length > 0) {
        //   // 有购物订单
        //   let goodsArr = [];
        //   ret.orders.map(v1 => {
        //     v1.goods.map(v2 => {
        //       goodsArr.push(v2);
        //     });
        //   });
        //   this.setState({
        //     orderDetailsModal: true,
        //     loadingModal: false,
        //     goodsArr,
        //     customerPhone: ret.phone || '0000',
        //     current: 1,
        //   });
        // }
        if (ret.action && !/您没有进店信息/.test(tipText)) {
          this.setQrcode({action: ret.action, tip: tipText});
        } else {
          this.setState({
            tip: tipText,
            tipsModal: true,
            loadingModal: false,
            qrCode: null,
          });
        }
      } else if (ret.msg) {
        let tipText = ret.msg.replace(/扫码/g, '人脸识别');
        Speech.speak(tipText);
        if (ret.code !== 1) {
          this.setState({tip: tipText, tipsModal: true, loadingModal: false});
        } else if (this.sense) {
          this.setState({loadingModal: false});
          if (ret.action === 'enter') {
            // 轮询获取订单数据
            this.goodsCounterInter = setInterval(() => {
              this.getOrderDetailMiniCounter();
            }, 1000);
            this.orderDetailMiniPop(600000); // 十分钟后关闭弹窗
          }
        }
      }
    } else {
      Speech.speak('正在重新识别，请靠中间站稳');
    }
  };

  setQrcode = ({action, tip, qrcode}) => {
    let p = 'j';
    if (this.sense) p = 's';
    if (this.state.stype === 'guard') p = 'g';
    const state = {
      qrCode: `${qrHost}/#/store-${action || 'leave'}-${p}${this.storeKey}`,
    };
    if (tip) {
      state.tip = tip;
      if (qrcode) {
        state.tipsModal = false;
        state.goTipsModal = true;
      } else state.tipsModal = true;
      state.loadingModal = false;
    }
    this.setState(state);
  };

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

  // 微信人脸身份识别
  wechatFace = async () => {
    const {orderDetailsModal, tipsModal} = this.state;
    if (orderDetailsModal || tipsModal) {
      // 出现订单弹窗，不做人脸识别
      return;
    }
    const tipText = '正在人脸识别';
    Speech.speak(tipText);
    // this.setState({tip: tipText, tipsModal: true});
    let auth = this.rawinfo;
    if (
      auth.return_code === 'SUCCESS' ||
      (auth.code === 1 && auth.data.bizCode === '0000')
    ) {
      if (auth.data) {
        auth = auth.data;
      }
      const params = {
        appid: auth.appid || auth.subAppId,
        mch_id: auth.mch_id || auth.subMchId,
        store_id: this.storeKey,
        authinfo: auth.authinfo || auth.authInfo,
        face_authtype: 'FACEID-ONCE',
        ask_unionid: 1,
      };
      let res = (await WxFacepay.faceinfo(params)) || {};
      if (!res.openid && !AutoClick.enable) {
        // 返回错误自动重新识别
        res = (await WxFacepay.faceinfo(params)) || {};
      }
      if (window.socket) {
        // 返回结果，立即重新连接socket
        window.socket.connect();
      }
      if (!res.openid) {
        this.payscoreEnable = false;
        // 返回错误出现二维码扫码
        this.goTips();
        return;
      }
      if (res.sub_openid) {
        res.openid = res.sub_openid;
      }
      this.faceinfo = {...res};
      await this.wxdoor();
    }
  };

  // 微信人脸身份识别且开通支付分
  payscore = async () => {
    const {orderDetailsModal, tipsModal} = this.state;
    if (orderDetailsModal || tipsModal) {
      // 出现订单弹窗，不做人脸识别
      return;
    }
    let tipText = '正在人脸识别';
    if (!WxFacepay.getUserPayScoreStatus) {
      tipText = '请扫码确认';
      if (this.sense) tipText = '请扫码开通支付分进店';
    }
    Speech.speak(tipText);
    if (!WxFacepay.getUserPayScoreStatus) {
      this.setQrcode({action: this.action, tip: tipText, qrcode: true});
      return;
    }
    const data = await this.payscoreinfo();
    if (data.code === 1) {
      const out_trade_no = data.data.orderId;
      const payscore_out_request_no = data.data.authorizationCode;
      const payscore_service_id = data.data.payscoreId;
      let auth = (await this.payscoreAuthinfo()) || {};
      if (
        auth.return_code === 'SUCCESS' ||
        (auth.code === 1 && auth.data.bizCode === '0000')
      ) {
        if (auth.data) {
          auth = auth.data;
        }
        const params = {
          appid: auth.appid || auth.subAppId,
          mch_id: auth.mch_id || auth.subMchId,
          out_trade_no,
          authinfo: auth.authinfo || auth.authInfo,
          payscore_out_request_no,
          payscore_service_id,
          ask_unionid: 1,
        };
        let res = await WxFacepay.getUserPayScoreStatus(params);
        if (!res.openid && !AutoClick.enable) {
          // 返回错误自动重新识别
          res = (await WxFacepay.getUserPayScoreStatus(params)) || {};
        }
        if (window.socket) {
          // 返回结果，立即重新连接socket
          window.socket.connect();
        }
        if (!res.openid) {
          // 返回错误出现二维码扫码
          this.payscoreEnable = false;
          this.goTips();
          return;
        }
        this.faceinfo = {
          orderId: out_trade_no,
          authCode: payscore_out_request_no,
          ...res,
        };
        await this.wxdoor();
      }
    }
  };

  wxdoor = async () => {
    this.loading(true);
    const action = {
      type: 'store/wxdoor',
      openid: this.faceinfo.openid,
      wxtoken: this.faceinfo.token || '',
      nickname: this.faceinfo.nickname || '',
      orderId: this.faceinfo.orderId || '',
      authCode: this.faceinfo.authCode || '',
    };
    if (validity.phone.test(this.phone)) action.phone = this.phone;
    if (this.sense) action.sense = true;
    if (this.state.stype) action.stype = this.state.stype;
    const ret = await this.props.dispatch(action);
    this.phone = '';
    this.loading(false);
    this.handleDoorLogin(ret);
  };

  // 获取用户支付分状态
  payscoreinfo = async () => {
    const {data} = await this.props.dispatch({
      type: 'goods/payscoreinfo',
    });
    return data;
  };

  // 获取刷脸支付调用凭证
  payscoreAuthinfo = async () => {
    const rawdata = await WxFacepay.rawdata();
    const {data} = await this.props.dispatch({
      type: 'goods/wxauthinfo',
      rawdata,
    });
    return data;
  };

  alipayinfo = async () => {
    const {data} = await this.props.dispatch({type: 'goods/alipayinfo'});
    this.alipayInfo = await Smilepay.init(data);
    if (this.alipayInfo.code === '1000')
      this.alipayInfo.metaInfo = JSON.parse(this.alipayInfo.metaInfo);
    return this.alipayInfo;
  };

  smileFace = async () => {
    const {orderDetailsModal, tipsModal} = this.state;
    if (orderDetailsModal || tipsModal) {
      return;
    } // 出现订单弹窗，不做人脸识别
    const tipText = '正在人脸识别';
    Speech.speak(tipText);
    await this.alipayinfo();
    if (!this.alipayInfo || !this.alipayInfo.metaInfo) return;
    const {data} = await this.props.dispatch({
      type: 'goods/smilepay',
      service_id: 'auth',
      zimmetainfo: this.alipayInfo.metaInfo,
    });
    if (data.code === 1) {
      const res = await Smilepay.verify(JSON.parse(data.data));
      if (res.code !== '1000') {
        Toast.show(res.msg);
        this.goTips();
        return;
      }
      this.loading(true);
      const action = {
        type: 'store/wxdoor',
        alipayUid: res.uid,
      };
      if (this.sense) action.sense = true;
      if (this.state.stype) action.stype = this.state.stype;
      const ret = await this.props.dispatch(action);
      this.loading(false);
      this.handleDoorLogin(ret);
    }
  };

  loading = (flag, timeout) => {
    this.setState({
      loadingModal: flag,
    });
    if (flag && timeout) {
      // 自动关闭加载界面
      this.wakeUp(timeout);
      clearTimeout(this.loadingTimeout);
      this.loadingTimeout = setTimeout(() => {
        this.setState({
          loadingModal: false,
        });
      }, timeout);
    }
  };

  // 语音通话请求
  onCall = async () => {
    await this.setState({
      tipsModal: false,
      goTipsModal: false,
      type: '',
    });
    const {talkCall} = this.state;
    if (talkCall === 2) {
      Speech.speak('正在接通中请稍候');
      this.talkCall();
      clearInterval(this.noTalkCall);
      this.noTalkCall = setInterval(() => this.talkCall(), 10000);
      this.setState({
        talkCall: 0,
      });
      clearInterval(this.callTimeout);
      this.callTimeout = setTimeout(() => {
        clearInterval(this.noTalkCall);
        this.setState({
          talkCall: 2,
        });
      }, 30000);
    }
  };

  talkCall = () => {
    this.props.dispatch({
      type: 'agora/talkCall',
    });
  };

  dropUp = () => {
    let {current} = this.state;
    if (current > 1) {
      this.setState({
        current: --current,
      });
    }
  };

  dropDown = goodsLength => {
    let {current} = this.state;
    if (current < goodsLength) {
      this.setState({
        current: ++current,
      });
    }
  };

  wakeUp = (timeout = 60000) => {
    this.setState({sleep: false, tipsModal: false, goTipsModal: false});
    clearTimeout(this.wakeUpTimeout);
    this.wakeUpTimeout = setTimeout(() => {
      this.setState({sleep: true, tipsModal: false, goTipsModal: false});
    }, timeout);
    if (this.state.stype === 'guard') this.face();
  };

  goTips = async () => {
    if (this.payscoreEnable) {
      await this.setState({tipsModal: false});
      // this.payscore();
    } else {
      Speech.speak('请扫码开门');
      this.setQrcode({action: this.action, tip: '请扫码开门', qrcode: true});
    }
  };

  goToo = async () => {
    await this.setState({tipsModal: false, goTipsModal: false, type: ''});
    window.socket.emit('jokerOpen', true, 'enter');
  };

  wxFacepay = async () => {
    const {data} = this.rawinfo;
    const auth = data;
    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;
        Speech.speak('刷脸支付启动失败，正在重新启动应用进行修复，请稍等...');
        Restart.restartApp();
      } else {
        this.faceRetry = true;
        await this.wxFacepay(); // 重试
      }
      return;
    }
    let res = await WxFacepay.facepay(params);
    if (!res && !AutoClick.enable) {
      res = await WxFacepay.facepay(params);
    }
    if (res.face_code) {
      const data = await this.balancePay(res.sub_openid);
      if (data.code !== 1) {
        await this.barcodePay(res.face_code, true, res.sub_openid);
      }
      this.faceRetry = false;
    }
  };

  smilepay = async () => {
    await this.alipayinfo();
    if (!this.alipayInfo || !this.alipayInfo.metaInfo) {
      Speech.speak('刷脸支付启动失败，正在重新启动应用进行修复，请稍等...');
      Restart.restartApp();
      return;
    }
    const {data} = await this.props.dispatch({
      type: 'goods/smilepay',
      zimmetainfo: this.alipayInfo.metaInfo,
    });
    if (data.code === 1) {
      const res = await Smilepay.verify(JSON.parse(data.data));
      if (res.code !== '1000') {
        Toast.show(res.msg);
        return;
      }
      // TODO: 编写 balancePay 和 barcodepay
      const balanceData = await this.balancePay(res.uid);
      if (balanceData.code !== 1) {
        await this.barcodePay(res.fToken, true, null, res.fToken, res.uid);
      }
    }
  };

  getGoods = () => {
    const {goodsArr} = this.state;
    const ids = {};
    const noBarcode = [];
    goodsArr.map(({barcode, num, prePrice, name}) => {
      if (barcode !== '000000') {
        // 非无码商品
        if (!ids[barcode]) {
          ids[barcode] = num;
        } else {
          ids[barcode] += num;
        }
      } else {
        noBarcode.push({
          name,
          barcode,
          price: 0,
          purPrice: 0,
          prePrice,
          num,
          weight: 0,
        });
      }
    });
    return {ids, noBarcode};
  };

  successPay = async balance => {
    Toast.hide();
    const msg = balance
      ? '余额付款成功，祝您生活愉快~'
      : '付款成功，祝您生活愉快~';
    this.props.dispatch({
      // 购物完成步骤
      type: 'app/step',
      step: 3,
    });
    Speech.speak(msg);
  };

  balancePay = async openid => {
    if (this.barcodeBusy) return true;
    Toast.loading('正在付款，请稍后~');
    this.barcodeBusy = true;
    const {ids, noBarcode} = this.getGoods();
    const {data} = await this.props.dispatch({
      type: 'goods/balancePay',
      ids,
      noBarcode,
      openid,
    });
    if (data.code === 1) {
      this.orderId = data.data.orderId;
      this.successPay(true);
      await AutoClick.clickBackKey();
      await wait(1200);
      this.barcodeBusy = false;
      return data;
    }
    this.barcodeBusy = false;
    return data;
  };

  barcodePay = async (code, facepay, openid, fToken, uid) => {
    if (this.barcodeBusy) return true;
    Toast.loading('正在付款，请稍后');
    const isWxpay = code.toString().match(/1[0-5]\d{16}/);
    const isAlipay = fToken || code.toString().match(/^(2[5-9]|30)\d{14,22}$/);
    if (!isWxpay && !isAlipay) return false;
    this.barcodeBusy = true;
    let successPay = false;
    const {ids, noBarcode} = this.getGoods();
    const res = await this.props.dispatch({
      type: 'goods/barcodepay',
      ids,
      code,
      facepay,
      noBarcode,
      openid,
      fToken,
      uid,
    });
    if (res.code !== 1) {
      Toast.info(`${res.msg}`);
      Speech.speak(res.msg);
      this.setState({orderDetailMini: true});
    }
    if (res.code === 1) {
      this.orderId = res.data.orderId;
      if (res.data.alipayUserId) {
        // 没有匹配到支付宝用户
        const voiceTitle =
          '为了正常出店，首次使用支付宝付款码，请用进店微信扫描屏幕二维码';
        // this.orderId = res.data.orderId;
        this.alipayUserId = res.data.alipayUserId;
        Speech.speak(voiceTitle);
      } else {
        this.successPay();
        successPay = true;
        await wait(1200);
      }
    } else if (res.code === 2) {
      // 等待付款
      for (let i = 0; i < 20; ++i) {
        await wait(3000);
        const status = await this.props.dispatch({
          type: 'goods/status',
          orderId: this.faceinfo.orderId,
        });
        if (status.code === 1 && status.data === 1) {
          this.successPay();
          successPay = true;
          await wait(1200);
          break;
        }
      }
    } else if (res.code === 3) {
      this.setState({orderDetailMini: true});
      await wait(res.data.timeout);
    } else {
      this.setState({orderDetailMini: true});
      await wait(1200);
    }
    this.barcodeBusy = false;
    if (successPay) {
      return 'SUCCESS';
    }
    return true;
  };

  onNoBuy = async () => {
    const {data} = await this.props.dispatch({type: 'store/noBuyGoGoGo'});
    console.log('data', data);
    Speech.speak(data.msg);
  };

  render() {
    const {
      verifyCodeModal,
      phoneModal,
      orderDetailMini,
      goodsArr,
      talkCall,
      storeName,
      contact,
      tip,
      tipsModal,
      sleep,
      faceType,
      loadingModal,
      qrCode,
      goTipsModal,
      type,
      code,
      stype,
    } = this.state;
    let flag = '';
    if (type === 'over' && (code === -9 || code === -10)) {
      flag = '我已付款';
    } else if (type === 'loss' && (code === -9 || code === -10)) {
      flag = '确认出店';
    } else {
      flag = '';
    }
    let {dispatch, admin} = this.props;
    if (faceType === 'alipay') {
      styles.header = {...styles.header, backgroundColor: '#1b7dc7'};
      styles.btnCome = {...styles.btnCome, backgroundColor: '#1b7dc7'};
      styles.footer = {...styles.footer, backgroundColor: '#1b7dc7'};
      styles.onCall = {...styles.onCall, backgroundColor: '#1b7dc7'};
    }
    return sleep && !orderDetailMini && stype !== 'guard' ? (
      <Screensaver onPress={this.wakeUp} />
    ) : (
      <View style={styles.content}>
        <PhoneModal
          visible={phoneModal}
          transparent
          onCall={() => this.setState({phoneModal: false})}
          onSubmit={this.onSubmit}
          faceType={faceType}
        />
        <VerifyCodeModal
          visible={verifyCodeModal}
          transparent
          onCall={() => this.setState({verifyCodeModal: false})}
          onSubmit={this.onCodeSubmit}
          faceType={faceType}
        />
        {/* <OrderDetailsModal
          visible={orderDetailsModal}
          transparent
          maskClosable
          onClose={this.handleOrderClose}
          onRequestClose={this.handleOrderClose}
          onCall={this.onCall}
          dropUp={this.dropUp}
          dropDown={this.dropDown}
          goodsArr={goodsArr}
          dispatch={dispatch}
          talkCall={talkCall}
          customerPhone={customerPhone}
          current={current}
          faceType={faceType}
        /> */}
        <OrderDetailMini
          visible={orderDetailMini}
          transparent
          onRequestClose={this.handleOrderClose}
          goodsArr={goodsArr}
          dispatch={dispatch}
          faceType={faceType}
          onGoBack={this.onNoBuy}
        />
        <TipsModal
          visible={tipsModal}
          transparent
          title={'开门失败'}
          tip={tip}
          leftText={'回店核对'}
          contentText={flag}
          rightText={'呼叫客服'}
          leftTouch={this.goToo}
          contentTouch={flag === '' ? '' : this.goTips}
          rightTouch={this.onCall}
          onMaskPress={() => this.setState({tipsModal: false})}
          faceType={faceType}
          tryFace={this.face}
        />
        <TipsModal
          visible={goTipsModal}
          transparent
          title="温馨提示"
          qrCode={qrCode}
          tip={tip}
          onMaskPress={() => this.setState({goTipsModal: false})}
          faceType={faceType}
          tryFace={this.face}
        />
        <LoadingModal transparent visible={loadingModal} />
        <View style={styles.header}>
          <View style={styles.title}>
            <View style={styles.left}>
              <Image
                source={require('../assets/logo2.png')}
                style={styles.imgs}
              />
              <Text style={styles.text}>{storeName}</Text>
            </View>
            <View style={styles.right}>
              <Text style={styles.text}>{contact}</Text>
              <Image style={styles.phone} source={phone} />
            </View>
          </View>
          <View style={styles.headline}>
            <Text style={styles.headTitle}>刷脸开门系统</Text>
          </View>
        </View>
        <View style={styles.face}>
          <View style={styles.faceRecogn}>
            <Touch style={styles.faceGif} onPress={this.face} feedback={false}>
              <Image
                source={require('../assets/Vertical/face.gif')}
                style={{flex: 1, width}}
              />
            </Touch>
          </View>
          {!admin.autoClick && (
            <Touch
              onPress={this.setting}
              style={{
                position: 'absolute',
                width: scaleSize(100),
                height: scaleSize(100),
                bottom: scaleSize(200),
                right: 0,
                backgroundColor: 'rgba(0,0,0,0.1)',
                alignItems: 'center',
                justifyContent: 'center',
                borderRadius: 10,
                zIndex: 999,
              }}>
              <Icons
                name="accessibility"
                style={{fontSize: setSpText(60), color: '#fff'}}
              />
            </Touch>
          )}
          <Touch onPress={this.face} style={styles.btnCome} feedback={false}>
            <View style={styles.click}>
              <Image
                source={
                  faceType === 'wxpay'
                    ? require('../assets/wxpay.png')
                    : require('../assets/Vertical/alipay01.png')
                }
                style={styles.wxpay}
                tintColor="white"
              />
              <Text style={styles.clickText}>点击进入</Text>
              <Image
                source={require('../assets/finger.png')}
                style={styles.finger}
              />
              <Text style={styles.clickText}>刷脸开门</Text>
            </View>
          </Touch>
        </View>
        <View style={styles.footer}>
          {talkCall === 1 ? (
            <View style={styles.footercall}>
              <View style={styles.call}>
                <Image
                  source={
                    faceType === 'wxpay'
                      ? require('../assets/call.gif')
                      : require('../assets/call_blue.gif')
                  }
                  style={styles.callGif}
                />
                <Text style={styles.callText}>正在语音通话中</Text>
              </View>
            </View>
          ) : talkCall === 0 ? (
            <View style={styles.footercall}>
              <View style={styles.call}>
                <Image
                  source={
                    faceType === 'wxpay'
                      ? require('../assets/call.gif')
                      : require('../assets/call_blue.gif')
                  }
                  style={styles.callGif}
                />
                <Text style={styles.callText}>正在接通中请稍候...</Text>
              </View>
            </View>
          ) : (
            <Touch
              onPress={this.onCall}
              style={styles.footercall}
              feedback={false}>
              <View style={styles.call}>
                <Image
                  source={
                    faceType === 'wxpay'
                      ? require('../assets/call.gif')
                      : require('../assets/call_blue.gif')
                  }
                  style={styles.callGif}
                />
                <Text style={styles.callText}>呼叫客服</Text>
              </View>
            </Touch>
          )}
          <View style={styles.goFoot}>
            <View
              style={{
                borderWidth: 10,
                borderColor: '#fff',
                width: scaleSize(220),
                height: scaleSize(220),
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <QRCode
                value={qrCode || `${qrHost}/#/account`}
                size={scaleSize(190)}
              />
            </View>
            <Text style={styles.goText}>扫码开门</Text>
          </View>
        </View>
      </View>
    );
  }
}

const styles = {
  content: {
    position: 'relative',
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  header: {
    flex: 0.2,
    backgroundColor: 'rgb(0,205,102)',
    width: '100%',
    flexDirection: 'column',
  },
  title: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: scaleSize(30),
    marginRight: scaleSize(30),
    marginTop: scaleSize(10),
  },
  headline: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
    marginBottom: scaleSize(20),
  },
  headTitle: {
    fontSize: setSpText(70),
    color: '#fff',
  },
  left: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: scaleSize(45),
  },
  imgs: {
    width: scaleSize(60),
    height: scaleSize(60),
    marginRight: scaleSize(20),
    resizeMode: 'contain',
  },
  right: {
    flexDirection: 'row-reverse',
    alignItems: 'center',
    marginTop: scaleSize(45),
  },
  img: {
    width: scaleSize(40),
    height: scaleSize(40),
    marginRight: scaleSize(20),
    resizeMode: 'contain',
  },
  text: {
    color: '#FFFFFF',
    fontSize: setSpText(35),
  },
  phone: {
    width: scaleSize(40),
    height: scaleSize(40),
    marginRight: scaleSize(25),
    resizeMode: 'contain',
  },
  face: {
    flex: 0.6,
    width: '100%',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'space-around',
    position: 'relative',
  },
  faceRecogn: {
    flex: 0.7,
  },
  faceGif: {
    position: 'relative',
    zIndex: 2,
  },
  btnCome: {
    flex: 0.13,
    backgroundColor: 'rgb(0,205,102)',
    width: '85%',
    borderRadius: scaleSize(20),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    elevation: 2,
  },
  click: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  clickText: {
    fontSize: setSpText(50),
    color: '#fff',
    marginLeft: setSpText(10),
  },
  wxpay: {
    width: scaleSize(67),
    height: scaleSize(61),
    marginRight: scaleSize(20),
  },
  finger: {
    width: scaleSize(60),
    height: scaleSize(80),
    marginLeft: scaleSize(120),
    marginRight: scaleSize(20),
  },
  footer: {
    flex: 0.2,
    width: '100%',
    flexDirection: 'row',
    backgroundColor: 'rgb(68, 197, 114)',
  },
  call: {
    felx: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: scaleSize(20),
  },
  callGif: {
    width: scaleSize(300),
    height: scaleSize(150),
    marginLeft: scaleSize(-100),
    marginTop: scaleSize(80),
  },
  callText: {
    fontSize: setSpText(70),
    color: '#fff',
    marginTop: setSpText(80),
    marginLeft: setSpText(-70),
  },
  onCall: {
    flex: 0.7,
    width: '100%',
    // backgroundColor: '#44c571',
    backgroundColor: 'rgb(68, 197, 114)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  onCallText: {
    fontSize: setSpText(60),
    color: '#fff',
    paddingTop: scaleSize(30),
    paddingLeft: scaleSize(-30),
  },
  footercall: {
    flex: 0.7,
    borderRightColor: '#fff',
    borderRightWidth: 2,
  },
  goFoot: {
    flex: 0.3,
    justifyContent: 'center',
    alignItems: 'center',
  },
  goText: {
    color: '#fff',
    fontSize: setSpText(40),
    paddingTop: scaleSize(10),
  },
};

export default connect(({store}) => ({store}))(FacePage);
