import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form, Input, Select, Button, Radio,DatePicker,Checkbox, Row, Col,Modal,message,Cascader
} from 'antd';
import * as ajax from "../../../services/api";
import './less/report.less';
const RadioGroup = Radio.Group;
const { Option } = Select;
const {TextArea} = Input;
const FormItem = Form.Item;
const confirm = Modal.confirm;
import PCascader from '../../../components/Pro/PCascader';

@connect(state => ({
  profile: state.profile,
}))

@Form.create()

export default class ManagementChange extends Component {
  constructor(props,context){
    super(props,context);
    this.state = {
      // comId:1,
      uid:1,
      loading:false,
      idCardType:'',
      nameList:[],
      fan:false,
      // areas: [],//地区
      nationList:[],
      idCardList:[],
      educationList:[],
      skillList:[],
      oldComManagerId:'',
      oldManagerName:'',
      oldManagerIdCardNo:'',
      newManagerName:'',
      newManagerIdCardNo:'',
    }
  }

  componentDidMount() {
    this.nameGroup();
    // this.getDistrict();
    this.getDictionaryData(); //获取所有所需要字典数据
  }

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

  // //省市区
  // 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,
  //     });
  //   })
  // };

  nameGroup = () => {
    ajax.comStockComManageListByStatus({
      pageSize:1,
      pageNumber:10,
    }).then((data) => {
      if(data.data){
        this.setState({
          nameList:data.data.data,
        })
      }
    })
  };

