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('鐪佸競鍖篸ata:', 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;
  }
}`;