import AsyncStorage from '@react-native-community/async-storage';
import Modal from '../components/Modal';
import Toast from '../components/Toast';
import Speech from '../utils/Speech';
import {counterInterval} from './authInterval';

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

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

export const counterLogin = async ({key, secret, device = 'counter', host}) => {
  if (!key) {
    await loginError('请输入门店标识');
    return;
  }
  if (!secret) {
    await loginError('请输入门店密钥');
    return;
  }
  const supportDevices = [
    'counter',
    'face',
    'smoke',
    'faceEnter',
    'faceLeave',
    'order',
    'guard',
  ];
  if (supportDevices.indexOf(device) < 0) {
    await loginError('不支持的设备类型');
    return;
  }
  await Toast.loading('授权认证中');
  if (device === 'smoke') device = 'faceSmoke';
  const action = {type: 'admin/auth', key, secret, login: device, host};
  // const { dispatch } = this.props;
  // const res = await dispatch(action);
  const res = await window.dispatch(action);
  if (res.code === 1) {
    Toast.success('授权认证成功，正在重启应用...', 2, async () => {
      await counterInterval(window.dispatch, res.data.expiresIn, true);
    });
  }
};

export default {showCounterLogin, counterLogin};
