import React, { Component } from "react";
import { Alert } from 'antd';
import { connect } from 'dva';
import {
  BhAccountSendVerifyCode,
  getComWalletAccountAmount,
  comWalletAccountExtract,
  getWalletRechargeToken,
  taskComBhAccountGetComBhAccountAmount,
  taskComBhAccountWithdrawa
} from '../../../../services/api';
import $modal from '../../../../utils/modal';
import $nModal from '../../../../utils/modal/nModal';
import { SMS_OP_WITHDRAW } from '../../../../common/shortMessage';
import { Tooltip, Icon, Button, Modal, notification, Radio, Form, Input } from 'antd';
import WalletModal from './WalletModal';
import UpdateMobileModal from './UpdateMobileModal';
import { formItemLayout1, commanFormItemLayout } from '../../../../constants/formItemLayout';
import yl from '../../../../assets/images/wallet/yl.png';
import cq from '../../../../assets/images/wallet/cq.png';

@connect(state => ({
  companyInfo: state.global.companyInfo
}))
@Form.create()
export default class StepFive extends Component {
  constructor(props, context) {
    super(props, context);
    if (this.props.companyInfo) {
      window.sessionStorage.setItem('companyInfo', JSON.stringify(this.props.companyInfo));
    }
    this.state = {
      companyInfo: this.props.companyInfo,  // 公司信息
      rechargeVisbale: false,

      rechargeTime: 0,  // 充值倒计时时间
      rechargeTimer: null,  //充值倒计时定时器
      rechargeBtnName: '获取验证码',  //充值发送验证码按钮名字
      codeValue: '', //提现短信验证码
      moneyReg: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, //金额正则
      cashOutVisbale: false, // 提现对话框
      accountInfo: {}, // 资金信息
      accountInfo: {}, //账户信息

      payUrl: '', //充值表单提交url

      time: 0, // 可发送验证码剩余时间
      btnName: '获取验证码',  // 发送验证码按钮名字
      timer: null, // 验证码定时器


      orderId: '',//提现的时候短信验证码发送后返回的orderid 在提现接口中要用到
      editModalVisble: false, // 修改对公账户模态框
      updateMobileModal:false,//修改手机号
      accountStatusValue: {
        0: '正常',
        7: '客户绑卡未激活',
        8: "平台客户开户处理中",
        9: '普通客户开户处理中',
      }
    };
  }

