import React, { Component } from "react";
import { Alert } from 'antd';
import {
  sendVerifyCode,
  getComWalletAccountAmount,
  comWalletAccountExtract,
  getWalletRechargeToken
} from '../../../../services/api';
// import $modal from '../../modal';
import $modal from '../../../../utils/modal';
import $nModal from '../../../../utils/modal/nModal';
import { SMS_OP_WITHDRAW } from '../../../../common/shortMessage';
// import { getHostByPath } from '../../../../utils/request.js';
import { Tooltip, Icon, Button, Modal, notification, Radio, Form, Input } from 'antd';
import WalletModal from './WalletModal';
import yl from '../../../../assets/images/wallet/yl.png';
import cq from '../../../../assets/images/wallet/cq.png';
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 12 }
  }
};
@Form.create()
export default class StepFive extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      companyInfo: JSON.parse(window.sessionStorage.getItem('companyInfo')),  // 公司信息
      rechargeVisbale: false,
      rechargeValue: '',  // 充值金额的值
      rechargeShowTip: false,  //显示提示
      codeValue: '', //提现短信验证码
      rechargeRadio: '1',  // 充值选项框  0->企业网银充值 1->线下转账充值,
      rechargeBtnDisable: false,  // 充值按钮的disable控制
      rechargeBtnToken: '',  // 充值时通过接口获取的token
      moneyReg: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, //金额正则
      cashOutVisbale: false, // 提现对话框
      moneyInfo: {}, // 资金信息
      accountInfo: {}, //账户信息

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

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


      orderId: '',//提现的时候短信验证码发送后返回的orderid 在提现接口中要用到
      editModalVisble: false  // 修改对公账户模态框
    };
  }

  componentDidMount() {
    this.setState({
      companyInfo: JSON.parse(window.sessionStorage.getItem('companyInfo'))
    });
  }
  componentDidUpdate() {
    this.__initPage();
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    let props = {
      accountInfo: nextProps.accountInfo
    };
    return props;
  }
  _cashOutSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { bankCardNo, walletAccountNo, mobilePhone } = this.state.accountInfo;
        const POST_DATA = {
          ...values,
          comName: this.state.companyInfo.comName,
          bankCardNo,
          walletAccountNo,
          mobilePhone,
          orderId: this.state.orderId
        };
        comWalletAccountExtract(POST_DATA).then(res => {
          // const MSG = res.msg;
          $modal('钱包提现申请提交成功！', '根据银行转账的时效，预计一天内会提现到您的结算卡中。', [{
            text: '确定',
            type: 'primary',
            onPress: () => {
              console.log('成功');
              this.props.updateBackInfo();
            }
          }], 'success');
        });
      }
    });
  }

  __initPage() {
    // getComWalletAccount().then(res => {
    //   this.setState({
    //     accountInfo: res.data
    //   });
    const { walletAccountNo } = this.state.accountInfo;
    if (!this.state.hasLoad) {
      if (walletAccountNo) {
        this.setState({
          hasLoad: true
        });
        getComWalletAccountAmount({ walletAccountNo }).then(res => {
          this.setState({
            moneyInfo: res.data
          });
        });
      }
    }
    // });
  }
  render() {
    return (
      <div className="wallet_container">
        <div className="wallet_header">
          <h3>您好{this.state.companyInfo.comName && `,${this.state.companyInfo.comName}！`}</h3>
          <p>中国银联 <img style={{ width: 100 }} src={yl} alt="" /> 与富民银行 <img style={{ width: 100 }} src={cq} alt="" /> 联合为您提供资金监管及安全保障服务！<a style={{ fontSize: 14 }} href="/finance/agreement/wallet" target="_blank">
            《富民银行委托结算服务协议》
              </a></p>
        </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.moneyInfo.totalAmount ?
                  <p className="point">{this.state.moneyInfo.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>
              <p className="point">{this.state.moneyInfo.availableAmount}</p>
            </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>
              <p className="point">{this.state.moneyInfo.frozenAmount}</p>
            </div>
          </li>
        </ul>

        <ol className="info_container">
          <li>
            <div className="left_content">
              <span>企业ID:</span>
            </div>
            <div className="right_content">
              {this.state.accountInfo.comId ?
                <span>{this.state.accountInfo.comId}</span> :
                <Icon type="loading" />}
            </div>
          </li>

          <li>
            <div className="left_content">
              <span>钱包账户号:</span>
            </div>
            <div className="right_content">
              {this.state.accountInfo.walletAccountNo ?
                <span>{this.state.accountInfo.walletAccountNo}</span> :
                <Icon type="loading" />}
            </div>
          </li>

          <li>
            <div className="left_content">
              <span>账户状态:</span>
            </div>
            <div className="right_content">
              <span>{this.state.accountInfo.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.accountInfo.mobilePhone}</span>
              <div className="other_box">
                <a className="absolute_link" href="javascript:void(0)" onClick={() => {
                  $nModal({
                    footer: null,
                    title: '修改企业绑定手机号及企业名称',
                    content: (
                      <>
                        <Alert
                          message={<div style={{ color: '#333' }}>
                            <span>1、请下载页面中的模板，根据页面提示完成信息填写；</span> <br />
                            <span>2、表格信息填写完毕后，需加盖企业公章；</span> <br />
                            <span>3、加盖公章后，请扫描成电子档，发送给平台在线客服，平台在线客服审核后系统自动修改，审核时间预计1~3个工作日。</span> <br />
                          </div>}
                          type="warning"
                          showIcon
                          style={{ marginBottom: '15px' }}
                        />

                        <a href="/files/重庆富民银行企富通用户信息变更申请表.doc" target="_blank" download="重庆富民银行企富通用户信息变更申请表" style={{marginLeft: 20, marginTop: 20}}>
                          点击下载： 重庆富民银行企富通用户信息变更申请表.doc
                        </a>
                      </>
                    )
                  })
                }}>修改</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.accountInfo.bankName} {this.state.accountInfo.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">
              <span>{this.state.accountInfo.createTime}</span>
            </div>
          </li>
        </ol>

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

        {/* 充值对话框*/}
        <Modal
          title="钱包充值"
          wrapClassName="modal_on_footer"
          onCancel={() => {
            this.setState({
              rechargeVisbale: false
            });
          }}
          visible={this.state.rechargeVisbale}
        >
          <div className="radio_cneter">
            {/* <Radio.Group
              defaultValue="1"
              buttonStyle="solid"
              onChange={e => {
                this.setState({
                  rechargeRadio: e.target.value
                });
              }}
            >
              <Radio.Button value="0">企业网银充值</Radio.Button>
              <Radio.Button value="1">转账充值</Radio.Button>
            </Radio.Group> */}
            {/* <p style={{textAlign: "center"}}>转账充值</p> */}
          </div>

          {/* 企业网银充值 */}
          {this.state.rechargeRadio == '0' &&
            <div className="wallet_modal_content">
              <p className="notice">注：企业网银充值服务，由中国银联提供技术支持与资金数据处理服务，确保您的资金安全到账！本充值方式，次日到账，请知悉。</p>
              {(() => {
                const { getFieldDecorator } = this.props.form;
                return (
                  <Form onSubmit={this.rechargeSubmit}>
                    <Form.Item {...formItemLayout} label='充值金额:'>
                      <Input
                        style={{ border: this.state.rechargeShowTip ? '1px solid #D9001B' : '1px solid #d9d9d9' }}
                        placeholder='请输入充值金额'
                        onChange={e => {
                          const value = e.target.value;
                          this.setState({
                            rechargeValue: value,
                            rechargeShowTip: !this.state.moneyReg.test(value) || value == 0
                          });
                        }}
                        maxLength={50}
                      />
                      <div style={{
                        display: this.state.rechargeShowTip ? 'block' : 'none',
                        color: '#D9001B'
                      }}>请输入正确金额，如：1000.00</div>
                    </Form.Item>
                    <Form.Item>
                      <div className="footer_btns">
                        <Button type="primary" htmlType="submit" onClick={() => {
                          const { rechargeValue, moneyReg } = this.state;
                          if (!moneyReg.test(rechargeValue) || rechargeValue == 0) {
                            this.setState({
                              rechargeBtnDisable: true
                            });
                            return notification.error({
                              message: '请输入正确金额，如：1000.00'
                            });
                          }
                          let { walletAccountNo, comName } = this.state.accountInfo;
                          if (comName == '') {
                            comName = this.state.companyInfo.comName;
                          }
                          const callfrontUrl = window.location.origin + '/finance/business-wallet';
                          const POST_DATA = {
                            walletAccountNo,
                            comName,
                            amount: rechargeValue,
                            callfrontUrl
                          };
                          // 获取企业钱包充值token
                          getWalletRechargeToken(POST_DATA).then(res => {
                            return console.log(res, 'resresresres');
                            const { token, payUrl } = res.data;
                            console.log(payUrl, 'payUrlpayUrlpayUrl')
                            this.setState({
                              rechargeBtnDisable: false,
                              payUrl,
                              rechargeBtnToken: token
                            }, () => {
                              const rechargeForm = document.getElementById('rechargeForm');
                              //  提交表单到充值页面
                              rechargeForm.submit();
                            });
                          }).catch(err => {
                            this.setState({
                              rechargeBtnDisable: false
                            });
                            console.log(err);
                          });
                        }}>提交充值</Button>
                      </div>
                    </Form.Item>
                  </Form>
                );
              })()}

            </div>
          }

          {/* 线下转账充值 */}
          {
            this.state.rechargeRadio == '1' &&
            <div className="wallet_modal_content">
              <p className="notice">转账充值说明：
                <span>请使用绑定的企业对公账户向富民银行安保人资服务专用户转账，系统确认到账后会自动为您的账户充值；</span>
                <span className="red_tip">使用其他银行账户转账将无法识别充值！</span>
              </p>
              <div className="bank_card_info">
                <p>企业对公账户：</p>
                <div style={{ paddingLeft: 20 }}>
                  <p className="bank_card">
                    <span className="card_num">{this.state.accountInfo.bankCardNo}</span>   {this.state.accountInfo.bankName}
                  </p>
                </div>
              </div>
              <div className="bank_card_info">
                <p>转账至：</p>
                <div style={{ paddingLeft: 20 }}>
                  <p className="bank_card">
                    <span className="card_num">收款银行：</span>   重庆富民银行
                  </p>
                  <p className="bank_card">
                    <span className="card_num">收款户名：</span>   富民银行安保人资服务专用户
                  </p>
                  <p className="bank_card">
                    <span className="card_num">收款账户：</span>   6800 0010 1931 0967 121
                  </p>
                  <p className="notice">注：部分银行系统，收款银行选择不到"重庆富民银行"的，请选择"民营银行"，并填写"重庆富民银行"。</p>
                </div>
              </div>
            </div>
          }
        </Modal>


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

              return (
                <Form onSubmit={this._cashOutSubmit}>
                  <Form.Item {...formItemLayout} label='提现金额:'>
                    {getFieldDecorator('amount', {
                      value: 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 {...formItemLayout} label='企业对公账户:'>
                    <span>{this.state.accountInfo.bankCardNo}</span>
                  </Form.Item>
                  <Form.Item {...formItemLayout} label='验证手机号:'>
                    <p style={{ display: 'inline-block' }}>{this.state.accountInfo.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.accountInfo;
                        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,
                          smsType: SMS_OP_WITHDRAW,
                          amount
                        };
                        sendVerifyCode(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 {...formItemLayout} label='短信验证码:'>
                    {getFieldDecorator('activeCode', {
                      value: 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 className="footer_btns">
              <Button type="primary" htmlType="submit" onClick={this._cashOutSubmit}>提交提现</Button>
            </div>
          </div>
        </Modal>

        {/* <form id="rechargeForm" action="http://localhost:8080/pay/pay/fbank/account/b2b/recharge" method="post"> */}
        <form id="rechargeForm"
          action={`${this.state.payUrl}`}
          method="post"
        >
          <input type="hidden" name="token" value={this.state.rechargeBtnToken} />
        </form>
      </div>
    );
  }
}
