import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import ModalDiaLog from 'components/ModalDiaLog/ModalDiaLog';
import PriceList from 'components/PriceList/PriceList';
import H5NumberInput from 'components/H5NumberInput/H5NumberInput';
import { Button, Slider, Modal, Icon, Toast } from 'antd-mobile';
import Ajax from 'ajax';
import ActionConfig from 'config/actionConfig.js';
import { requestPublicPipParams, preparePublicParams } from 'utils/staticParams';
import errorMsg from 'config/errorConfig.js';
import commonTool from 'utils/commonTool.js';
import skipConfig from 'config/config.js';
import { queryAccount } from '../query-account/queryAccount.js';
import { Storage } from 'storage';
import questionMask from '../../style/iconImage/questionMark.png';
import './view.scss';

const QUERY_FAILD = '查询失败';

class FirmTradeIndex extends Component {
  constructor(props) {
    super(props);
    const objectId = this.props.pid.replace('|', '/');
    // const staticParams = this.getStaticParams(objectId);
    this.state = {
      objectId,
      code1: objectId.split('/')[0],
      code2: objectId.split('/')[1],
      direct: this.props.location.search.split('?')[1],
      currency: objectId.split('/')[0],
      pip: 2,
      // pip: staticParams.defaultPip,
      // defaultPip: staticParams.defaultPip,
      // maxPip: staticParams.maxPip,
      maxPip: 10,
      account: '',
      budgetAccount: 0,
      tradeAccountBalance: 0,
    };
    this.alertInstance = {};
    this.referenceRate = this.state.direct === 'buy' ? this.props.priceObject[this.state.objectId].ASK_RATE : this.props.priceObject[this.state.objectId].OFFER_RATE;
    this.doFirmTrade = this.doFirmTrade.bind(this);
    this.closeAlert = this.closeAlert.bind(this);
    this.showInfoMsg = this.showInfoMsg.bind(this);

    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) {
        this.closeAlert();
      } else {
        window.history.go(-1);
      }
    };
  }

  componentWillMount() {
    // 到了交易页面再判断一下走势图是不是没有被移除，如果没有则移除
    // 之所以延迟了 100ms ，是因为那边移除比较慢
    setTimeout(() => {
      const kChartId = Storage.getItem('kChartId');
      console.log(kChartId);
      if (kChartId && window.plus.KlineChartPlugin) {
        console.log('removeKChart');
        window.plus.KlineChartPlugin.dismiss(kChartId);
        Storage.removeItem('kChartId');
      }
    }, 100);
    queryAccount((res) => {
      if (res.success) {
        this.tradeAccountBalance();
      }
    });
  }

  componentDidMount() {
    // const objectId = this.props.pid.replace('|', '/');
    // if (Storage.getItem('customerType') !== 'personal') {
    //   requestPublicPipParams({
    //     APPID: '1',
    //     CURRENCY_PAIR: objectId,
    //     CYCODE: objectId.split('/')[0],
    //     TRADETYPE: '0',
    //   }, (res) => {
    //     this.setState({
    //       pip: res.defaultPip,
    //       maxPip: res.maxPip,
    //     });
    //   });
    //   // preparePublicParams();
    // }
  }

  // getStaticParams(objectId) {
  //   let staticParams = {
  //     maxPip: 100,
  //     defaultPip: 10,
  //   };
  //   if (Storage.getItem('customerType') === 'personal') {
  //     const params = Storage.getItem('STATIC_PARAMS', true);
  //     staticParams = params.productParams[objectId];
  //     console.error(staticParams);
  //   }
  //   return staticParams;
  // }

  getCurrency() {
    let cur;
    if (this.state.direct === 'buy') {
      if (this.state.currency === this.state.code1) {
        cur = this.state.code2;
      } else {
        cur = this.state.code1;
      }
    } else {
      cur = this.state.currency;
    }
    return cur;
  }
  handleDirect(buyDirect) {
    this.setState({
      direct: buyDirect,
    }, this.caculateCharge);
  }
  handleCurrency(codeCurrency) {
    this.setState({
      currency: codeCurrency,
      account: '',
    }, this.caculateCharge);
  }
  handleAccount(val) {
    this.setState({
      account: val,
    });
  }
  caculateCharge() {
    const param = this.state;
    const curPriceObj = this.props.priceObject[param.objectId];
    let result;
    if (param.currency === param.code1) {
      if (param.direct === 'buy') { // 买第一货币
        result = -param.account * curPriceObj.ASK_RATE;
        this.referenceRate = curPriceObj.ASK_RATE;
      } else { // 卖第一货币
        result = param.account * curPriceObj.OFFER_RATE;
        this.referenceRate = curPriceObj.OFFER_RATE;
      }
    } else if (param.direct === 'buy') { // 买第二货币
      result = -param.account / curPriceObj.OFFER_RATE;
      this.referenceRate = curPriceObj.OFFER_RATE;
    } else { // 卖第二货币
      result = param.account / curPriceObj.ASK_RATE;
      this.referenceRate = curPriceObj.ASK_RATE;
    }
    this.setState({
      budgetAccount: result,
    });
    this.tradeAccountBalance();
  }
  handleSlider(name, value) {
    commonTool.gtjaBurialPoint('138003');
    this.setState({
      pip: value,
    });
  }
  closeAlert() {
    this.alertInstance.close();
    this.alertInstance = {};
  }
  alertTradeMsg(obj) {
    return (
      <div className="confirm-content border-item">
        <div><label>流水号</label><span>{obj.SERIAL_NO}</span></div>
        <div><label>货币对</label><span>{obj.CURRENCY_PAIR}</span></div>
        <div><label>交易金额</label><span>{obj.TRADE_AMT}{obj.TRADE_CCY}</span></div>
        <div>
          <label>对手金额</label><span>{obj.RELATE_AMT}{this.state.currency === this.state.code1 ? this.state.code2 : this.state.code1}</span>
        </div>
        <div><label>成交汇率</label><span>{obj.TRADE_RATE}</span></div>
        {obj.PREF_POINT ? <div><label>优惠点数</label><span>{obj.PREF_POINT}</span></div> : ''}
        {obj.BIG_QUEYR_FLAG && obj.BIG_QUEYR_FLAG === '0' && <div className="big-data-info">该交易归类为大额交易,需后台人员进行审核</div>}
      </div>
    );
  }
  doFirmTrade(event) {
    commonTool.gtjaBurialPoint('138004');
    event.preventDefault();
    if (this.props.priceObject[this.state.objectId].PRICE_STATUS === 'N') {
      Toast.info('您选择的产品不在交易状态!', 1);
      return false;
    }
    if (this.state.account === '0' || this.state.account === '') {
      Toast.info('交易金额不能为空！', 1);
      return false;
    }
    if (this.state.tradeAccountBalance === QUERY_FAILD) {
      Toast.info('查询可用余额失败，无法发起交易！', 1);
      return false;
    }
    const preAmount = (this.state.currency === this.state.code1 ? this.state.code2 : this.state.code1);
    if (preAmount === this.getCurrency()) {
      if (Math.abs(this.state.budgetAccount * 1) > this.state.tradeAccountBalance * 1) {
        Toast.info('您的可用余额不足，无法发起交易！', 1);
        return false;
      }
    } else if (this.state.account * 1 > this.state.tradeAccountBalance * 1) {
      Toast.info('您的可用余额不足，无法发起交易！', 1);
      return false;
    }

    // 打开交易加载框
    Toast.loading('交易中...', 0);
    const param = {
      CURRENCY_PAIR: this.state.objectId,
      BUY_OR_SELL: this.state.direct === 'buy' ? 'B' : 'S',
      TRADE_CCY: this.state.currency,
      TRADE_AMT: this.state.account * 1,
      TOLERATE_POINT: this.state.pip,
      REFERENCE_RATE: this.referenceRate,
      TRADE_TYPE: Storage.getItem('customerType') === 'personal' ? 'FIRM_FOREX' : '1',
      ENQUIRY_FLAG: '1',
      CUSTOMER_ID: Storage.getItem('customerId'),
      TRADE_ACCOUNT: Storage.getItem('tradeAccount'),
      CHANNEL: ActionConfig[Storage.getItem('customerType')][0].channel,
      VALUE_DATE: this.props.priceObject[this.state.objectId].VALUE_DATE * 1,
      BOOKING_ID: skipConfig.bookingId,
    };
    const url = ActionConfig[Storage.getItem('customerType')][0].doFxTrade;
    Ajax(url, param).then((res) => {
      Toast.hide();// 成功关闭交易加载框
      if (res.success) {
        this.alertInstance = Modal.alert(
          <div><span>{res.data.result.BIG_QUEYR_FLAG === '0' ? '大额交易' : '交易成功'}</span><Icon
            onClick={this.closeAlert}
            type="cross"
            color="#309fea"
            size="lg"
          />
          </div>,
          this.alertTradeMsg(res.data.result),
          [
            {
              text: '返回行情',
              onPress: () => {
                console.log('cancel');
                commonTool.gtjaBurialPoint('138005');
                window.history.go(-1);
              },
            },
            {
              text: '我的交易记录',
              onPress: () => {
                console.log('ok');
                commonTool.gtjaBurialPoint('138006');
                const path = {
                  pathname: '/QueryTradeList',
                };
                this.props.history.push(path);
              },
            }],
        );
        queryAccount();
      } else {
        this.setState({
          errorFlag: true,
          errorMsg: commonTool.transformErrMsg(res.message),
        });
      }
    }, (err) => {
      Toast.hide();// 失败关闭交易加载框
      console.error(err);
    });
  }
  tradeAccountBalance() {
    const tradeAccountList = Storage.getItem('tradeAccountList', true) || [];
    let currencyAccount = {
      AVAIL_AMT: QUERY_FAILD,
    };
    tradeAccountList && tradeAccountList.map((i, index) => {
      if (i.CURRENCY === this.getCurrency()) {
        currencyAccount = i;
      }
    });
    this.setState({
      tradeAccountBalance: currencyAccount.AVAIL_AMT,
    });
  }
  showInfoMsg() {
    this.setState({
      showInfoMsgFlag: true,
    });
  }
  handleAddOrIncre() {
    let info = '';
    if (this.state.budgetAccount < 0) {
      info = '减少';
    } else if (this.state.budgetAccount > 0) {
      info = '增加';
    } else if (this.state.direct === 'buy') {
      info = '减少';
    } else {
      info = '增加';
    }
    return info;
  }
  render() {
    const {
      objectId,
      currency,
      code1,
      code2,
      maxPip,
      // defaultPip,
    } = this.state;
    const currentProduct = [this.props.priceObject[objectId]];
    const notTradeCurrency = currency === code1 ? code2 : code1;
    const fixedDec = notTradeCurrency === 'JPY' ? 0 : '';
    const budgetAccount = commonTool.formatFloatAmount(Math.abs(Number(this.state.budgetAccount)), fixedDec, true);
    return (
      <div id="FirmTradeIndex">
        <div className="app_menu trade-header">
          <label onClick={() => {
            history.back();
          }}
          >取消
          </label>
          市价交易
        </div>
        <PriceList posts={currentProduct} />
        <form className="firm-content">
          <div className="item">
            <label>买卖方向</label>
            <span
              className={this.state.direct === 'buy' ? 'active-span left-item' : 'left-item'}
              onClick={this.handleDirect.bind(this, 'buy')}
            >买入
            </span>
            <span
              className={this.state.direct === 'sell' ? 'active-span' : ''}
              onClick={this.handleDirect.bind(this, 'sell')}
            >卖出
            </span>
          </div>
          <div className="item">
            <label>交易币种</label>
            <span
              className={this.state.currency === this.state.code1 ? 'active-span left-item' : 'left-item'}
              onClick={this.handleCurrency.bind(this, this.state.code1)}
            >{this.state.code1}
            </span>
            <span
              className={this.state.currency === this.state.code2 ? 'active-span' : ''}
              onClick={this.handleCurrency.bind(this, this.state.code2)}
            >{this.state.code2}
            </span>
          </div>
          <div className="item width100">
            <label className="widthAuto">交易金额</label>
            <label
              className="widthAuto"
            >{this.state.currency === this.state.code1 ? `(${this.state.code1})` : `(${this.state.code2})`}
            </label>
            <H5NumberInput
              currency={this.state.currency}
              value={this.state.account}
              itemObj={this.props.priceObject[objectId]}
              getInputValue={this.handleAccount.bind(this)}
              onBlur={this.caculateCharge.bind(this)}
              placeHolder={`可用 ${commonTool.formatFloatAmount(this.state.tradeAccountBalance * 1)} ${this.getCurrency()}`}
            />
          </div>
          <div className="item">
            <label>交付日</label>
            <select disabled>
              <option value="">{commonTool.formatDate(currentProduct[0].VALUE_DATE)}</option>
            </select>
          </div>
          <label className="account-budget-content">
            预计
            <span
              className="reCurrency"
            >{this.state.currency === this.state.code1 ? this.state.code2 : this.state.code1}
            </span>余额{this.handleAddOrIncre()}
            <span
              className="account-budget"
            >{budgetAccount}
            </span>
          </label>
        </form>
        <div className="slider-content">
          <div className="slider-title">
            <label>最大价格容忍点差
              <img className="questionMark" alt="" src={questionMask} onClick={this.showInfoMsg} />
              <ModalDiaLog
                visible={this.state.showInfoMsgFlag}
                onClose={() => {
                  this.setState({
                    showInfoMsgFlag: false,
                  });
                }}
                errMsg="如果客户提交订单的价格与最新报价之间的价格差异超过最大价格容忍点差，则交易不予成交。如果价格差异小于最大价格容忍点差，交易以最新报价成交。"
              />
            </label>
            <label>{this.state.pip}</label>
          </div>
          <Slider
            style={{ marginLeft: 10, marginRight: 10 }}
            // defaultValue={defaultPip}
            defaultValue={2}
            min={0}
            max={maxPip}
            handleStyle={{
              width: '15px',
              height: '15px',
              marginTop: '-7px',
              boxShadow: '0 2px 3px 0 rgba(126,200,248,0.99)',
            }}
            onChange={this.handleSlider.bind(this, 'change')}
            onAfterChange={this.handleSlider.bind(this, 'afterChange')}
          />
          <div className="mark-content">
            <span>0</span>
            <span>{maxPip}</span>
          </div>
        </div>
        <Button
          type="primary"
          inline
          activeClassName="default-btn-active"
          className="default tradeBtn"
          onClick={this.doFirmTrade}
        >确定
        </Button>
        <ModalDiaLog
          visible={this.state.errorFlag}
          onClose={() => {
            this.setState({ errorFlag: false });
          }}
          errMsg={this.state.errorMsg}
        />
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  console.log(state);
  console.log(ownProps);
  const { firmQuotation } = state;
  const selectedInstrument = 'firm';
  const { pid } = ownProps.match.params;
  const {
    items: quotation,
    priceObject,
  } = firmQuotation[selectedInstrument] || {
    items: [],
    priceObject: {},
  };
  return {
    selectedInstrument,
    quotation,
    priceObject,
    pid,
  };
};

export default withRouter(connect(mapStateToProps)(FirmTradeIndex));