  componentDidMount() {
    if (window.sessionStorage.getItem('companyInfo')) {
      this.setState({
        companyInfo: JSON.parse(window.sessionStorage.getItem('companyInfo'))
      });
    }

  }
  componentDidUpdate() {
    this.__initPage();
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    let props = {
      bankInfo: nextProps.bankInfo
    };
    return props;
  }
  //提现
  _cashOutSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const POST_DATA = {
          ...values,
        };
        taskComBhAccountWithdrawa(POST_DATA).then(res => {
          $modal('提交提现成功！', '到账时间：根据人行处理转账情况决定，一般为实时到账。', [{
            text: '确定',
            type: 'primary',
            onPress: () => {
              // this.__initPage();
              taskComBhAccountGetComBhAccountAmount().then(res => {
                this.setState({ accountInfo: res.data });
              });
              this.setState({
                cashOutVisbale: false
              });
            }
          }], 'success');
        });
      }
    });
  }

  __initPage() {
    const { bankInfo } = this.props;
    if (!this.state.hasLoad) {
      if (bankInfo) {
        this.setState({
          hasLoad: true
        });
        taskComBhAccountGetComBhAccountAmount().then(res => {
          this.setState({ accountInfo: res.data });
        });
      }
    }
  }
  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { rechargeVisbale, cashOutVisbale, bankInfo } = this.state;
    return (
      <div className="wallet_container">
        <div className="wallet_header">
          <h3>您好{this.state.companyInfo.comName && `,${this.state.companyInfo.comName}！`}</h3>
        </div>
        <ul className="card_container">
          <li>
            <div className="img_box">
              <Icon type="pay-circle" style={{ fontSize: 50 }} />
              {/* <img src="" alt=""/> */}
            </div>
            <div className="card_info">
              <span>账户总额(元)</span>
              <Tooltip title="账户总额=可用余额+冻结金额">
                <Icon type="info-circle" theme="filled" />
              </Tooltip>
              {
                this.state.accountInfo.totalAmount ?
                  <p className="point">{this.state.accountInfo.totalAmount}</p> :
                  <Icon style={{ display: 'block' }} type="loading" />
              }
            </div>
            <div className="card_other">
              <Button onClick={() => {
                this.setState({
                  rechargeVisbale: true
                });
              }} type="primary">充值</Button>
            </div>
          </li>

          <li>
            <div className="img_box">
              <Icon type="pay-circle" style={{ fontSize: 50 }} />
            </div>
            <div className="card_info">
              <span>可用余额(元)</span>
              <Tooltip title="可以直接被消费使用、转账、提现的金额。">
                <Icon type="info-circle" theme="filled" />
              </Tooltip>
              {
                this.state.accountInfo.availableAmount ?
                  <p className="point">{this.state.accountInfo.availableAmount}</p> :
                  <Icon style={{ display: 'block' }} type="loading" />
              }
            </div>
            <div className="card_other">
              <Button
                onClick={() => {
                  this.setState({
                    cashOutVisbale: true
                  });
                }}
              >提现</Button>
            </div>
          </li>
          <li>
            <div className="img_box">
              <Icon type="pay-circle" style={{ fontSize: 50 }} />
            </div>
            <div className="card_info">
              <span>冻结金额(元)</span>
              <Tooltip title="因业务关系，暂时被冻结的金额，待业务关系解除后则会转入可用余额。">
                <Icon type="info-circle" theme="filled" />
              </Tooltip>
              {
                this.state.accountInfo.frozenAmount ?
                  <p className="point">{this.state.accountInfo.frozenAmount}</p> :
                  <Icon style={{ display: 'block' }} type="loading" />
              }
            </div>
          </li>
        </ul>

        <ol className="info_container">
          <li>
            <div className="left_content">
              <span>发薪账号:</span>
            </div>
            <div className="right_content">
              {this.state.bankInfo.bhVirlAcctNo ?
                <span>{this.state.bankInfo.bhVirlAcctNo}</span> :
                <Icon type="loading" />}
            </div>
          </li>

          <li>
            <div className="left_content">
              <span>账户状态:</span>
            </div>
            <div className="right_content">
              <span>{
                this.state.accountStatusValue[this.state.bankInfo.accountStatus]
              }</span>
            </div>
          </li>

          <li>
            <div className="left_content">
              <span>绑定手机号:</span>
              <div className="other_box">
                <Tooltip title="用以接收交易验证码，确保交易安全。">
                  <Icon type="info-circle" theme="filled" />
                </Tooltip>
              </div>
            </div>
            <div className="right_content">
              <span>{this.state.bankInfo.mobilePhone}</span>
              <div className="other_box">
                <a className="absolute_link" href="javascript:void(0)" onClick={() => {
                  this.setState({
                    updateMobileModal:true
                  })
                }}>修改</a>
              </div>
            </div>
          </li>

          {/* <li>
            <div className="left_content">
              <span>充值卡账户:</span>
              <div className="other_box">
                <Tooltip title="通过线下转账充值时，必须使用此账户转账，系统才可识别钱包账户，否则无法充值到账。">
                  <Icon type="info-circle" theme="filled" />
                </Tooltip>
              </div>
            </div>
            <div className="right_content">
              <span>建设银行 8888 8888 8888 8888 888</span>
              <div className="other_box">
              </div>
            </div>
          </li> */}

          <li>
            <div className="left_content">
              <span>企业基本户:</span>
              <div className="other_box">
                <Tooltip title="企业线下转账充值、提现时指定的企业对公账户。">
                  <Icon type="info-circle" theme="filled" />
                </Tooltip>
              </div>
            </div>
            <div className="right_content">
              <span>{this.state.bankInfo.bankOutlets} {this.state.bankInfo.bankCardNo}</span>
              <div className="other_box">
                <a
                  className="absolute_link"
                  href="javascript:void(0)"
                  onClick={() => {
                    this.setState({
                      editModalVisble: true
                    });
                  }}
                >
                  修改
                </a>
              </div>
            </div>
          </li>
          <li>
            <div className="left_content">
              <span>发薪权限:</span>
            </div>
            <div className="right_content">
              {
                this.state.bankInfo.isOpenSalaryAuth == '0' ? <span> 未开启 <span style={{ color: '#f9b903' }}>(请联系在线客服进行申请)</span></span> : <span>已开启</span>
              }
            </div>
          </li>
        </ol>

        {/* 修改对公账户对话框 */}
        <WalletModal
          companyInfo={this.state.companyInfo}
          visible={this.state.editModalVisble}
          bankInfo={this.state.bankInfo}
          // update={() => { this.__initPage() }}
          update={() => { this.props.updateBackInfo() }}
          onCancel={() => {
            this.setState({
              editModalVisble: false
            });
          }}
        />

        {/* 修改手机号 */}
        <UpdateMobileModal 
          companyInfo={this.state.companyInfo}
          visible={this.state.updateMobileModal}
          bankInfo={this.state.bankInfo}
          update={() => { this.props.updateBackInfo() }}
          onCancel={() => {
            this.setState({
              updateMobileModal: false
            });
          }}
        />

        {/* 充值对话框*/}
        {
          rechargeVisbale &&
          <Modal
            title="发薪账户充值"
            footer={null}
            onCancel={() => {
              this.setState({
                rechargeVisbale: false
              });
            }}
            visible={rechargeVisbale}
          >
            <Form
            //  onSubmit={this._cashOutSubmit}
            >
              <div>线下转账充值说明：</div>
              <div>请使用您的企业基本户向您企业开通的发薪账户转账，系统确认到账后会自动为您的账户充值；
                <span style={{ color: 'red' }}>使用其他银行账户转账将无法识别充值，系统会自动退款！</span>
              </div>
              <Form.Item {...commanFormItemLayout} label='您的企业基本户:'>
                {getFieldDecorator('amount', {
                  // initialValue: this.state.cashOutValue,
                  rules: [
                    {
                      required: true,
                      message: '获取付款账户失败'
                    }
                  ]
                })(
                  <div>{this.state.bankInfo.bankOutlets} {this.state.bankInfo.bankCardNo}</div>
                )}
              </Form.Item>
              <Form.Item {...commanFormItemLayout} label='转账至:'>
                {getFieldDecorator('amount', {
                  // initialValue: this.state.cashOutValue,
                  // rules: [
                  //   {
                  //     required: true,
                  //     message: '请输入充值金额'
                  //   },
                  // {
                  //   validator: (rule, value, callback) => {
                  //     if (value && !this.state.moneyReg.test(value) || parseFloat(value) == 0) {
                  //       callback('请输入正确金额，如：1000.00');
                  //     } else {
                  //       callback();
                  //     }
                  //   }
                  // }
                  // ]
                })(
                  <>
                    <div>收款银行：渤海银行北京分行</div>
                    <div>收款户名：{this.state.companyInfo.comName}</div>
                    <div>收款账户：{this.state.bankInfo.bhVirlAcctNo}</div>
                  </>)}
              </Form.Item>

            </Form>
          </Modal>
        }


        {/* 提现对话框*/}
        {
          cashOutVisbale &&
          <Modal
            title="发薪账户提现"
            footer={null}
            onCancel={() => {
              this.setState({
                cashOutVisbale: false
              });
            }}
            visible={cashOutVisbale}
          >
            <div className="wallet_modal_content">
              <p className="notice">注：钱包提现服务，由中国银联提供技术支持与资金数据处理服务，确保您的资金安全到账！</p>
              {(() => {
                const { getFieldDecorator } = this.props.form;

                return (
                  <Form onSubmit={this._cashOutSubmit}>
                    <Form.Item {...formItemLayout1} label='收款账户:'>
                      {getFieldDecorator('bankCardNo', {
                        initialValue: this.state.bankInfo.bankCardNo,
                        rules: [
                          {
                            required: true,
                            message: '获取收款账户失败'
                          }
                        ]
                      })(<Input
                        placeholder='收款账户'
                        disabled
                        maxLength={50}
                      />)}
                    </Form.Item>
                    <Form.Item {...formItemLayout1} label='提现金额:'>
                      {getFieldDecorator('amount', {
                        // initialValue: this.state.cashOutValue,
                        rules: [
                          {
                            required: true,
                            message: '请输入提现金额'
                          },
                          {
                            validator: (rule, value, callback) => {
                              if (value && !this.state.moneyReg.test(value) || parseFloat(value) == 0) {
                                callback('请输入正确金额，如：1000.00');
                              } else {
                                callback();
                              }
                            }
                          }
                        ]
                      })(<Input
                        placeholder='请输入提现金额'
                        maxLength={50}
                      />)}
                    </Form.Item>
                    <Form.Item {...formItemLayout1} label='验证手机号:'>
                      <p style={{ display: 'inline-block' }}>{this.state.bankInfo.mobilePhone}</p>
                      <Button
                        type="primary"
                        disabled={this.state.time > 0}
                        style={{ marginLeft: 15 }}
                        onClick={() => {
                          const amount = this.props.form.getFieldValue('amount');
                          if (!amount) {
                            return notification.error({
                              message: '请先输入金额'
                            });
                          }
                          let { time, timer } = this.state;
                          const { mobilePhone } = this.state.bankInfo;
                          if (time > 0) return;
                          if (timer) clearInterval(timer);
                          if (!mobilePhone || !/^\d{11}$/.test(mobilePhone)) {
                            // if (!mobilePhone || !/^1[34578]\d{9}$/.test(mobilePhone)) {
                            return notification.error({
                              message: '系统没有获取到手机号'
                            });
                          }

                          const DATA = {
                            mobilePhone,
                            transCode: 'XNTX',
                            bankCardNo: this.state.bankInfo.bankCardNo,
                            comName: this.state.companyInfo.comName,
                            amount
                          };
                          BhAccountSendVerifyCode(DATA).then(res => {
                            this.setState({
                              orderId: res.data
                            });
                            time = 60;
                            timer = setInterval(() => {
                              time -= 1;
                              if (time > 0) {
                                this.setState({
                                  time,
                                  btnName: `重试(${time})`,
                                  timer
                                });
                              } else {
                                clearInterval(timer);
                                this.setState({
                                  btnName: '获取验证码',
                                  timer: null
                                }, () => {
                                  this.setState({
                                    time: 0
                                  });
                                });
                              }
                            }, 1000);
                          })
                        }}
                      >{this.state.btnName}</Button>
                    </Form.Item>
                    <Form.Item {...formItemLayout1} label='短信验证码:'>
                      {getFieldDecorator('activeCode', {
                        // initialValue: this.state.activeCode,
                        rules: [
                          {
                            required: true,
                            message: '请输入验证码'
                          },
                          {
                            validator: (rule, value, callback) => {
                              if (value && !/\d{0,6}/.test(value)) {
                                callback('请输入正确验证码');
                              } else {
                                callback();
                              }
                            }
                          }
                        ]
                      })(<Input
                        placeholder='请输入短信验证码'
                        onChange={e => {
                          this.setState({
                            codeValue: e.target.value
                          });
                        }}
                        maxLength={50}
                      />)}
                    </Form.Item>
                  </Form>
                );
              })()}
              <div style={{ textAlign: "center" }}>
                <Button type="primary" htmlType="submit" onClick={this._cashOutSubmit}>提交提现</Button>
              </div>
            </div>
          </Modal>
        }
      </div>
    );
  }
}
