import React, { Component } from 'react';
import { Router, Route, Link } from 'react-router-dom';
import { Button, Icon, ActionSheet, Toast, Modal } from 'antd-mobile';
import AmountInput from 'components/AmountInput/AmountInput';
import ModalDiaLog from 'components/ModalDiaLog/ModalDiaLog';
import Header from 'components/Header/Header';
import PwdKeyboard from 'pages/setting/PwdKeyboard.js';
import Ajax from 'ajax';
import plusReady from 'plugins/plusReady';
import ActionConfig from 'config/actionConfig.js';
import skipConfig from 'config/config.js';
import commonTool from 'utils/commonTool.js';
import errorMsg from 'config/errorConfig.js';
import { queryAccount } from '../query-account/queryAccount.js';
import { Storage } from 'storage';
import './view.scss';

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
let pwdTran;
let pwdTranStr;
export default class TransferAccounts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // 转账金额
      account: '',
      // 资金账号
      accountNumber: '美元',
      currency: 'USD',
      checkFlag: false,
      tradeAccountBalance: 0,
      bankCardsList: {},
    };
    this.currArray = ['取消'];
    this.bankCardsList = {};
    this.doTransferAccount = this
      .doTransferAccount
      .bind(this);
    this.showAccountOption = this
      .showAccountOption
      .bind(this);
    this.handleCheck = this
      .handleCheck
      .bind(this);
    this.transferAllAmount = this
      .transferAllAmount
      .bind(this);
    this.caculateCharge = this.caculateCharge.bind(this);
    this.alertInstance = {};
    window.backFunc = () => {
      if (document.getElementsByClassName('am-number-keyboard-wrapper-hide').length === 0) {
        document.getElementsByClassName('keyboard-hide')[0].click();
      } else if (Object.keys(this.alertInstance).length !== 0) {
        pwdTran.removePassword();
        this.alertInstance.close();
        this.alertInstance = {};
      } else {
        window.history.go(-1);
      }
    };
  }
  componentWillMount() {
    commonTool.gtjaBurialPoint('293006');
    this.queryBankCardsList();
    queryAccount((res) => {
      if (res.success) {
        this.tradeAccountBalance();
      }
    });
  }
  tradeAccountBalance() {
    const tradeAccountList = Storage.getItem('tradeAccountList', true);
    let currencyAccount;
    tradeAccountList && tradeAccountList.map((i, index) => {
      if (i.CURRENCY === this.state.currency) {
        currencyAccount = i;
      }
    });
    this.setState({ tradeAccountBalance: currencyAccount.EXTRACT_AMT });
  }
  queryBankCardsList() {
    const param = {
      CUSTOMER_ID: Storage.getItem('customerId'),
      TRADE_ACCOUNT: Storage.getItem('tradeAccount'),
      BOOKING_ID: skipConfig.bookingId,
    };
    const url = ActionConfig[Storage.getItem('customerType')][0].queryCustomerBankCard;
    Ajax(url, param).then((res) => {
      console.log('查询返回');
      console.log(res);
      if (res.success) {
        console.log(res);
        res
          .data
          .result
          .datals
          .map((i, index) => {
            i.currency = i.BANKCARD_CURRENCYS;
            this
              .currArray
              .unshift(this.transEngToChin(i.currency));
            this.bankCardsList[i.currency] = i;
          });
        this.setState({
          bankCardsList: this.bankCardsList,
        });
      } else {
        console.log(res);
      }
    }, (err) => {
      console.log('error');
    });
  }
  passWordBox() {
    return (
      <div className="confirm-content">
        <div className="password-content pwdTran" />
      </div>
    );
  }
  testPwdOne() {
    const box1 = document.getElementsByClassName('pwdTran')[0];
    const alertHeight = document.getElementsByClassName('am-modal-content')[0].offsetHeight;
    const left = ((document.body.offsetWidth - 270) / 2) + 15;
    const top = ((document.body.offsetHeight - alertHeight) / 2) + 65;
    pwdTran = new PwdKeyboard({
      'left': left, 'top': top, 'width': 200, 'height': box1.clientHeight,
    });
  }
  transferAllAmount() {
    commonTool.gtjaBurialPoint('293008');
    this.setState({
      account: this.state.tradeAccountBalance,
    }, this.caculateCharge);
  }
  doTransferAccount() {
    commonTool.gtjaBurialPoint('293009');
    if (!this.state.bankCardsList[this.state.currency]) {
      Toast.info('您还未填写银行账户信息，需临柜补充后方可申请资金转出！', 1);
      return false;
    }
    if (!this.state.currency) {
      Toast.info('请选择转出币种！', 1);
      return false;
    }
    if (this.state.account === 0 && this.state.account != null) {
      Toast.info('转账金额不能为空！', 1);
      return false;
    }
    if (this.state.account === '0') {
      Toast.info('转账金额不能为零！', 1);
      return false;
    }
    if ((this.state.tradeAccountBalance * 1) < this.state.account) {
      Toast.info('您的余额不足，无法出金！', 1);
      return false;
    }
    if (!this.state.checkFlag) {
      Toast.info('您还未同意国泰君安转账费用相关说明！', 1);
      return false;
    }
    const self = this;
    plusReady(() => {
      self.alertInstance = Modal.alert(<div>
        <span>交易密码</span>
      </div>, this.passWordBox(), [
        {
          text: '取消',
          onPress: () => {
            console.log('cancel');
            pwdTran.removePassword();
          },
        }, {
          text: '确定',
          onPress: () => {
            pwdTran.getPassword((pwd) => {
              pwdTranStr = JSON
                .parse(pwd)
                .password;
              this.setState({
                transferPwd: pwdTranStr,
              }, this.ajaxTransferAccount);
              pwdTran.removePassword();
            });
          },
        },
      ]);
      setTimeout(() => {
        self.testPwdOne();
      }, 1000);
    });
  }
  ajaxTransferAccount() {
    Toast.loading('交易中...', 0);
    const param = {
      CUSTOMER_ID: Storage.getItem('customerId'),
      TRADE_ACCOUNT: Storage.getItem('tradeAccount'),
      TRADE_AMT: this.state.account,
      CURRENCY_INFO: `${this.state.currency}:2`,
      BANK_CARD: this.state.bankCardsList[this.state.currency].BANKCAR_CODE,
      TRANSFER_PWD: this.state.transferPwd,
      FEE: this.state.poundageTotal,
    };
    const url = ActionConfig[Storage.getItem('customerType')][0].outAmount;
    Ajax(url, param).then((res) => {
      Toast.hide();
      if (res.success) {
        Toast.info('转出成功！', 1, () => {
          queryAccount();
          window.history.go(-1);
        });
      } else {
        this.setState({
          errorFlag: true,
          errorMsg: commonTool.transformErrMsg(res.message),
        });
      }
    }, (err) => {
      console.error(err);
      Toast.hide();
    });
  }
  caculateCharge() {
    // 计算转账费用
    const param = {
      CUSTOMER_TYPE: Storage.getItem('customerType') === 'personal'
        ? '0'
        : '1',
      FUND_ACCOUNT: this.state.account,
      FUND_CURRENCY: this.state.currency,
      SCENE: '2',
    };
    const url = ActionConfig[Storage.getItem('customerType')][0].queryPoundage;
    Ajax(url, param).then((res) => {
      if (res.success) {
        console.log('查询成功！');
        this.setState({ poundageTotal: res.data.result.POUNDAGE_TOTAL });
      }
    }, (err) => {
      console.error(err);
    });
  }
  handleAccount(val) {
    this.setState({
      account: val,
    });
  }
  handleCheck(even) {
    console.log(even.target.checked);
    this.setState({ checkFlag: even.target.checked });
  }
  transEngToChin(chi) {
    let str;
    switch (chi) {
      case 'USD':
        str = '美元';
        break;
      case 'HKD':
        str = '港币';
        break;
      case 'EUR':
        str = '欧元';
        break;
      case 'JPY':
        str = '日元';
        break;
      case 'GBP':
        str = '英镑';
        break;
      case 'AUD':
        str = '澳大利亚元';
        break;
      case 'CHF':
        str = '瑞士法郎';
        break;
      default:
        str = '';
        break;
    }
    return str;
  }
  transChinToEng(chi) {
    let str;
    switch (chi) {
      case '美元':
        str = 'USD';
        break;
      case '港币':
        str = 'HKD';
        break;
      case '欧元':
        str = 'EUR';
        break;
      case '日元':
        str = 'JPY';
        break;
      case '英镑':
        str = 'GBP';
        break;
      case '澳大利亚元':
        str = 'AUD';
        break;
      case '瑞士法郎':
        str = 'CHF';
        break;
      default:
        str = '';
        break;
    }
    return str;
  }
  showAccountOption() {
    const BUTTONS = this.currArray;
    // const BUTTONS = ['美元', '港币', '欧元', '日元', '英镑', '澳大利亚元', '瑞士法郎', '取消'];
    ActionSheet.showActionSheetWithOptions({
      options: BUTTONS,
      cancelButtonIndex: BUTTONS.length - 1,
      destructiveButtonIndex: BUTTONS.length - 2,
      // title: 'title',
      message: '请选择转出币种',
      maskClosable: true,
      'data-seed': 'logId',
      wrapProps,
    }, (buttonIndex) => {
      commonTool.gtjaBurialPoint('293007');
      BUTTONS[buttonIndex] !== '取消' && this.setState({
        accountNumber: BUTTONS[buttonIndex],
        currency: this.transChinToEng(BUTTONS[buttonIndex]),
        account: '',
      }, this.tradeAccountBalance);
    });
  }
  render() {
    return (
      <div id="TransferAccounts">
        <Header>转出</Header>
        <div className="transfer-content">
          <ul className="">
            <li>
              <label>付款账户</label>
              <span>{Storage.getItem('tradeAccount')}</span>
            </li>
            <li>
              <label>转出币种</label>
              <Icon type="right" size="md" color="#dddddd" />
              <Button
                type="primary"
                inline
                className="select-account"
                onClick={this.showAccountOption}
              >{this.state.accountNumber}
              </Button>
            </li>
            <li>
              <label>银行账号</label>
              <span>{this.state.bankCardsList[this.state.currency] && this.bankCardsList[this.state.currency].BANKCAR_CODE}</span>
            </li>
            <li>
              <label>可取资金</label>
              <span>{this.state.tradeAccountBalance}&emsp;{this.state.currency}</span>
            </li>
            <li>
              <label>转账金额</label>
              <div className="input-number">
                <AmountInput
                  currency={this.state.currency}
                  value={`${this.state.account}`}
                  getInputValue={this.handleAccount.bind(this)}
                  onBlur={this.caculateCharge}
                />
              </div>

              <div onClick={this.transferAllAmount} className="trasfer-all">全部转出</div>
            </li>
            <li>
              <label>转账费用</label>
              <span>{this.state.poundageTotal}&emsp;{this.state.currency}</span>
            </li>
          </ul>
          <input
            className="input-check"
            id="myInput"
            type="checkbox"
            onChange={this.handleCheck}
          />
          <label htmlFor="myInput">我已阅读并同意<Link to="/DisClaimerText">《国泰君安出入金免责声明》</Link>
          </label>
        </div>
        <Button
          type="primary"
          inline
          activeClassName="default-btn-active"
          className="default"
          onClick={this.doTransferAccount}
        >提交
        </Button>
        <ModalDiaLog
          visible={this.state.errorFlag}
          onClose={() => {
            this.setState({ errorFlag: false });
          }}
          errMsg={this.state.errorMsg}
        />
      </div>
    );
  }
}
