import React, { Component } from 'react';
import {
  Form,
  Input,
  Radio,
  DatePicker,
  Cascader,
  Select,
  Button,
  message,
  InputNumber
} from 'antd';
import { connect } from 'dva';
import * as ajax from '../../../services/api';
import './less/personnel.less';
import moment from 'moment';
import PCascader from '../../../components/Pro/PCascader';

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

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class DetailedInformationPage extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      confirmDirty: false,
      perId: '',
      // perTypeList: [], //人员类别
      nationList: [], //国籍下拉选择值
      educationList: [], //学历
      bloodList: [], //血型
      nationMoreList: [], //民族下拉选择
      politicalList: [], //政治面貌
      maritalList: [], //婚姻
      residentList:[],//户籍类型
      areas: [], //省市区
      basicInFormaationData: {
        idCardType: '',
        idCardNo: '',
        name: '',
        isIncumbency: '',
        sex: '',
        nation: '',
        birthday: '',
        firstWorkDay: '',
        // perType: '',
        nationality: '',
        originPlace: '',
        education: '',
        mobilePhone: '',
        email: '',
        height: '',
        bloodType: '',
        politicalStatus: '',
        maritalStatus: '',
        residentProvince: '',
        residentCity: '',
        residentArea: '',
        residenceAddress: '',
        domicileProvince: '',
        domicileCity: '',
        domicileArea: '',
        domicileAddress: '',
        contactper: '',
        contactPhone: '',
        perSource: '',
        remark: '',
        drivingLicenseLevel: ''
      },
      specialInformationData: [], //特殊字段
      drivingList: [], //驾照选择
      text: [],
      perIndFieldId: ''
    };
  }

  componentDidMount() {
    this.setState({
      perId: this.props.perId
    });
    ajax
      .systemPerBaseInfoGetPerBaseInfo({ perId: this.props.perId })
      .then(data => {
        if (data.data) {
          this.setState(
            {
              basicInFormaationData: data.data
            }
          );
        }
      });
    ajax
      .systemConfigPerIndustryFindListByComId({ perId: this.props.perId })
      .then(data => {
        if (data.data.length >= 1) {
          this.setState(
            {
              specialInformationData: []
            },
            () => {
              this.setState({
                specialInformationData: data.data,
                perIndFieldId: data.data[0].perIndFieldId || ''
              });
            }
          );
        }
      });
    this.renderAllDictInformation();
    // this.renderNation();
    // this.renderEducation();
    // this.renderBlood();
    // this.renderNationMore();
    // this.renderPolitical();
    // this.renderMarital();
    // this.getDistrict();
    // this.renderDriving();
    // this.renderPerType();
  }

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.birthday = values['birthday'].format('YYYY-MM-DD');
        if (values.height === '') {
          values.height = 0;
        }
        // if (values.domicile[0] !== '' && values.domicile.length > 1) {
        //   values.domicileProvince = values.domicile[0].toString();
        //   values.domicileCity = values.domicile[1].toString();
        //   values.domicileArea = values.domicile[2].toString();
        // } else {
        //   values.domicileProvince = null;
        //   values.domicileCity = null;
        //   values.domicileArea = null;
        // }
        if(values.domicile[0]===''){
          return message.warning("请输入居住地址")
        }else{
          values.domicileProvince = values.domicile[0].toString();
          values.domicileCity = values.domicile[1].toString();
          values.domicileArea = values.domicile[2].toString();
        }
        delete values.domicile;
        // if (values.resident.length > 1 && values.resident[0] !== '') {
        //   values.residentProvince = values.resident[0];
        //   values.residentCity = values.resident[1];
        //   values.residentArea = values.resident[2];
        // } else {
        //   values.residentProvince = null;
        //   values.residentCity = null;
        //   values.residentArea = null;
        // }
        if(values.resident[0]===''){
          return message.warning("请输入身份证住址")
        }else{
          values.residentProvince = values.resident[0];
          values.residentCity = values.resident[1];
          values.residentArea = values.resident[2];
        }
        delete values.resident;
        values.perIndustryInfoList = [];
        if (values.diseaseHistory !== '') {
          values.perIndustryInfoList.push({
            fieldCode: 'diseaseHistory',
            fieldValue: values.diseaseHistory,
            perIndFieldId: this.state.perIndFieldId
          });
        }
        if (values.isVeteran !== '' && values.isVeteran !== undefined) {
          values.perIndustryInfoList.push({
            fieldCode: 'isVeteran',
            fieldValue: values.isVeteran,
            perIndFieldId: this.state.perIndFieldId
          });
        }
        if (values.workMonths !== '') {
          values.perIndustryInfoList.push({
            fieldCode: 'workMonths',
            fieldValue: values.workMonths,
            perIndFieldId: this.state.perIndFieldId
          });
        }
        if (values.workYears !== '') {
          values.perIndustryInfoList.push({
            fieldCode: 'workYears',
            fieldValue: values.workYears,
            perIndFieldId: this.state.perIndFieldId
          });
        }
        delete values.diseaseHistory;
        delete values.isVeteran;
        delete values.workMonths;
        delete values.workYears;
        values.perIndustryInfoList = JSON.stringify(values.perIndustryInfoList);
        values.perId = this.state.perId;
        console.log('提交的数据: ', values);
        //先校验没错的时候在提交
        ajax.systemPerBaseInfoUpdateDetailedInfo({ ...values }).then(
          data => {
            // console.log(data.data);
            this.props.props.history.push(
              `/PersonnelRecruitment/departmentmanagement`
            );
          },
          err => {
            console.log(err);
          }
        );
      }
      // values.perId = this.state.perId;
      // ajax.systemPerBaseInfoUpdateDetailedInfo({...values}).then((data)=>{
      //   console.log(data.data);
      // },(err)=>{
      //   console.log(err);
      // })
    });
  };

  //一次性获取所有字典数据
  renderAllDictInformation = () => {
    ajax
      .publicCommonDictGetDictByCodeTypes({
        codeTypes:
          'nationality,education,bloodType,nation,politicalStatus,maritalStatus,drivingLicenseLevel,residentType'
      })
      .then(
        data => {
          //判断获取数据是否为空
          if (data.data) {
            this.setState({
              nationList: data.data.nationality, //国籍下拉选择
              educationList: data.data.education, //学历下拉选择
              bloodList: data.data.bloodType, //血型下拉选择
              nationMoreList: data.data.nation, //民族下拉选择
              politicalList: data.data.politicalStatus, //政治面貌下拉选择
              maritalList: data.data.maritalStatus, //婚姻下拉选择
              drivingList: data.data.drivingLicenseLevel, //驾照下拉选择
              residentList:data.data.residentType//户籍类型下拉
            });
          }
        },
        err => {
          console.log(err);
        }
      );
  };

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

  educationList = () => {
    return this.state.educationList.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };
  // //获取人员类别
  // renderPerType = () => {
  //   // debugger
  //   ajax.getPerType({ codeType: 'perType' }).then(
  //     response => {
  //       console.log(response);
  //       if (response.data) {
  //         this.setState({
  //           perTypeList: response.data
  //         });
  //       }
  //     },
  //     err => {
  //       console.log(err);
  //     }
  //   );
  // };
  // perTypeList = () => {
  //   return this.state.perTypeList.map((val, key) => {
  //     return (
  //       <Option key={key} value={val.codeValue + ''}>
  //         {val.label}
  //       </Option>
  //     );
  //   });
  // };

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

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

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

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

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

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

  //特殊字段
  specialList = () => {
    return this.state.specialInformationData.map((val, key) => {
      return (
        <div className='wed' key={key}>
          {this.renderForm(val)}
        </div>
      );
    });
  };

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

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

  //遍历特殊字段
  renderForm = value => {
    // console.log(value);
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 10 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 7 }
      }
    };
    if (value.fieldType === '1') {
      return (
        <FormItem {...formItemLayout} label={value.fieldName}>
          {getFieldDecorator(`${value.fieldCode}`, {
            initialValue: `${value.fieldValue}`,
            rules: [
              { required: true, message: `请输入${value.fieldName}!` }
            ]
          })(
            <TextArea
              placeholder='请填写'
              style={{ height: 150 }}
              maxLength={value.maxLength}
            />
          )}
        </FormItem>
      );
    } else if (value.fieldType === '2') {
      return (
        <FormItem {...formItemLayout} label={value.fieldName}>
          {getFieldDecorator(`${value.fieldCode}`, {
            initialValue: `${value.fieldValue}`,
            rules: [
              { required: true, message: `请选择${value.fieldName}!` }
            ]
          })(<InputNumber className='width-400' />)}
        </FormItem>
      );
    } else if (value.fieldType === '3') {
      return (
        <FormItem {...formItemLayout} label={value.fieldName}>
          {getFieldDecorator(`${value.fieldCode}`, {
            initialValue: moment(`${value.fieldValue}`, 'YYYY-MM-DD') || null,
            rules: [
              { required: true, message: `请选择${value.fieldName}!` }
            ]
          })(<DatePicker />)}
        </FormItem>
      );
    } else if (value.fieldType === '4') { //是否退伍军人，从业年限--年（月）
      return (
        <FormItem {...formItemLayout} label={value.fieldName}>
          {getFieldDecorator(`${value.fieldCode}`, {
            initialValue: `${value.fieldValue}`,
            rules: [
              { required: true, message: `请选择${value.fieldName}!` }
            ]
          })(
            <Select className='width-400' placeholder='请选择'>
              {this.renderSecrialData(value.dictList)}
            </Select>
          )}
        </FormItem>
      );
    }
  };

  //身高比较
  checkHeight = (rule, value, callback) => {
    if (value && !/^([1-9][0-9]\d{0,1})$/.test(value)) {
      callback('请输入正确的身高！');
    } else {
      callback();
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 10 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 7 }
      }
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 14,
          offset: 6
        }
      }
    };

    return (
      <div className='DetailedInformationPage PersonnelGeneralStyle'>
        <div className='general-main'>
          <div className='from-box'>
            <Form onSubmit={this.handleSubmit}>
              
              {this.state.basicInFormaationData.birthday ? (
                <FormItem {...formItemLayout} label='出生日期'>
                  {getFieldDecorator('birthday', {
                    initialValue: moment(
                      this.state.basicInFormaationData.birthday,
                      'YYYY-MM-DD'
                    ),
                    rules: [{ required: true, message: '请选择出生日期!' }]
                  })(<DatePicker className='width-400' disabled />)}
                </FormItem>
              ) : (
                <FormItem {...formItemLayout} label='出生日期'>
                  {getFieldDecorator('birthday', {
                    rules: [{ required: true, message: '请选择出生日期!' }]
                  })(<DatePicker className='width-400' disabled />)}
                </FormItem>
              )}
              <FormItem {...formItemLayout} label='性别'>
                {getFieldDecorator('sex', {
                  initialValue: this.state.basicInFormaationData.sex,
                  rules: [{ required: true, message: '请选择性别!' }]
                })(
                  <RadioGroup disabled>
                    <Radio value='1'>男</Radio>
                    <Radio value='2' style={{ marginLeft: '46px' }}>
                      女
                    </Radio>
                  </RadioGroup>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='国籍'>
                {getFieldDecorator('nationality', {
                  initialValue: this.state.basicInFormaationData.nationality,
                  rules: [{ required: true, message: '请选择国籍!' }]
                })(
                  <Select className='width-400' placeholder='请选择'>
                    {this.nationList()}
                  </Select>
                )}
              </FormItem>
              {/* <FormItem {...formItemLayout} label='籍贯'>
                {getFieldDecorator('originPlace', {
                  initialValue: this.state.basicInFormaationData.originPlace,
                  rules: [
                    {
                      required: true,
                      message: '请输入籍贯!'
                    }
                  ]
                })(
                  <Input
                    className='width-400'
                    placeholder='请填写'
                    maxLength={30}
                  />
                )}
              </FormItem> */}
              <FormItem {...formItemLayout} label='学历'>
                {getFieldDecorator('education', {
                  initialValue: this.state.basicInFormaationData.education,
                  rules: [
                    {
                      required: true,
                      message: '请输入学历!'
                    },
                    {
                      validator: this.checkConfirm
                    }
                  ]
                })(
                  <Select className='width-400' placeholder='请选择'>
                    {this.educationList()}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='身高'>
                {getFieldDecorator('height', {
                  initialValue: this.state.basicInFormaationData.height,
                  rules: [
                    {
                      required: true,
                      message: '请输入身高!'
                    },
                    {
                      validator: this.checkHeight
                    }
                  ]
                })(
                  <Input
                    style={{ width: 400 }}
                    placeholder='请填写'
                    addonAfter='CM'
                    maxLength={3}
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='血型'>
                {getFieldDecorator('bloodType', {
                  initialValue: this.state.basicInFormaationData.bloodType,
                  rules: [{ required: true, message: '请选择血型!' }]
                })(
                  <Select className='width-400' placeholder='请选择'>
                    {this.bloodList()}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='民族'>
                {getFieldDecorator('nation', {
                  initialValue: this.state.basicInFormaationData.nation,
                  rules: [{ required: true, message: '请选择民族!' }]
                })(
                  <Select className='width-400' placeholder='请选择'>
                    {this.nationMoreList()}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='政治面貌'>
                {getFieldDecorator('politicalStatus', {
                  initialValue: this.state.basicInFormaationData
                    .politicalStatus,
                  rules: [{ required: true, message: '请选择政治面貌!' }]
                })(
                  <Select className='width-400' placeholder='请选择'>
                    {this.politicalList()}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='婚姻状况'>
                {getFieldDecorator('maritalStatus', {
                  initialValue: this.state.basicInFormaationData.maritalStatus,
                  rules: [{ required: true, message: '请选择婚姻状况!' }]
                })(
                  <Select className='width-400' placeholder='请选择'>
                    {this.maritalList()}
                  </Select>
                )}
              </FormItem>
              {this.state.basicInFormaationData.residentProvince !== '' ? (
                <FormItem {...formItemLayout} label='身份证住址'>
                  {getFieldDecorator('resident', {
                    initialValue: [
                      parseInt(
                        this.state.basicInFormaationData.residentProvince
                      ),
                      parseInt(this.state.basicInFormaationData.residentCity),
                      parseInt(this.state.basicInFormaationData.residentArea)
                    ],
                    rules: [
                      {
                        type: 'array',
                        required: true,
                        message: '请选择你的身份证住址!'
                      }
                    ]
                  })(
                    // <Cascader
                    //   options={this.state.areas}
                    //   placeholder='请选择'
                    //   className='width-400'
                    // />
                    <PCascader placeholder="请选择" className='width-400'/>
                  )}
                </FormItem>
              ) : (
                <FormItem {...formItemLayout} label='身份证住址'>
                  {getFieldDecorator('resident', {
                    initialValue: ['', '', ''],
                    rules: [
                      {
                        type: 'array',
                        required: true,
                        message: '请选择你的身份证住址!'
                      }
                    ]
                  })(
                    // <Cascader
                    //   options={this.state.areas}
                    //   placeholder='请选择'
                    //   className='width-400'
                    // />
                    <PCascader placeholder="请选择" className='width-400'/>
                  )}
                </FormItem>
              )}
              <FormItem {...formItemLayout} label='详细地址'>
                {getFieldDecorator('residenceAddress', {
                  initialValue: this.state.basicInFormaationData
                    .residenceAddress,
                  rules: [
                    {
                      required: true,
                      message: '请输入地址!'
                    }
                  ]
                })(
                  <Input
                    className='width-400'
                    placeholder='请填写身份证件详细地址'
                    maxLength={100}
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='户籍类型'>
                {getFieldDecorator('residentType', {
                  initialValue: this.state.basicInFormaationData.residentType,
                  rules: [{ required: true, message: '请选择户籍类型!' }]
                })(
                  <Select className='width-400' placeholder='请选择'>
                    {this.residentList()}
                  </Select>
                )}
              </FormItem>
              {this.state.basicInFormaationData.domicileProvince !== '' ? (
                <FormItem {...formItemLayout} label='居住住址'>
                  {getFieldDecorator('domicile', {
                    initialValue: [
                      parseInt(
                        this.state.basicInFormaationData.domicileProvince
                      ),
                      parseInt(this.state.basicInFormaationData.domicileCity),
                      parseInt(this.state.basicInFormaationData.domicileArea)
                    ],
                    rules: [
                      {
                        type: 'array',
                        required: true,
                        message: '请选择你的居住住址!'
                      }
                    ]
                  })(
                    // <Cascader
                    //   options={this.state.areas}
                    //   placeholder='请选择'
                    //   className='width-400'
                    // />
                    <PCascader placeholder="请选择" className='width-400'/>
                  )}
                </FormItem>
              ) : (
                <FormItem {...formItemLayout} label='居住住址'>
                  {getFieldDecorator('domicile', {
                    initialValue: ['', '', ''],
                    rules: [
                      {
                        type: 'array',
                        required: true,
                        message: '请选择你的居住住址!'
                      }
                    ]
                  })(
                    // <Cascader
                    //   options={this.state.areas}
                    //   placeholder='请选择'
                    //   className='width-400'
                    // />
                    <PCascader placeholder="请选择" className='width-400'/>
                  )}
                </FormItem>
              )}
              <FormItem {...formItemLayout} label='详细地址'>
                {getFieldDecorator('domicileAddress', {
                  initialValue: this.state.basicInFormaationData
                    .domicileAddress,
                  rules: [
                    {
                      required: true,
                      message: '请输入地址!'
                    }
                  ]
                })(
                  <Input
                    className='width-400'
                    placeholder='请填写详细居住地址'
                    maxLength={100}
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='紧急联系人'>
                {getFieldDecorator('contactper', {
                  initialValue: this.state.basicInFormaationData.contactper,
                  rules: [
                    {
                      required: true,
                      message: '请输入紧急联系人!'
                    }
                  ]
                })(
                  <Input
                    className='width-400'
                    placeholder='请填写'
                    maxLength={10}
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='紧急联系人手机号'>
                {getFieldDecorator('contactPhone', {
                  initialValue: this.state.basicInFormaationData.contactPhone,
                  rules: [
                    { required: true, message: '请输入紧急联系人手机号' },
                    {
                      validator: this.checkPhone
                    }
                  ]
                })(
                  <Input
                    className='width-400'
                    placeholder='请填写正确手机号码'
                    maxLength={11}
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='驾照等级'>
                {getFieldDecorator('drivingLicenseLevel', {
                  initialValue: this.state.basicInFormaationData
                    .drivingLicenseLevel,
                  rules: [{ required: true, message: '请选择驾照等级!' }]
                })(
                  <Select className='width-400' placeholder='请选择'>
                    {this.drivingList()}
                  </Select>
                )}
              </FormItem>
              {this.specialList()}
              <FormItem {...tailFormItemLayout}>
                {/*<Button type="primary" htmlType="button" style={{ "backgroundColor": "#FFF", "color": "#666", "borderColor": "#ccc" }}>取消</Button>*/}
                <Button type='primary' htmlType='submit'>
                  保存
                </Button>
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
    );
  }
}
