import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Button,
  Form,
  Select,
  Input,
  Radio,
  message,
  Cascader,
  Drawer
} from 'antd';
import './less/report.less';
// import Drawer from 'react-motion-drawer';
import PCascader from '../../../components/Pro/PCascader';
import {
  publicCommonDictGetDictByCodeTypes,
  getDistrictData,
  savePerShareholder,
  comStockGetShareholderById
} from '../../../services/api';
import PSelect from '../../../components/Pro/PSelect';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
let addZiShareolderIdLocal = '';

@connect(state => ({ profile: state.profile }))
@Form.create()
export default class AddZiShareloder extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      loading: false,
      addZiShareolderId: 0,
      initUpd: 0,
      nationality: [],
      nation: [],
      selectedIdCardType: '',
      selectedNationality: 'CHN',
      initAdd: 0,
      shareholderInfo: {
        name: '', //姓名
        phone: '', //手机
        nationality: '', //国籍
        nation: '', //名族
        sex: '', //性别
        houseReg: '', //户籍
        idCardType: '', //证件类型
        cerNo: '', //证件号码
        address: '', //具体地址
        areas: [] //省市区
      },
      // comId:1, //默认企业为1
      areas: [] //省市区
    };
  }

  componentWillReceiveProps(props) {
    if (props.visiable) {
      this.setState({ addZiShareolderId: props.addZiShareolderId }, () => {
        if (
          this.state.addZiShareolderId !== 0 &&
          this.state.addZiShareolderId !== undefined
        ) {
          if (addZiShareolderIdLocal !== props.idx) {
            //编辑时，输入任何数据都会重复的执行，用此方法保证不会重复执行
            comStockGetShareholderById({
              id: this.state.addZiShareolderId
            }).then(data => {
              data.data.areas = [
                data.data.province,
                data.data.city,
                data.data.area
              ];
              this.setState({
                shareholderInfo: {
                  name: data.data.name, //姓名
                  phone: data.data.phone, //手机
                  nationality: data.data.nationality, //国籍
                  nation: data.data.nation, //名族
                  sex: data.data.sex, //性别
                  houseReg: data.data.houseReg, //户籍
                  idCardType: data.data.idCardType, //证件类型
                  cerNo: data.data.cerNo, //证件号码
                  address: data.data.address, //具体地址
                  areas: data.data.areas //省市区
                }
              });
              this.props.form.setFieldsValue(this.state.shareholderInfo);
            });
            addZiShareolderIdLocal = props.idx;
          }
        } else {
          //进入自然人新增
          if (this.state.initAdd === 0) {
            this.props.form.setFieldsValue({
              name: '', //姓名
              phone: '', //手机
              nationality: '', //国籍
              nation: '', //名族
              sex: '', //性别
              houseReg: '', //户籍
              idCardType: '', //证件类型
              cerNo: '', //证件号码
              areas: [],
              address: '' //具体地址
            });
            this.setState({ initAdd: 1 });
          }
        }
      });
    }
  }

  componentDidMount() {
    // this.getDistrict();
    this.getDict();
  }

  getDict = () => {
    //字典下拉
    publicCommonDictGetDictByCodeTypes({
      codeTypes: 'nationality,nation'
    }).then(data => {
      if (data.data) {
        this.setState({
          nationality: data.data.nationality, //国籍
          nation: data.data.nation
        });
      }
    });
  };

  //省市区
  // getDistrict = () => {
  //   getDistrictData().then(data => {
  //     let areas = data.data.map(val => {
  //       return {
  //         value: val.regionId,
  //         label: val.regionName,
  //         children: val.childs.map(valChild => {
  //           return {
  //             value: valChild.regionId,
  //             label: valChild.regionName,
  //             children: valChild.childs.map(valChildChild => {
  //               return {
  //                 value: valChildChild.regionId,
  //                 label: valChildChild.regionName
  //               };
  //             })
  //           };
  //         })
  //       };
  //     });
  //     this.setState({
  //       areas: areas
  //     });
  //   });
  // };

  handleSubmitShareolder = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values.province = values.areas[0];
        values.city = values.areas[1];
        values.area = values.areas[2];
        // values.comId = this.state.comId;
        if (this.state.addZiShareolderId !== 0) {
          values.shareholderId = this.state.addZiShareolderId;
        }
        this.setState({ loading: true });
        savePerShareholder({ ...values })
          .then(data => {
            // message.success('提交成功！');
            this.props.forceUpdate();
            this.setState({
              loading: false
            });
            if (this.state.addZiShareolderId === 0) {
              this.setState({ initAdd: 0 });
            }
            this.props.onChange(false);
          })
          .catch(() => {
            this.setState({ loading: false });
          });
        delete values.areas;
      } else {
        message.error('提交失败！');
        this.setState({ loading: false });
      }
    });
  };

  //验证手机号码
  checkPhone = (rule, value, callback) => {
    if (value && !/^1[0-9]{10}$/.test(value)) {
      callback('请输入正确的手机号码！');
    } else {
      callback();
    }
  };

  //证件类型-号码验证-身份证
  checkIdCardNo = (rule, value, callback) => {
    // const form = this.props.form;
    // const idType = form.getFieldValue('idCardType');
    if (value && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
      callback('请输入正确的身份证号码！');
    } else {
      callback();
    }
  };

  //证件类型-号码验证-其他
  checkCardNo = (rule, value, callback) => {
    if (value && !/^[A-Za-z0-9]{1,20}$/.test(value)) {
      callback('请输入最大20位长度的证件号码！');
    } else {
      callback();
    }
  };

  //验证名称类，限制不能全角输入
  checkFullWidth = (rule, value, callback) => {
    if (value && !/[^\uFF00-\uFFFF]/g.test(value)) {
      callback('请输入正确的名称！');
    } else {
      callback();
    }
  };

  //身份证改变事件
  idCardTypeOnChangeHandler = value => {
    // this.props.form.validateFields(['cerNo']);
    this.props.form.setFieldsValue({ cerNo: '' });
    this.setState({ selectedIdCardType: value });
  };

  //国籍改变事件
  nationalityOnChangeHandler = value => {
    this.props.form.setFieldsValue({ nation: '' });
    this.setState({ shareholderInfo: { nationality: value } });
    // this.setState({});
  };

  renderNation = () => {
    return this.state.nation.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  renderNationality = () => {
    return this.state.nationality.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

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

    let mark = '新增';
    if (
      this.state.addZiShareolderId !== 0 &&
      this.state.addZiShareolderId !== undefined
    ) {
      mark = '修改';
    }

    const { getFieldDecorator } = this.props.form;

    return (
      <Drawer
        title={mark + '自然人股东'}
        placement="right"
        visible={this.props.visiable}
        width={600}
        onClose={() => {
          this.props.onChange(false);
        }}
      >
        <div>
          <Form onSubmit={this.handleSubmitShareolder}>
            <FormItem {...formItemLayout} label="姓名">
              {getFieldDecorator('name', {
                initialValue: this.state.shareholderInfo.name,
                rules: [
                  {
                    required: true,
                    message: '请输入姓名'
                  },
                  {
                    pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/,
                    message: '请输入中英文最大长度20'
                  }
                ]
              })(<Input placeholder="请输入" maxLength={20} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="手机号">
              {getFieldDecorator('phone', {
                initialValue: this.state.shareholderInfo.phone,
                rules: [
                  {
                    required: true,
                    message: '请输入手机号'
                  },
                  {
                    validator: this.checkPhone
                  }
                ]
              })(<Input placeholder="请输入" maxLength={11} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="国籍" hasFeedback>
              {getFieldDecorator('nationality', {
                initialValue: this.state.shareholderInfo.nationality,
                rules: [{ required: true, message: '请选择国籍!' }]
              })(
                <Select
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  style={{ width: '100%' }}
                  onChange={this.nationalityOnChangeHandler}
                  placeholder="请选择"
                >
                  {this.renderNationality()}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="民族" hasFeedback>
              {getFieldDecorator('nation', {
                initialValue: this.state.shareholderInfo.nation,
                rules:[{
                  required:this.state.shareholderInfo.nationality !== 'CHN' &&
                  this.state.shareholderInfo.nationality !== 'TWN' &&
                  this.state.shareholderInfo.nationality !== 'HKG' &&
                  this.state.shareholderInfo.nationality !== 'MAC'?false:true,
                  message:"请选择民族"
                }]
              })(
                <Select
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  style={{ width: '100%' }}
                  disabled={
                    this.state.shareholderInfo.nationality !== 'CHN' &&
                    this.state.shareholderInfo.nationality !== 'TWN' &&
                    this.state.shareholderInfo.nationality !== 'HKG' &&
                    this.state.shareholderInfo.nationality !== 'MAC'
                  }
                  placeholder="请选择"
                >
                  {this.renderNation()}
                </Select>
                // <PSelect type="nation"  style={{width: '100%'}}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="性别">
              {getFieldDecorator('sex', {
                initialValue: this.state.shareholderInfo.sex,
                rules: [
                  {
                    required: true,
                    message: '请选择性别'
                  }
                ]
              })(
                <RadioGroup>
                  <Radio value="1">男</Radio>
                  <Radio value="2">女</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="户籍" hasFeedback>
              {getFieldDecorator('houseReg', {
                initialValue: this.state.shareholderInfo.houseReg,
                rules: [
                  {
                    required: true,
                    message: '请选择户籍'
                  },
                  {
                    pattern: /^[\u4e00-\u9fa5]{1,20}$/,
                    message: '请输汉字最大20位!'
                  }
                ]
              })(<Input placeholder="请输入" maxLength={50} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="证件类型" hasFeedback>
              {getFieldDecorator('idCardType', {
                initialValue: this.state.shareholderInfo.idCardType,
                rules: [
                  {
                    required: true,
                    message: '请选择证件类型'
                  }
                ]
              })(
                <PSelect
                  type="idCardType_bak"
                  onChange={this.idCardTypeOnChangeHandler}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="证件号码">
              {this.state.selectedIdCardType === '1'
                ? getFieldDecorator('cerNo', {
                    initialValue: this.state.shareholderInfo.cerNo,
                    rules: [
                      {
                        required: true,
                        message: '请输入证件号码！'
                      },
                      {
                        validator: this.checkIdCardNo
                      }
                    ]
                  })(<Input placeholder="请填写证件号码" maxLength={20} />)
                : getFieldDecorator('cerNo', {
                    initialValue: this.state.shareholderInfo.cerNo,
                    rules: [
                      {
                        required: true,
                        message: '请输入证件号码！'
                      },
                      {
                        validator: this.checkCardNo
                      }
                    ]
                  })(<Input placeholder="请填写证件号码" maxLength={20} />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="住址"
              // hasFeedback
            >
              {getFieldDecorator('areas', {
                // initialValue: [this.state.shareholderInfo.province,this.state.shareholderInfo.city,this.state.shareholderInfo.area],
                initialValue: this.state.shareholderInfo.areas,
                rules: [{ required: true, message: '请选择住址!' }]
              })(
              // <Cascader options={this.state.areas} placeholder="请选择" />
              <PCascader placeholder="请选择"/>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label=" "
              colon={false}
              className="wed-none"
            >
              {getFieldDecorator('address', {
                initialValue: this.state.shareholderInfo.address,
                rules: [
                  {
                    required: true,
                    message: '请填写自然人股东详细住址'
                  },
                  {
                    // pattern: /^[\u4E00-\u9FA5A-Za-z0-9_-]{1,100}$/,
                    pattern: /.{1,100}$/,
                    message: '最大长度100'
                  }
                ]
              })(
                <TextArea
                  rows={8}
                  placeholder="请填写自然人股东详细住址"
                  maxLength={100}
                />
              )}
            </FormItem>
          </Form>
          <div
            style={{
              position: 'absolute',
              left: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right'
            }}
          >
            <Button
              onClick={() => {
                if (this.state.addZiShareolderId === 0) {
                  this.setState({ initAdd: 0 });
                }
                this.props.onChange(false);
              }}
              style={{ marginRight: 8 }}
            >
              取消
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              onClick={this.handleSubmitShareolder}
              loading={this.state.loading}
            >
              保存
            </Button>
          </div>
        </div>
      </Drawer>
    );
  }
}
