import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import HeaderComponent from './HeaderComponent';
import {
  publicCommonDictGetDictByCodeTypes,
  getConfigBankList,
  sendVerifyCode,
  saveCccountInfo
} from '../../../services/api';
import PFromUpload from '../../../components/Pro/PFromUpload';
import { formItemLayout, formLayout } from '../../../constants/formItemLayout';
import PSelect from '../../../components/Pro/PSelect';
import { SMS_COM_REGISTER } from '../../../common/shortMessage';
import { Form, Select, Input, Button, Row, Col, notification, DatePicker } from 'antd';
import AddForm from './addForm';
import $modal from '../../../utils/modal';
const { Option } = Select;
// @connect(state => ({
//   global: state.global
// }))
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
@Form.create()
export default class BusinessWallet extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // companyInfo: this.props.global.companyInfo,  // 公司信息
      companyInfo: JSON.parse(window.sessionStorage.getItem('companyInfo')),  // 公司信息
      comCerType: [], //企业证件类型
      bankList: [],  //绑定充值、结算卡银行列表
      submitStatus: false, // 验证码发送成功以后才能提交

      selectedBanks: [],  //选中的银行
      // selectedBanks: ["ICBC-工商银行"],  //选中的银行

      time: 0, // 可发送验证码剩余时间
      btnName: '获取验证码',  // 发送验证码按钮名字
      timer: null, // 验证码定时器
      mobilePhone: '' //绑定验证手机号
    };
  }
  componentDidMount() {
    // 获取企业证件类型
    this.publicCommonDictGetDictByCodeTypes();
    // 绑定充值、结算卡银行列表
    this.__getConfigBankList();
  }
  //类型查询
  publicCommonDictGetDictByCodeTypes = () => {
    const codeTypes = "comCerType";
    publicCommonDictGetDictByCodeTypes({ codeTypes }).then(({ data = {} }) => {
      this.setState({ comCerType: data.comCerType });
    }, (err) => {
      console.log(err);
    });
  }
  __getConfigBankList() {
    getConfigBankList().then(res => {
      /**
       * 0: {bankCode: "CQFMB", bankName: "重庆富民银行"}
          bankCode: "CQFMB"
          bankName: "重庆富民银行"
          1: {bankCode: "ICBC", bankName: "工商银行"}
          bankCode: "ICBC"
          bankName: "工商银行"
          2: {bankCode: "ICBC", bankName: "中国工商银行澳门分行"}
          bankCode: "ICBC"
          bankName: "中国工商银行澳门分行"
       */
      const keyArr = [];  //过滤bankCode相同的选项后的值（只取第一个）
      res.data.forEach(bank => {
        const nowArr = JSON.parse(JSON.stringify(keyArr));
        if (!nowArr.find(item => item.bankCode == bank.bankCode)) { //数组里面没有
          keyArr.push(bank);
        }
      });
      this.setState({
        bankList: keyArr
      });
    });
  }
  handleSubmit = e => {
    e.preventDefault();
    this.setState({
      submitStatus: true
    });
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // 校验股东信息和受益人信息
        this._validateTable((error, tableValues) => {
          if (error) {
            const errorKeys = Object.keys(error);
            const key = errorKeys[0];
            const type = key.replace(/(.+\-)(\d+)(\-.+)/, '$3').slice(1);
            const index = key.replace(/(.+\-)(\d+)(\-.+)/, '$2');
            // const keyInfoArr = key.split('-');
            // const type = keyInfoArr[2];
            // const index = keyInfoArr[1];
            let title = '';
            if (type === 's') {
              title = '股东信息';
            } else if (type === 'b') {
              title = '受益人信息';
            }
            this.setState({
              submitStatus: false
            });
            $modal(
              `${title},第${parseInt(index) + 1}行`,
              error[key].errors[0].message
            );
          } else {
            // 校验成功 进行提交
            const bankCode = values.bankCode[0].split('-')[0];
            values.bankCode = bankCode;

            // 身份证有效期
            // idCardDate 
            values.idCardStartDate = moment(values.idCardDate[0]).format(dateFormat);
            values.idCardEndDate = moment(values.idCardDate[1]).format(dateFormat);
            Reflect.deleteProperty(values, 'idCardDate');
            
            // 表格数据
            values.shareholderInfo = JSON.stringify(tableValues.shareholders);
            values.beneficiaryInfo = JSON.stringify(tableValues.beneficiarys);

            // 隐藏参数
            // values.legalRepPhone = this.state.companyInfo.legalRepPhone;

            saveCccountInfo(values).then(res => {
              this.setState({
                submitStatus: false
              });
              this.props.setStatus(5);
              this.setState({
                submitStatus: false
              });
              // this.props.dispatch({
              //   type: "financial/_setStepInfo",
              //   payload: values
              // });
              // window.sessionStorage.setItem('stepInfo',JSON.stringify(values));  
            }).catch(err => {
              this.setState({
                submitStatus: false
              });
            });
          }
        });
      } else {
        this.setState({
          submitStatus: false
        });
      }
    });
  };
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <HeaderComponent breadcrumb={['企业钱包', '开通钱包']} step={0}></HeaderComponent>

        <div className="form_container">
          <p className="header">填写开户资料</p>
          <Form onSubmit={this.handleSubmit} style={{ paddingRight: 15 }}>
            <Row gutter={16}>
              <Col span={20}>
                <Form.Item {...formLayout} label='企业名称:'>
                  {getFieldDecorator('comName', {
                    initialValue: this.state.companyInfo && this.state.companyInfo.comName,
                    rules: [
                      {
                        required: true,
                        message: '请输入企业名称'
                      },
                      {
                        validator: (rule, value, callback) => {
                          if (value && !/^\S{0,50}$/.test(value)) {
                            callback('请输入正确的企业名称！');
                          } else {
                            callback();
                          }
                        }
                      }
                    ]
                  })(<Input placeholder='请选择' disabled maxLength={50} />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={10}>
                <Form.Item {...formItemLayout} label="企业证件类型:" hasFeedback>
                  {getFieldDecorator('comCerType', {
                    initialValue: this.state.companyInfo && this.state.companyInfo.comCerType,
                    rules: [{ required: true, message: '请选择企业证件类型!' }],
                  })(
                    <Select>
                      {(() => {
                        const { comCerType } = this.state;
                        return comCerType.map(
                          (val, key) => (
                            <Option
                              value={val.codeValue}
                              key={key}>
                              {val.label}
                            </Option>
                          ));
                      })()}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={10}>
                <Form.Item {...formItemLayout} label='企业证件号码:'>
                  {getFieldDecorator('comCerNo', {
                    initialValue: this.state.companyInfo && this.state.companyInfo.comCerNo,
                    rules: [
                      {
                        required: true,
                        message: '请输入企业证件号码'
                      },
                      {
                        validator: (rule, value, callback) => {
                          if (value && !/^\S{0,50}$/.test(value)) {
                            callback('请输入正确的企业证件号码！');
                          } else {
                            callback();
                          }
                        }
                      }
                    ]
                  })(<Input placeholder='请输入' maxLength={50} />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={10}>
                <Form.Item {...formItemLayout} label="企业类型:" hasFeedback>
                  {getFieldDecorator('fmComType', {
                  // {getFieldDecorator('comType', {
                    // initialValue: this.state.companyInfo && this.state.companyInfo.comType,
                    rules: [{ required: true, message: '请选择企业类型!' }],
                  })(
                    <PSelect
                      style={{ minWidth: 120 }}
                      type="fmComType"
                      placeholder="请选择企业类型"
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={10}>
                <Form.Item {...formItemLayout} label='企业联系电话:'>
                  {getFieldDecorator('contractPhone', {
                    initialValue: this.state.companyInfo && this.state.companyInfo.telePhone,
                    rules: [
                      {
                        required: true,
                        message: '请输入绑定验证手机号'
                      },
                      {
                        validator: (rule, value, callback) => {
                          // if (value && !/^1[34578]\d{9}$/.test(value)) {
                          if (value && !/^1[0-9]{10}$/.test(value)) {
                            callback('请输入正确绑定验证手机号！');
                          } else {
                            callback();
                          }
                        }
                      }
                    ]
                  })(<Input
                    placeholder='请输入'
                    maxLength={50}
                  />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={20}>
                <Form.Item {...formLayout} label='企业经营地址:'>
                  {getFieldDecorator('businessAddress', {
                    value: this.state.businessAddress,
                    rules: [
                      {
                        required: true,
                        message: '请输入企业经营地址'
                      },

                    ]
                  })(<Input
                    placeholder='请输入'
                    maxLength={50}
                  />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={10}>
                <Form.Item {...formItemLayout} label='法人姓名:'>
                  {getFieldDecorator('legalRepName', {
                    initialValue: this.state.companyInfo && this.state.companyInfo.legalRepName,
                    rules: [
                      {
                        required: true,
                        message: '请输入法人姓名'
                      },
                      {
                        validator: (rule, value, callback) => {
                          if (value && !/^\S{0,50}$/.test(value)) {
                            callback('请输入正确的法人姓名！');
                          } else {
                            callback();
                          }
                        }
                      }
                    ]
                  })(<Input placeholder='请输入' maxLength={50} />)}
                </Form.Item>
              </Col>
              <Col span={10}>
                <Form.Item {...formItemLayout} label='法人身份证号:'>
                  {getFieldDecorator('idCardNo', {
                    initialValue: this.state.companyInfo && this.state.companyInfo.idCardNo,
                    rules: [
                      {
                        required: true,
                        message: '请输入法人身份证号'
                      },
                      {
                        validator: (rule, value, callback) => {
                          if (value && !/^\S{0,20}$/.test(value)) {
                            callback('请输入正确的法人身份证号！');
                          } else {
                            callback();
                          }
                        }
                      }
                    ]
                  })(<Input placeholder='请输入' maxLength={50} />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={20}>
                <Form.Item {...formLayout} label='法人常住地:'>
                  {getFieldDecorator('legalRepPlace', {
                    value: '',
                    rules: [
                      {
                        required: true,
                        message: '请输入法人常住地'
                      },

                    ]
                  })(<Input
                    placeholder='请输入'
                    maxLength={50}
                  />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={20}>
                <Form.Item {...formLayout} label='法人户籍地:'>
                  {getFieldDecorator('legalResPlace', {
                    value: '',
                    // rules: [
                    //   {
                    //     required: true,
                    //     message: '请输入法人户籍地'
                    //   },

                    // ]
                  })(<Input
                    placeholder='请输入'
                    maxLength={50}
                  />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={10}>
                <Form.Item {...formItemLayout} label='法人手机号:'>
                  {getFieldDecorator('legalRepPhone', {
                    initialValue: this.state.companyInfo && this.state.companyInfo.legalRepPhone,
                    rules: [
                      {
                        required: true,
                        message: '请输入法人手机号'
                      },
                      {
                        validator: (rule, value, callback) => {
                          // if (value && !/^1[34578]\d{9}$/.test(value)) {
                          if (value && !/^1[0-9]{10}$/.test(value)) {
                            callback('请输入正确绑定验证手机号！');
                          } else {
                            callback();
                          }
                        }
                      }
                    ]
                  })(<Input
                    placeholder='请输入'
                    maxLength={20}
                  />)}
                </Form.Item>
              </Col>
              <Col span={10}>
                <Form.Item {...formItemLayout} label="法人职业类型:">
                  {getFieldDecorator('legalJobCode', {
                    // rules: [{ required: true, message: '请选择职业类型!' }],
                  })(
                    <PSelect
                      style={{ minWidth: 120 }}
                      type="legalJobCode"
                      placeholder="请选择职业类型"
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={10}>
                <Form.Item  {...formItemLayout} label="身份证有效期">
                  {getFieldDecorator('idCardDate', {
                    initialValue: [],
                    rules: [{ required: true, message: '请选择身份证有效期！' }]
                  })(
                    <RangePicker
                      format={dateFormat}
                      disabledDate={current => {
                        return current > moment('2100/1/1');
                      }}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={10}>
                <div style={{ lineHeight: '38px', color: '#FFAA00' }}>
                  若为永久证件，到期日期请选择2099-12-31
                </div></Col>
            </Row> 
            <Row gutter={16}>
              <Col span={10}>
                <Form.Item {...formItemLayout} label="绑定对公账户银行:" hasFeedback>
                  {getFieldDecorator('bankCode', {
                    initialValue: this.state.selectedBanks,
                    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({
                            'bankCode': value
                          }, () => {
                            console.log(this.props.form.getFieldValue('bankCode'), "bankCode")
                          });
                        });

                        // this.setState({
                        //   selectedBanks: value
                        // });
                      }}
                    >
                      {this.state.bankList.map((item, index) => (
                        <Option
                          // 名字也拼接在value里面，搜索的时候可以过滤
                          value={`${item.bankCode}-${item.bankName}`}
                          key={index}>
                          {item.bankName}
                        </Option>
                      ))
                      }
                    </Select>,
                  )}
                  {/* <div className="form_tip">
                    <span>结算卡：企业钱包余额充值、提现等结算专用账户。</span>
                  </div> */}
                </Form.Item>
              </Col>
              <Col span={10}>
                <Form.Item {...formItemLayout} label='绑定对公账户卡号:'>
                  {getFieldDecorator('bankCardNo', {
                    // initialValue: this.state.companyInformationData.comName,
                    rules: [
                      {
                        required: true,
                        message: '请输入绑定对公账户卡号'
                      },
                      {
                        validator: (rule, value, callback) => {
                          if (value && !/^\d{0,40}$/.test(value)) {
                            callback('请输入正确绑定对公账户卡号！');
                          } else {
                            callback();
                          }
                        }
                      }
                    ]
                  })(<Input placeholder='请输入' maxLength={50} />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={20}>
                <Form.Item {...formLayout} label=' ' colon={false}>
                  <div style={{ lineHeight: '18px', color: '#FFAA00', marginBottom: '-20px' }}>
                    绑定对公账户：企业转账充值、提现时指定的银行账户，请绑定企业的对公账户，非员工个人银行账户。
                  </div>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={10}>
                <Form.Item {...formItemLayout} label='绑定验证手机号:'>
                  <Row >
                    <Col span={17}>
                      {getFieldDecorator('mobilePhone', {
                        value: this.state.mobilePhone,
                        rules: [
                          {
                            required: true,
                            message: '请输入绑定验证手机号'
                          },
                          {
                            validator: (rule, value, callback) => {
                              // if (value && !/^1[34578]\d{9}$/.test(value)) {
                              if (value && !/\d{11}$/.test(value)) {
                                callback('请输入正确绑定验证手机号！');
                              } else {
                                callback();
                              }
                            }
                          }
                        ]
                      })(<Input
                        onChange={e => {
                          this.setState({
                            mobilePhone: e.target.value
                          });
                        }}
                        placeholder='请输入'
                        maxLength={50}
                      />)}
                    </Col>
                    <Col span={6} offset={1}>
                      <Button type="primary"
                        disabled={this.state.time > 0}
                        onClick={() => {
                          let { time, timer, mobilePhone } = this.state;
                          if (time > 0) return;
                          if (timer) clearInterval(timer);
                          if (!mobilePhone || !/^1[34578]\d{9}$/.test(mobilePhone)) {
                            return notification.error({
                              message: '请输入正确手机号！'
                            });
                          }

                          const DATA = {
                            mobilePhone,
                            smsType: SMS_COM_REGISTER
                          }
                          sendVerifyCode(DATA).then(res => {
                            this.setState({
                              submitStatus: false
                            });
                            time = 60;
                            timer = setInterval(() => {
                              time -= 1;
                              if (time > 0) {
                                this.setState({
                                  time,
                                  btnName: `重试(${time})`,
                                  timer
                                });
                              } else {
                                console.log(time + '-2');
                                clearInterval(timer);
                                this.setState({
                                  btnName: '获取验证码',
                                  timer: null
                                }, () => {
                                  this.setState({
                                    time: 0
                                  });
                                });
                              }
                            }, 1000);
                          })
                        }}
                      >{this.state.btnName}</Button>
                      {/* <div className="form_tip">
                        <span>验证手机号：用以企业钱包进行转账（薪资代发）、提现等资金变动时验证码接收。</span>
                      </div> */}
                    </Col>
                  </Row>
                </Form.Item>
              </Col>
              <Col span={10}>
                <Form.Item {...formItemLayout} label='短信验证码:'>
                  {getFieldDecorator('activeCode', {
                    // initialValue: this.state.companyInformationData.comName,
                    rules: [
                      {
                        required: true,
                        message: '请输入短信验证码'
                      },
                      {
                        validator: (rule, value, callback) => {
                          if (value && !/^\d{0,6}$/.test(value)) {
                            callback('请输入正确短信验证码！');
                          } else {
                            callback();
                          }
                        }
                      }
                    ]
                  })(<Input placeholder='请输入' maxLength={6} />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={20}>
                <Form.Item {...formLayout} label=' ' colon={false}>
                  <div style={{ lineHeight: '18px', color: '#FFAA00', marginBottom: '-20px' }}>
                    验证手机号：用以企业钱包进行转账（薪资代发）、提现等资金变动时验证码接收，建议绑定财务负责人手机号。
                  </div>
                </Form.Item>
              </Col>
            </Row>
            <p className="header">填写股东、受益人资料</p>
            <AddForm getAddFun={(fun) => {
              this._validateTable = fun;
            }} />
            <p className="header">上传证件资料</p>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  {...formItemLayout}
                  label="企业证件扫描件"
                // help="每张不超过:8M,格式为:jpg，jpeg，png"
                >
                  {getFieldDecorator('comCerUrl', {
                    initialValue: this.state.companyInfo && this.state.companyInfo.comCerUrl,
                    rules: [
                      {
                        required: true,
                        message: '请上传证件扫描件'
                      }
                    ]
                  })(
                    <PFromUpload
                      num={1}
                      size={1.5}
                      types={['image/jpeg', 'image/jpg', 'image/png', 'image/bmp']}
                    />
                  )}
                  <p>每张不超过:1.5M,支持扩展名jpg,jpeg,png,bmp</p>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  {...formItemLayout}
                  label="法人身份证人像面"
                // help="每张不超过:8M,格式为:jpg，jpeg，png"
                >
                  {getFieldDecorator('idCardFrontUrl', {
                    // initialValue: this.state.certificationData.comCerUrl,
                    rules: [
                      {
                        required: true,
                        message: '请上传法人身份证人像面'
                      }
                    ]
                  })(
                    <PFromUpload
                      num={1}
                      size={1.5}
                      types={['image/jpeg', 'image/jpg', 'image/png', 'image/bmp']}
                    />
                  )}
                  <p>每张不超过:1.5M,支持扩展名jpg,jpeg,png,bmp</p>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  {...formItemLayout}
                  label="法人身份证国徽面"
                // help="每张不超过:8M,格式为:jpg，jpeg，png"
                >
                  {getFieldDecorator('idCardReverseUrl', {
                    // initialValue: this.state.certificationData.comCerUrl,
                    rules: [
                      {
                        required: true,
                        message: '请上传法人身份证国徽面'
                      }
                    ]
                  })(
                    <PFromUpload
                      num={1}
                      size={1.5}
                      types={['image/jpeg', 'image/jpg', 'image/png', 'image/bmp']}
                    />
                  )}
                  <p>每张不超过:1.5M,支持扩展名jpg,jpeg,png,bmp</p>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item {...formItemLayout} label=" " colon={false}>
              <Button type="primary"
                disabled={this.state.submitStatus}
                htmlType="submit">确定并下一步</Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}