  submitHandlerDeep = (that,values) => {
    that.setState({ loading: true });
    ajax.comStockSaveReplaceComManage({...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.oldManagerName = this.state.oldManagerName;
        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.uid = this.state.uid;
        values.oldComManagerId = this.state.oldComManagerId;

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

  renderNationIoi = () => {
    return this.state.nameList.map((val, key) => {
      return <Option key={key} value={val.comManagerId+""}>{val.name} ({val.idCardNo})</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');
        },
      });
    }
  };

  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>;
    });
  };


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

  //证件类型-号码验证
  checkIdCardNo = (rule, value, callback) => {
    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();
    }
  };

  //选择人员，职务发生变化
  handleChangeName = (value) => {
    this.setState({
      oldComManagerId:value,
    });
   ajax.comStockGetComManageById({comManagerId:value}).then((data) =>{
     console.log('选择人员，职务发生变化',data.data);
     if(data.data){
       let sd = data.data.positionName;
       const form = this.props.form;
       form.setFieldsValue({'positionName':sd});
        this.setState({
          oldManagerName:data.data.name,
          oldManagerIdCardNo:data.data.idCardNo,
        });
     }
   })
  };

    //身份证改变事件
    idCardTypeOnChangeHandler = (value) =>{
      // this.props.form.validateFields(['cerNo']);
      this.props.form.setFieldsValue({'newManagerIdCardNo':''});
      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 (
      <div className="ManagementChange">
      <h2>管理员变更</h2>
      <Form
        onSubmit={this.handleSubmit}
        style={{ marginTop: 24 }}
      >
        <h3>原管理人员</h3>
        <FormItem
        {...formItemLayout}
        label="姓名"
      >
        {getFieldDecorator('oldManagerIdCardNo', {
          rules: [{
            required: true, message: '请选择原管理人员姓名',
          }],
        })(
          <Select placeholder="请选择" onChange={this.handleChangeName}>
            {/* <Option value="0">请选择</Option> */}
            {this.renderNationIoi()}
          </Select>
        )}
      </FormItem>
        <FormItem {...formItemLayout} label='部门'>
          {getFieldDecorator('departName', {
            rules: [
              {
                required: true,
                message: '请输入部门'
              },
            ]
          })(<Input placeholder='请输入' maxLength={20} />)}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="职务"
        >
          {getFieldDecorator('positionName', {
            rules: [{
              required: true, message: '请输入职务',
            }],
          })(
            <Input placeholder="请输入" disabled/>
          )}
        </FormItem>
        <h3>现管理人员</h3>
        <FormItem
          {...formItemLayout}
          label="姓名"
        >
          {getFieldDecorator('newManagerName', {
            rules: [{
              required: true, message: '请输入姓名',
            },{
              pattern:/^[\u4e00-\u9fa5]{1,10}$/,message: "请输入最大10个汉字"
            }],
          })(
            <Input placeholder="请输入" />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="职务"
        >
          {getFieldDecorator('positionName', {
            rules: [{
              required: true, message: '请输入职务',
            }],
          })(
            <Input placeholder="请输入" disabled/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="性别"
        >
          {getFieldDecorator('sex',{
            rules: [{
              required: true, message: '请选择性别',
            }],
          })(
            <RadioGroup>
              <Radio value="1">男</Radio>
              <Radio value="2">女</Radio>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label='是否是退伍军人'>
          {getFieldDecorator('isVeteran', {
            rules: [{ required: true, message: '请选是否是退伍军人' }]
          })(
            <RadioGroup>
              <Radio value='0'>否</Radio>
              <Radio value='1'>是</Radio>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="民族"
        >
          {getFieldDecorator('nation',
            {
              rules: [{ required: true, message: '请选择民族' }],
            })(
            <Select placeholder="请选择">
              {this.renderNationList()}
            </Select>
          )}
        </FormItem>
       <FormItem
          {...formItemLayout}
          label="户籍"
        >
          {getFieldDecorator('hu', {
            rules: [{ required: true, message: '请选择户籍' }],
          })(
            // <Cascader options={this.state.areas} placeholder="请选择" />
            <PCascader placeholder="请选择"/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="证件类型"
        >
          {getFieldDecorator('idCardType', {
            rules: [{ required: true, message: '请选择证件类型' }],
          })(
            <Select placeholder="请选择" onChange={this.idCardTypeOnChangeHandler} >
              {this.idCardList()}
            </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="证件号"
        >
        { this.state.idCardType === '1' ?
            getFieldDecorator('newManagerIdCardNo', {
              rules: [{
                required: true, message: '请输入证件号',
              },{
                validator: this.checkIdCardNo
              }],
            })(
              <Input placeholder="请输入" maxLength={20} />
            )
            :
            getFieldDecorator('newManagerIdCardNo', {
              rules: [{
                required: true, message: '请输入证件号',
              },{
                validator: this.checkId
              }],
            })(
              <Input placeholder="请输入" maxLength={20}/>
            )
          }
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="联系方式"
        >
          {getFieldDecorator('telephone', {
            rules: [{
              required: true, message: '请输入联系方式',
            }, {
              validator: this.checkPhone
            }],
          })(
            <Input placeholder="请输入" maxLength={20}/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="学历"
        >
          {getFieldDecorator('education', {
            rules: [{ required: true, message: '请选择学历' }],
          })(
            <Select placeholder="请选择">
              {this.renderEducation()}
            </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="职业技能等级"
        >
          {getFieldDecorator('jobSkillLevel',{
            rules: [{
              required: true, message: '请选择职业技能等级',
            }],
          })(
            <Select placeholder="请选择">
              {this.skillList()}
            </Select>
          )}
        </FormItem>
       <FormItem
          {...formItemLayout}
          label="居住地址"
        >
          {getFieldDecorator('ed', {
            rules: [{ required: true, message: '请选择居住地址' }],
          })(
            // <Cascader options={this.state.areas} placeholder="请选择" />
            <PCascader placeholder="请选择"/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label=" "
          colon={false}
          className="detailedAddress"
        >
          {getFieldDecorator('domicileAddress', {
            rules: [{
              required: true,message:'居住具体地址不能为空'
            }],
          })(
            <TextArea row={2} placeholder="请输入" maxLength={50}/>
          )}
        </FormItem>
        <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
          <Button loading={submitting} onClick={this.fan}>
            返回
          </Button>
          <Button type="primary" style={{ marginLeft: 8 }} loading={this.state.loading} htmlType="submit">提交</Button>
        </FormItem>
      </Form>
      </div>
    );
  }
}
