import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form,
  Input,
  Select,
  Button,
  Upload,
  Icon,
  Modal,
  Cascader,
  message
} from 'antd';
import PFromUpload from '../../../components/Pro/PFromUpload';
// 默认展示图片
// const defaultUploadImg = require('../../../assets/images/upload.png');

import {
  getCompanyVnvoiceInfo,
  getDistrictData,
  uploadUrl,
  updateCompanyInvoiceInfo
} from '../../../services/api';
import PCascader from '../../../components/Pro/PCascader';
const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class Invoice extends Component {
  state = {
    loading: false,
    telephone: '',
    bankAccount: '',
    bank: '建设银行',
    province: '',
    city: '',
    area: '',
    address: '',
    taxRegCerNo: '',
    taxPayerType: '',
    // "comId": '',
    comName: '',
    comProvice: '',
    comCity: '',
    comArea: '',
    previewVisible: false,
    previewImage: '',
    options: [],
    // authEntrustUrlList: '',
    personType: {
      tax: {
        visible: true,
        url: ''
      },
      business: {
        visible: true,
        url: ''
      },
      general: {
        visible: true,
        url: ''
      },
      bank: {
        visible: true,
        url: ''
      }
    }
  };

  componentDidMount() {
    /* (async () => {
      const data = await getDistrictData({}).catch((err) => { console.log(err); });
      console.log(data, 'async');
    })(); */

    // getDistrictData({}).then(
    //   data1 => {
    //     function generadata(data) {
    //       return data.map(val => {
    //         const obj = {};
    //         obj.label = val.regionName;
    //         obj.value = val.regionId + '';
    //         if (val.childs && val.childs.length > 0) {
    //           obj.children = generadata(val.childs);
    //         }
    //         return obj;
    //       });
    //     }
    //     const options1 = generadata(data1.data);
    //     this.setState({ options: options1 });
        this.getCompanyVnvoiceInfoSd();
    //   },
    //   err => {
    //     console.log(err, 'getDistrictData');
    //   }
    // );
  }
  getCompanyVnvoiceInfoSd = () => {
    getCompanyVnvoiceInfo({}).then(
      data => {
        const { personType } = this.state;
        if (data.data && data.data.taxPayerType === '2') {
          personType.general.visible = false;
          personType.bank.visible = false;
        }

        this.setState({ ...data.data, personType });

        personType.tax.url = data.data.taxRegCerUrl;
        personType.business.url = data.data.businessLicenseUrl;
        personType.general.url = data.data.generalTaxProveUrl;
        personType.bank.url = data.data.bankAccountLicenseUrl;

        const { comArea, comCity, comProvice,comName,comAddress,province,city,area } = data.data;

        this.setState({
          personType,
          comName,
          comProvice,
          comCity,
          comArea,
          comAddress,
          province,
          city,
          area
        });
      },
      err => {
        console.log(err, 'getCompanyVnvoiceInfo');
      }
    );
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true
    });
  };

  beforeUpload = file => {
    const types = ['image/png', 'image/jpeg', 'image/jpg'];
    if (types.indexOf(file.type) === -1) {
      message.error('只能上传图片!');
      return false;
    }
    const isLt8M = file.size / 1024 / 1024 < 8;
    if (!isLt8M) {
      message.error('图片大小大于8MB!');
      return false;
    }

    return true;
    // return isJPG && isPNG && isLt8M;
  };

  handleChange = (info, field) => {
    //除了移除状态，上传过程中，判断是否符合上传规则
    let result = true;
    if (status !== 'removed') {
      result = this.beforeUpload(info.file);
    }
    if (!result) {
      return;
    }
    const { setFieldsValue } = this.props.form;
    let { fileList } = info;
    fileList = fileList.slice(-1);
    this.setState({ [field + 'List']: fileList });

    if (info.file.status === 'removed') {
      message.error('至少需要一张图片');
      return;
    }

    if (info.file.status !== 'uploading') {
      if (info.file.response) {
        // if (info.file.response.retType === "-1") {
        if (info.file.response.retType !== '0') {
          const defaultFile = [
            {
              uid: -2,
              // name: 'xxx.png',
              status: 'done',
              url: ''
            }
          ];
          this.setState({
            [field + 'List']: defaultFile
          });
          message.error(info.file.response.msg);
          return;
        }
      } else {
        return;
      }
    }

    if (info.file.status === 'done') {
      // if (info.file.response.retType === "0") {
      message.success(`${info.file.name} 文件上传成功`);
      this.setState({
        [field + 'List']: fileList,
        [field]: fileList[0].response.data
      });
      setFieldsValue({ [field]: fileList.slice(-1) });
      // } else {
      //   setFieldsValue({ [field]: "" });
      //   message.error(`${info.file.response.msg}`);
      // }
    } else if (info.file.status === 'error') {
      // setFieldsValue({ [field]: "" });
      message.error(`${info.file.name} 文件上传失败.`);
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        /* this.props.dispatch({
          type: 'form/submitRegularForm',
          payload: values,
        }); */
        const data = { ...values, province: '' };
        [data.province, data.city, data.area] = values.provinceCityArea;
        
        if (!data.city || data.area == 'null') {
          delete data.city;
        }
        if (!data.area || data.area == 'null') {
          delete data.area;
        }
        // data.comId = this.state.comId;
        delete data.comProviceComCityComArea;
        delete data.comAddress;
        delete data.provinceCityArea;
        this.setState({ loading: true });
        updateCompanyInvoiceInfo(data).then(() => {
          this.setState({ loading: false });
        }).catch(() => {
          this.setState({ loading: false });
        });
        // message.success('提交成功！');
      }
    });
  };

  //验证电话
  checkTel = (rule, value, callback) => {
    if (value && !/^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/.test(value)) {
      callback('请输入正确的电话！');
    } else {
      callback();
    }
  };

  //验证公司银行账号,
  checkBank = (rule, value, callback) => {
    if (value && !/^[0-9]{1,50}$/.test(value)) {
      callback('请输入正确的公司银行账号，仅限数字，字符长度不大于50！');
    } else {
      callback();
    }
  };

  //验证税务登记证号码
  checkTaxRegCerNo = (rule, value, callback) => {
    if (value && !/^[A-Za-z0-9]+$/.test(value)) {
      callback('请输入正确的税务登记证号码！');
    } else {
      callback();
    }
  };

  // 根据用户选择纳税人类别，来区分显示证件扫描件的上传内容
  handlePersonType = value => {
    const { personType } = this.state;
    if (value === '2') {
      personType.general.visible = false;
      personType.bank.visible = false;

      this.setState({
        personType
      });
    } else {
      personType.general.visible = true;
      personType.bank.visible = true;

      this.setState({
        personType
      });
    }
  };

  // 显示证件扫描件的上传内容渲染函数
  uploadSortsRender = () => {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 }
      }
    };
    const { state } = this;
    const uploadSorts = [
      // {
      //   filelist: state.personType.tax.url,
      //   filed: 'taxRegCerUrl',
      //   action: uploadUrl,
      //   url: state.taxRegCerUrl,
      //   label: '税务登记证',
      //   msg: '请上传税务登记证',
      //   name: 'xfile',
      //   visible: state.personType.tax.visible
      // },
      {
        filelist: state.personType.business.url,
        filed: 'businessLicenseUrl',
        action: uploadUrl,
        url: state.businessLicenseUrl,
        label: '社会统一信用代码证',
        msg: '请上社会统一信用代码证',
        name: 'xfile',
        visible: state.personType.business.visible
      },
      {
        filelist: state.personType.general.url,
        filed: 'generalTaxProveUrl',
        action: uploadUrl,
        url: state.generalTaxProveUrl,
        label: '一般纳税人证明',
        msg: '请上传一般纳税人证明',
        name: 'xfile',
        visible: state.personType.general.visible
      },
      {
        filelist: state.personType.bank.url,
        filed: 'bankAccountLicenseUrl',
        action: uploadUrl,
        url: state.bankAccountLicenseUrl,
        label: '银行开户许可证',
        msg: '请上传银行开户许可证',
        name: 'xfile',
        visible: state.personType.bank.visible
      }
    ];

    return uploadSorts.map(val => {
      const item = val;

      return val.visible ? (
        <FormItem key={val.label} {...formItemLayout} label={val.label}>
          {getFieldDecorator(val.filed, {
            initialValue: item.filelist,
            rules: [{ required: true, message: val.msg }]
          })(<PFromUpload num={1} />)}
        </FormItem>
      ) : null;
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { previewVisible, previewImage } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 }
      }
    };

    const { state } = this;

    return (
      <div className="s_rtf s_erf">
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <div className="card">基本信息</div>
          <FormItem {...formItemLayout} label="单位名称">
            {getFieldDecorator('comName', {
              initialValue: state.comName,
              rules: []
            })(<Input disabled placeholder="请输入" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="电话">
            {getFieldDecorator('telephone', {
              initialValue: state.telephone,
              rules: [
                {
                  required: true,
                  message: '请输入电话！'
                },
                {
                  validator: this.checkTel
                }
              ]
            })(<Input placeholder="请输入" maxLength={13} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="注册地址">
            {getFieldDecorator('comProviceComCityComArea', {
              initialValue: [parseInt(state.comProvice), parseInt(state.comCity), parseInt(state.comArea)],
              rules: [{ required: true, message: '请选择国籍/地区' }]
            })(
              // <Cascader disabled options={state.options} onChange={() => {}} />
              <PCascader disabled placeholder="请选择"/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label=" "
            colon={false}
            className="detailedAddress"
          >
            {getFieldDecorator('comAddress', {
              initialValue: state.comAddress,
              rules: [
                {
                  required: true,
                  message: '请输入街道！'
                }
              ]
            })(
              <TextArea
                disabled
                rows={3}
                placeholder="请填写公司注册详细地址"
                maxLength={100}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="公司银行帐号">
            {getFieldDecorator('bankAccount', {
              initialValue: state.bankAccount,
              rules: [
                {
                  required: true,
                  message: '请输入公司银行帐号！'
                },
                {
                  validator: this.checkBank
                }
              ]
            })(<Input placeholder="请输入" maxLength={50} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="开户银行">
            {getFieldDecorator('bank', {
              initialValue: state.bank,
              rules: [
                {
                  required: true,
                  message: '请输入开户银行！'
                }
              ]
            })(<Input placeholder="请输入" maxLength={100} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="发票寄送地址">
            {getFieldDecorator('provinceCityArea', {
              initialValue: [
                state.province,
                state.city,
                state.area
              ],
              rules: [{ required: true, message: '请选择国籍/地区' }]
            })(
            // <Cascader options={this.state.options} />
            <PCascader placeholder="请选择"/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label=" "
            colon={false}
            className="detailedAddress"
          >
            {getFieldDecorator('address', {
              initialValue: state.address,
              rules: [
                {
                  required: true,
                  message: '请输入街道！'
                }
              ]
            })(<TextArea rows={3} placeholder="请输入街道" maxLength={100} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="税务登记证号/统一信用代码证号">
            {getFieldDecorator('taxRegCerNo', {
              initialValue: state.taxRegCerNo,
              rules: [
                {
                  required: true,
                  message: '请输入税务登记证号！'
                },
                {
                  validator: this.checkTaxRegCerNo
                }
              ]
            })(<Input placeholder="请输入" maxLength={20} />)}
          </FormItem>
          <div className="card">证件扫描件</div>

          <FormItem {...formItemLayout} label="增值税纳税人类别">
            {getFieldDecorator('taxPayerType', {
              initialValue: state.taxPayerType,
              rules: [{ required: true, message: '请选择增值税纳税人类别' }]
            })(
              <Select placeholder="请选择" onChange={this.handlePersonType}>
                <Option value="1">增值税一般纳税人</Option>
                <Option value="2">增值税小规模纳税人</Option>
              </Select>
            )}
          </FormItem>
          {this.uploadSortsRender()}
          {/*  <FormItem
          {...formItemLayout}
          label="税务登记证"
        >
          {getFieldDecorator('taxRegCerUrl', {
            rules: [{ required: true, message: '上传税务登记证' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.taxRegCerUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="证件扫描件副本"
        >
          {getFieldDecorator('businessLicenseUrl', {
            rules: [{ required: true, message: '请上传证件扫描件副本' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.businessLicenseUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="一般纳税人证明"
        >
          {getFieldDecorator('generalTaxProveUrl', {
            rules: [{ required: true, message: '请上传一般纳税人证明' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.generalTaxProveUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="增值税授权委托书"
        >
          {getFieldDecorator('authEntrustUrl', {
            rules: [{ required: true, message: '请上传增值税授权委托书' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.authEntrustUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="银行开户许可证"
        >
          {getFieldDecorator('bankAccountLicenseUrl', {
            rules: [{ required: true, message: '请上传银行开户许可证' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.bankAccountLicenseUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem> */}
          <FormItem {...formItemLayout} label=" " colon={false}>
            <Button
              size="large"
              type="primary"
              htmlType="submit"
              loading={this.state.loading}
            >
              提交
            </Button>
          </FormItem>
          <Modal
            visible={previewVisible}
            footer={null}
            onCancel={this.handleCancel}
            width="90%"
          >
            <img alt="example" style={{ width: '100%' }} src={previewImage} />
          </Modal>
        </Form>
      </div>
    );
  }
}
