import React, { Component } from "react";
import { Modal, Form, Input, Button, Alert, Select, notification, Row, Col } from 'antd';
import PFromUpload from '../../../../components/Pro/PFromUpload';
import { getConfigBankList, systemPlatNewsSendVerificationCode, systemPlatNewsVerificationCode, saveBankCardChangeEvent } from '../../../../services/api'
const { Option } = Select;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 12 }
  }
};
@Form.create()
export default class WalletModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time: 0, // 可发送验证码剩余时间
      btnName: '获取验证码',  // 发送验证码按钮名字
      timer: null, // 验证码定时器
      bankList: [],  //银行列表
      key:0
    }
  }
  componentDidMount() {
    this.__getConfigBankList();
  }
  __getConfigBankList() {
    getConfigBankList().then(res => {
      const keyArr = [];  //过滤dictValue相同的选项后的值（只取第一个）
      res.data.bankCode.forEach(bank => {
        const nowArr = JSON.parse(JSON.stringify(keyArr));
        if (!nowArr.find(item => item.codeValue == bank.codeValue)) { //数组里面没有
          keyArr.push(bank);
        }
      });
      this.setState({
        bankList: keyArr
      });
    });
  }
  _formSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      // if(err) return;
      const { activeCode, bank, bankCardNo, bankCardUrl, changeProveUrl } = values;
      const { mobile } = this.props;
      const bankCode = bank[0].split('-')[0];
      const bankName = bank[0].split('-')[1];
      // 检查验证码是否正确
      systemPlatNewsVerificationCode({ mobile, code: activeCode }).then(res => {
        // 保存钱包银行卡信息变更
        saveBankCardChangeEvent({
          changeProveUrl,
          bankCardUrl,
          bankCode,
          bankName,
          bankCardNo
        }).then(result => {
          this.props.form.resetFields();
          this.props.onCancel();
          this.props.update();
          this.setState({
            key: Math.random(),
          })
        });
      });
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Modal
          width={600}
          title="修改企业对公账户"
          visible={this.props.visible}
          onOk={this._formSubmit}
          onCancel={()=>{
            this.props.form.resetFields();
            this.setState({
              key: Math.random(),
            })
            this.props.onCancel();
          }}
          className="wallet_modal"
        >
          <Alert
            message={
              <div>
                <span className="notice">
                  1、企业对公账户提交修改后，需等平台客服进行审核，预计1~3个工作日完成；
                </span>
                <br />
                <span className="notice">
                  2、审核通过，页面数据直接变更。审核期间，绑定卡仍以旧卡信息为准；
                </span>
                <br />
                <span className="red_tip">
                  3、审核期间，若非紧急情况，请勿转账充值，以免到款入账时，绑定卡信息已变更，造成无法入账。
                </span>
              </div>
            }
            type="warning"
            showIcon
          />
          <Form style={{ marginTop: 20 }}>
            <Row>
              <Col span={12}>
                <Form.Item

                  label="企业钱包信息修改证明:"
                // help="每张不超过:8M,格式为:jpg，jpeg，png"
                >
                  {getFieldDecorator('changeProveUrl', {
                    initialValue: '',
                    rules: [
                      {
                        required: true,
                        message: '请上传扫描件'
                      }
                    ]
                  })(
                    <PFromUpload
                      num={1}
                      size={2*1024}
                      disabled={this.state.statusBianDisabled}
                      key={this.state.key}
                    />
                  )}
                  <a href="https://bcxin-saas-prod.obs.cn-north-1.myhuaweicloud.com/saasweb/front/qbxxxgzmmb.docx">《企业钱包信息修改证明》模板下载</a>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="旧绑定卡开户许可证:"
                // help="每张不超过:8M,格式为:jpg，jpeg，png"
                >
                  {getFieldDecorator('bankCardUrl', {
                    initialValue: '',
                    rules: [
                      {
                        required: true,
                        message: '请上传扫描件'
                      }
                    ]
                  })(
                    <PFromUpload
                      num={1}
                      size={2*1024}
                      disabled={this.state.statusBianDisabled}
                      key={this.state.key}
                    />
                  )}
                  <span>每张不超过:2M,格式为:jpg，jpeg，png</span>
                </Form.Item>
              </Col>
            </Row>

            <Form.Item {...formItemLayout} label="新绑定卡银行:" hasFeedback>
              {getFieldDecorator('bank', {
                rules: [{ required: true, message: '请选择新绑定卡银行！' }]
              })(
                <Select
                  // value={this.state.selectedBanks}
                  mode="multiple"
                  placeholder="请选择"
                  suffixIcon={false}
                  onChange={selectedBanks => {
                    // 只能选取一个值 要将之前的值删除
                    let value = [];
                    if (selectedBanks.length > 0) {
                      // 选最后一个
                      const selectedItem = selectedBanks[selectedBanks.length - 1];
                      value.push(selectedItem);
                    } else {
                      value = selectedBanks;
                    }
                    setTimeout(() => {
                      this.props.form.setFieldsValue({
                        'bank': value
                      });
                    });
                  }}
                >
                  {this.state.bankList.map((item, index) => (
                    <Option
                      // 名字也拼接在value里面，搜索的时候可以过滤
                      value={`${item.codeValue}-${item.label}`}
                      key={index}>
                      {item.label}
                    </Option>
                  ))
                  }
                </Select>,
              )}
              {/* <div className="form_tip">
                <span>结算卡：企业钱包余额充值、提现等结算专用账户。</span>
              </div> */}
            </Form.Item>
            <Form.Item {...formItemLayout} label='新绑定卡卡号:'>
              {getFieldDecorator('bankCardNo', {
                value: this.state.activeCode,
                rules: [
                  {
                    required: true,
                    message: '请输入新绑定卡卡号'
                  },
                  {
                    validator: (rule, value, callback) => {
                      if (value && !/^\d{0,40}$/.test(value)) {
                        callback('请输入正确卡号！');
                      } else {
                        callback();
                      }
                    }
                  }
                ]
              })(<Input
                placeholder='请输入新绑定卡卡号'
                maxLength={50}
              />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label='验证手机号:'>
              <p style={{ display: 'inline-block' }}>{this.props.mobile}</p>
              <Button
                type="primary"
                disabled={this.state.time > 0}
                style={{ marginLeft: 15 }}
                onClick={() => {
                  let { time, timer } = this.state;
                  const { mobile } = this.props;
                  if (time > 0) return;
                  if (timer) clearInterval(timer);
                  if (!mobile || !/^\d{11}$/.test(mobile)) {
                    // if (!mobilePhone || !/^1[34578]\d{9}$/.test(mobilePhone)) {
                    return notification.error({
                      message: '系统没有获取到手机号'
                    });
                  }
                  // 发送验证码
                  systemPlatNewsSendVerificationCode({ mobile }).then(res => {
                    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>
        </Modal>
      </div>
    );
  }
}

