import React, { Component } from 'react';
import { connect } from 'dva';
import style from 'styled-components';
import {
  Form,
  Input,
  Select,
  Button,
  Radio,
  DatePicker,
  Cascader,
  Modal,
  message,
  Drawer
} from 'antd';
// import Drawer from 'react-motion-drawer';
import * as ajax from '../../../services/api';
import './less/report.less';
import PCascader from '../../../components/Pro/PCascader';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
const confirm = Modal.confirm;

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class ManagementAdd extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open: this.props.visible,
      loading: false,
      // comId:1,
      comManagerId: props.comManagerId, //传过来的方案id
      nationList: [],
      idCardType: '',
      idCardList: [],
      educationList: [],
      skillList: [],
      // areas: [], //地区
      listPage: {
        idCardType: '',
        idCardNo: '',
        name: '',
        sex: '',
        nation: '',
        residentProvince: '',
        residentCity: '',
        residentArea: '',
        residenceAddress: '',
        telephone: '',
        education: '',
        positionName: '',
        domicileProvince: '',
        domicileCity: '',
        domicileArea: '',
        domicileAddress: '',
        jobSkillLevel: ''
      },
      fan: false
    };
  }
  componentWillReceiveProps(props) {
    console.log(props);
    if (this.state.open !== props.visible) {
      this.setState(
        { open: props.visible, comManagerId: props.comManagerId },
        () => {
          console.log(this.state.open, this.state.comManagerId);
        }
      );
      this.addManagementList(props.comManagerId);
      // this.getDistrict();
      this.getDictionaryData(); //获取所有所需要字典数据
    }
  }

  componentDidMount() {
    // this.addManagementList();
    // this.nationListCon();//民族
    // this.getDistrict();
    // this.getIdCard();
    // this.getEducation();
    // this.getSkill();
  }

  //获取所有所需要字典数据
  getDictionaryData = () => {
    ajax
      .publicCommonDictGetDictByCodeTypes({
        codeTypes: ['nation', 'idCardType_bak', 'education', 'skillLevel']
      })
      .then(data => {
        //判断获取数据是否为空
        if (data.data) {
          this.setState({
            nationList: data.data.nation,
            idCardList: data.data.idCardType_bak,
            educationList: data.data.education,
            skillList: data.data.skillLevel
          });
        }
      });
  };

  addManagementList = comManagerId => {
    // if (this.state.comManagerId !== '00') {
    //   ajax.comStockGetManageById({ comManagerId: this.state.comManagerId }).then((data) => {
    //     if (data.data) {
    //       this.setState({
    //         listPage: data.data,
    //       });
    //     }
    //   });
    // }
    if (comManagerId !== '00') {
      ajax.comStockGetManageById({ comManagerId }).then(data => {
        if (data.data) {
          this.setState({
            listPage: data.data
          });
        }
      });
    }
  };

  //省市区
  // getDistrict = () => {
  //   ajax.getDistrictData().then(data => {
  //     console.log('省市区data:', 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
  //               };
  //             })
  //           };
  //         })
  //       };
  //     });
  //     //console.log('areas:'+JSON.stringify(areas));
  //     this.setState({
  //       areas: areas
  //     });
  //   });
  // };

  submitHandlerDeep = (that, values) => {
    that.setState({ loading: true });
    ajax.submitComStockSaveComManage({ ...values }).then(
      data => {
        // message.success('管理人员信息保存成功！');
        that.setState({ loading: false });
        that.setState({
          fan: true
        });
        that.props.close();
      },
      err => {
        console.log(err);
        that.setState({ loading: false });
      }
    );
    that.props.close();
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('values', values);
        values.residentProvince = values.hu[0];
        values.residentCity = values.hu[1];
        values.residentArea = values.hu[2];
        values.domicileProvince = values.ed[0];
        values.domicileCity = values.ed[1];
        values.domicileArea = values.ed[2];
        delete values.hu;
        delete values.ed;
        // values.comId = this.state.comId;
        if (this.state.comManagerId !== '00') {
          values.comManagerId = this.state.comManagerId;
        }

        let idCardTypeName = '';
        this.state.idCardList.map(val => {
          if (val.codeValue === values.idCardType) {
            idCardTypeName = val.label;
          }
          return 1;
        });
        const that = this;
        if (this.state.comManagerId !== '00') {
          that.submitHandlerDeep(that, values);
        } else {
          //确认提示
          confirm({
            title:
              '[' +
              idCardTypeName +
              ']：[' +
              values.idCardNo +
              ']，提交后证件类型及证件号不可修改。是否确认提交。',
            okText: '确认',
            cancelText: '取消',
            onOk() {
              that.submitHandlerDeep(that, values);
            },
            onCancel() {
              console.log('Cancel');
            }
          });
        }
      }
    });
  };

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

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

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

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

  fan = () => {
    let _that = this;
    if (_that.state.fan) {
      // _that.props.history.push(`/enterprise/reported`);
      _that.props.close();
    } else {
      confirm({
        title: '当前信息未保存，是否确认返回？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          // _that.props.history.push(`/enterprise/reported`);
          _that.props.close();
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  //验证手机号码
  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');
    // console.log('证件类型select发生变化的值:' + idType);
    if (value && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
      callback('请输入正确的身份证号码！');
    } else {
      callback();
    }
  };
  //证件类型-普通号码验证
  checkId = (rule, value, callback) => {
    if (value && !/^[a-zA-Z0-9]{1,20}$/.test(value)) {
      callback('请输入正确的证件号码！');
    } else {
      callback();
    }
  };

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

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    const config = {
      rules: [{ type: 'object', required: true, message: '请选择日期!' }]
    };

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

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 }
      }
    };

    return (
      <Drawer
        overlayColor='rgba(0, 0, 0,0)'
        placement='right'
        visible={this.state.open}
        title='管理员信息'
        width={600}
        zIndex={11}
        destroyOnClose
        // className="drawer-box"
        onChange={open => {
          this.props.onChange(open);
          this.setState({ open });
        }}
        onClose={() => {
          this.setState({
            open: false
          });
        }}
      >
        {/* <Container> */}
        <div>
          {/* <header className="body-header" style={{"paddingLeft":'20px',"paddingTop":'14px'}}>管理员信息</header> */}

          <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
            <FormItem {...formItemLayout} label='姓名'>
              {getFieldDecorator('name', {
                initialValue: this.state.listPage.name,
                rules: [
                  {
                    required: true,
                    message: '请输入姓名'
                  },
                  {
                    pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/,
                    message: '请输入8位中文或英文的姓名'
                  }
                ]
              })(<Input placeholder='请输入' maxLength={8} />)}
            </FormItem>
            <FormItem {...formItemLayout} label='部门'>
              {getFieldDecorator('departName', {
                initialValue: this.state.listPage.departName,
                rules: [
                  {
                    required: true,
                    message: '请输入部门'
                  },
                ]
              })(<Input placeholder='请输入' maxLength={20} />)}
            </FormItem>
            <FormItem {...formItemLayout} label='职务'>
              {getFieldDecorator('positionName', {
                initialValue: this.state.listPage.positionName,
                rules: [
                  {
                    required: true,
                    message: '请输入职务'
                  }
                ]
              })(<Input placeholder='请输入' />)}
            </FormItem>
            <FormItem {...formItemLayout} label='性别'>
              {getFieldDecorator('sex', {
                initialValue: this.state.listPage.sex,
                rules: [
                  {
                    required: true,
                    message: '请选择性别'
                  }
                ]
              })(
                <RadioGroup>
                  <Radio value='1'>男</Radio>
                  <Radio value='2'>女</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label='是否是退伍军人'>
              {getFieldDecorator('isVeteran', {
                initialValue: this.state.listPage.isVeteran,
                rules: [{ required: true, message: '请选是否是退伍军人' }]
              })(
                <RadioGroup>
                  <Radio value='0'>否</Radio>
                  <Radio value='1'>是</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label='民族'>
              {getFieldDecorator('nation', {
                initialValue: this.state.listPage.nation,
                rules: [{ required: true, message: '请选择民族' }]
              })(
                <Select placeholder='请选择'>
                  {/* <Option value="">请选择</Option> */}
                  {this.renderNationList()}
                </Select>
              )}
            </FormItem>
            {this.state.comManagerId === '00' ? (
              <FormItem {...formItemLayout} label='户籍'>
                {getFieldDecorator('hu', {
                  rules: [{ required: true, message: '请选择户籍' }]
                })(
                  // <Cascader options={this.state.areas} placeholder='请选择' />
                  <PCascader placeholder="请选择"/>
                )}
              </FormItem>
            ) : (
              <FormItem {...formItemLayout} label='户籍'>
                {getFieldDecorator('hu', {
                  initialValue: [
                    this.state.listPage.residentProvince,
                    this.state.listPage.residentCity,
                    this.state.listPage.residentArea
                  ],
                  rules: [{ required: true, message: '请选择户籍' }]
                })(
                  // <Cascader options={this.state.areas} placeholder='请选择' />
                  <PCascader placeholder="请选择"/>
                )}
              </FormItem>
            )}
            <FormItem {...formItemLayout} label='证件类型'>
              {getFieldDecorator('idCardType', {
                initialValue: this.state.listPage.idCardType,
                rules: [{ required: true, message: '请选择证件类型' }]
              })(
                <Select
                  disabled={this.state.comManagerId !== '00'}
                  placeholder='请选择'
                  onChange={this.idCardTypeOnChangeHandler}
                >
                  {this.idCardList()}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label='证件号'>
              {this.state.idCardType === '1'
                ? getFieldDecorator('idCardNo', {
                    initialValue: this.state.listPage.idCardNo,
                    rules: [
                      {
                        required: true,
                        message: '请输入证件号'
                      },
                      {
                        validator: this.checkIdCardNo
                      }
                    ]
                  })(
                    <Input
                      disabled={this.state.comManagerId !== '00'}
                      placeholder='请输入'
                      maxLength={18}
                    />
                  )
                : getFieldDecorator('idCardNo', {
                    initialValue: this.state.listPage.idCardNo,
                    rules: [
                      {
                        required: true,
                        message: '请输入证件号'
                      },
                      {
                        validator: this.checkId
                      }
                    ]
                  })(
                    <Input
                      disabled={this.state.comManagerId !== '00'}
                      placeholder='请输入'
                      maxLength={20}
                    />
                  )}
            </FormItem>
            <FormItem {...formItemLayout} label='联系方式'>
              {getFieldDecorator('telephone', {
                initialValue: this.state.listPage.telephone,
                rules: [
                  {
                    required: true,
                    message: '请输入联系方式'
                  },
                  {
                    validator: this.checkPhone
                  }
                ]
              })(<Input placeholder='请输入' maxLength={20} />)}
            </FormItem>
            <FormItem {...formItemLayout} label='学历'>
              {getFieldDecorator('education', {
                initialValue: this.state.listPage.education,
                rules: [{ required: true, message: '请选择学历' }]
              })(
                <Select placeholder='请选择'>
                  {/* <Option value="0">请选择</Option> */}
                  {this.renderEducation()}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label='职业技能等级'>
              {getFieldDecorator('jobSkillLevel', {
                initialValue: this.state.listPage.jobSkillLevel,
                rules: [
                  {
                    required: true,
                    message: '请选择职业技能等级'
                  }
                ]
              })(
                <Select placeholder='请选择'>
                  {/* <Option value="0">请选择</Option> */}
                  {this.skillList()}
                </Select>
              )}
            </FormItem>
            {this.state.comManagerId === '00' ? (
              <FormItem {...formItemLayout} label='居住地址'>
                {getFieldDecorator('ed', {
                  rules: [{ required: true, message: '请选择居住地址' }]
                })(
                  // <Cascader options={this.state.areas} placeholder='请选择' />
                  <PCascader placeholder="请选择"/>
                )}
              </FormItem>
            ) : (
              <FormItem {...formItemLayout} label='居住地址'>
                {getFieldDecorator('ed', {
                  initialValue: [
                    this.state.listPage.domicileProvince,
                    this.state.listPage.domicileCity,
                    this.state.listPage.domicileArea
                  ],
                  rules: [{ required: true, message: '请选择居住地址' }]
                })(
                  // <Cascader options={this.state.areas} placeholder='请选择' />
                  <PCascader placeholder="请选择"/>
                )}
              </FormItem>
            )}
            <FormItem
              {...formItemLayout}
              label=' '
              colon={false}
              className='detailedAddress'
            >
              {getFieldDecorator('domicileAddress', {
                initialValue: this.state.listPage.domicileAddress,
                rules: [
                  {
                    required: true,
                    message: '居住具体地址不能为空'
                  }
                ]
              })(<TextArea row={2} placeholder='请输入' maxLength={50} />)}
            </FormItem>
            {/* <FormItem {...submitFormLayout} style={{ marginTop: 32 }}> */}
          </Form>
          <div
            style={{
              position: 'absolute',
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e8e8e8',
              padding: '10px 16px',
              textAlign: 'right',
              left: 0,
              background: '#fff',
              borderRadius: '0 0 4px 4px'
            }}
          >
            <Button loading={submitting} onClick={this.fan}>
              返回
            </Button>
            <Button
              type='primary'
              style={{ marginLeft: 8 }}
              loading={this.state.loading}
              htmlType='submit'
              onClick={this.handleSubmit}
            >
              提交
            </Button>
            {/* </FormItem> */}
          </div>
        </div>
        {/* </Container> */}
      </Drawer>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
  color: #333;
  .body-header{
      font-size: 20px;
      color: #333333;
      padding-bottom:16px;
      border-bottom:1px solid #e9e9e9;
  }
}`;
