import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form, Input, Select, Button, Radio,DatePicker,Checkbox, Row, Col,Cascader,message,Modal,Drawer
} from 'antd';
import * as ajax from "../../../services/api";
import moment from 'moment';
import "moment/locale/zh-cn";
import PCascader from '../../../components/Pro/PCascader';
// import Drawer from 'react-motion-drawer';

import './less/report.less';

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

const confirm = Modal.confirm;
const dateFormat = 'YYYY-MM-DD';

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

@Form.create()

export default class DistrictDetails extends Component {
  constructor(props,context){
    super(props,context);
    this.state = {
      open: this.props.visible,
      loading: false,
      securityRange:[],//安保范围
      crossManageId: this.props.crossManageId,//传过来的方案id
      // areas: [],//地区
      messageList:{
        province:'',
        city:'',
        area:'',
        address:'',//详细地址
        recordPoliceName:'',//备案公安机关名称
        recordDate:'',//备案日期
        responsPer:'',//负责人
        responsPerPhone:'',//负责人手机号
        idCardNo:'',//负责人身份证号
        post:'',//负责人职务
        startDate:'',//跨区经营开始日期
        telePhone:'',//联系电话
        securityRange:[],//安保范围
        securityRangeContentArrays:[],//安保范围数组
      },
      fan:false,//返回之前是否保存
    }
  };

  componentWillReceiveProps(props) {
    if(this.state.props !== props.visible) {
      this.setState({ open: props.visible,crossManageId:props.crossManageId },() => {
          console.log(this.state.open,this.state.crossManageId)
        });
      this.messageList();
      this.securityRangeList();
      // this.getDistrict();//省市区选择
    }
  }

  // componentDidMount() {
    // this.securityRangeList();
    // this.messageList();
    // this.getDistrict();//省市区选择
    // console.log('thisthisTwo',this);
  // }

  securityRangeList = () =>{
    ajax.publicCommonDictGetDictByCodeTypes({codeTypes:'securityRange'}).then((data) => {
      if (data.data) {
        this.setState({
          securityRange: data.data.securityRange,
        });
      }
    });
  };

  messageList = () => {
    const { setFieldsValue } = this.props.form;
    if(this.state.crossManageId !== '00'){
      ajax.comStockGetCrossManageById({crossManageId:this.state.crossManageId}).then((data) => {
        this.setState({
          messageList:data.data,
        });
      });
    }
  };

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

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.province = values.EconomicType[0];
        if(values.EconomicType[1]){
          values.city = values.EconomicType[1];
        }else{
          values.city = 0;
        }
        if(values.EconomicType[2]){
          values.area = values.EconomicType[2];
        }else{
          values.area = 0;
        }
        values.recordDate = values['recordDate'].format('YYYY-MM-DD');
        values.startDate = values['startDate'].format('YYYY-MM-DD');
        delete values.EconomicType;
        values.securityRangeContentArrays = values.securityRange;
        if(this.state.crossManageId !== '00'){
          values.crossManageId = this.state.crossManageId;
        }
        let d1 = new Date(values.startDate.replace(/\-/g, "\/"));
        let d2 = new Date(values.recordDate.replace(/\-/g, "\/"));
        if(d1<d2){
          message.error('跨区经营开始日期不能早于备案日期');
        }else{
          this.setState({ loading: true });
          ajax.comStockSaveCrossManage({...values}).then((data) => {
            // console.log('提交成功');
            // message.success('跨区经营详情保存成功！');
            this.setState({
              fan:true,
              loading: false,
            },()=>{
                this.props.close();
            });
          },(err) => {
              this.setState({ loading: false });
          });
        }
      }
    });
  };

  callback = (key) => {
    console.log(key);
  };

  onChangeCheck = (checkedValues)=>{
    console.log('checked = ', checkedValues);
  };

  //安保范围选择
  renderList = () => {
    return this.state.securityRange.map((val, key) => {
      return <Col key={key} span={8} style={{ marginTop:'5px' }}><Checkbox value={val.codeValue+""}>{val.label}</Checkbox></Col>
    });
  };

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


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

  //验证固定号码
  checkLandlinePhone = (rule, value, callback) => {
    if (value && !(/^0\d{2,3}-?\d{7,8}$/).test(value)) {
      callback('请输入正确的联系电话！');
    } else {
      callback();
    }
  };

  //验证身份证号码
  checkIdCardNo = (rule, value, callback) => {
    if (value && !(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/).test(value)) {
      callback('请输入正确的身份证号码！');
    } else {
      callback();
    }
  };

  checkPersonName = (rule, value, callback) => {
    if (value && !(/^[\u4e00-\u9fa5_a-zA-Z]+$/).test(value)) {
      callback('请输入正确的负责人姓名！');
    } else {
      callback();
    }
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    // const { setFieldsValue } = 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}
        // noTouchClose
        title="查看记录"
        destroyOnClose
        width={600}
        zIndex={11}
        // className="drawer-box"
        onChange={(open) => {
          this.props.onChange(open);
          this.setState({ open });
        }}
        onClose={() => {
          this.setState({
            open: false
          });
        }}
      >
          {/* <h3 style={{"fontSize":'22px',"padding":"18px",'borderBottom':'1px solid #dedede'}}>修改记录</h3> */}
          {/* <h3 style={{"fontSize":'22px',"padding":"18px",'borderBottom':'1px solid #dedede'}}>查看记录</h3> */}
      <div>
      <Form onSubmit={this.handleSubmit}>
        {this.state.crossManageId === '00' ? <FormItem
          {...formItemLayout}
          label="跨区经营地址"
        >
          {getFieldDecorator('EconomicType', {
            rules: [{ required: true, message: '请选择跨区经营地址' }],
          })(
            // <Cascader options={this.state.areas} placeholder="请选择" disabled/>
            <PCascader placeholder="请选择" disabled/>
          )}
        </FormItem> : <FormItem
          {...formItemLayout}
          label="跨区经营地址"
        >
          {getFieldDecorator('EconomicType', {
            initialValue: [this.state.messageList.province,this.state.messageList.city,this.state.messageList.area],
            rules: [{ required: true, message: '请选择跨区经营地址' }],
          })(
            // <Cascader options={this.state.areas} placeholder="请选择" disabled/>
            <PCascader placeholder="请选择" disabled/>
          )}
        </FormItem>}

        <FormItem
          {...formItemLayout}
          label=" "
          colon={false}
          className="detailedAddress"
        >
          {getFieldDecorator('address', {
            initialValue:this.state.messageList.address,
            rules: [{
              required: true,
              message: '请输入跨区经营具体地址',
            }],
          })(
            <TextArea row={2} placeholder="" maxLength={50} disabled/>
          )}
        </FormItem>

        <FormItem
          {...formItemLayout}
          label="备案公安机关名称"
        >
          {getFieldDecorator('recordPoliceName', {
            initialValue:this.state.messageList.recordPoliceName,
            rules: [{
              required: true, message: '请输入备案公安机关名称',
            },{
              pattern: /^[\u4E00-\u9FA5\（\）]{1,20}$/,
              message: "请输入中文最大长度20"
            }],
          })(
            <Input placeholder="请输入" maxLength={20} disabled/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="负责人"
        >
          {getFieldDecorator('responsPer', {
            initialValue:this.state.messageList.responsPer,
            rules: [{
              required: true, message: '请输入负责人',
            },{
              pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/,
              message: "请输入负责人，中文或英文"
            }],
          })(
            <Input placeholder="请输入" maxLength={10} disabled/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="负责人手机号"
        >
          {getFieldDecorator('responsPerPhone', {
            initialValue:this.state.messageList.responsPerPhone,
            rules: [{
              required: true, message: '请输入负责人手机号',
            },{
              validator: this.checkPhone
            }],
          })(
            <Input placeholder="请输入" maxLength={11} disabled/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="负责人职务"
        >
          {getFieldDecorator('post', {
            initialValue:this.state.messageList.post,
            rules: [{
              pattern: /^[\u4e00-\u9fa5]{1,20}$/, message: '请输汉字最大20位!',
            },{ required: true, message: '请选择负责人职务' }],
          })(
            <Input placeholder="请输入" maxLength={20} disabled/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="负责人身份证号"
        >
          {getFieldDecorator('idCardNo', {
            initialValue:this.state.messageList.idCardNo,
            rules: [{
              required: true, message: '请输入负责人身份证号',
            },{
              validator: this.checkIdCardNo
            }],
          })(
            <Input placeholder="请输入" maxLength={18} disabled/>
          )}
        </FormItem>

        {this.state.crossManageId === '00' ? <FormItem
          {...formItemLayout}
          label="跨区经营开始日期"
        >
          {getFieldDecorator('startDate', {
            rules: [{ type: 'object', required: true, message: '跨区经营开始日期不能为空' }],
          })(
            <DatePicker style={{ width:'100%' }} disabled/>
          )}
        </FormItem> : <FormItem
          {...formItemLayout}
          label="跨区经营开始日期"
        >
          {getFieldDecorator('startDate', {
            initialValue: moment(this.state.messageList.startDate, dateFormat),
            rules: [{ type: 'object', required: true, message: '跨区经营开始日期不能为空' }],
          })(
            <DatePicker style={{ width:'100%' }} disabled/>
          )}
        </FormItem>}

        {this.state.crossManageId === '00' ?   <FormItem
          {...formItemLayout}
          label="备案日期"
        >
          {getFieldDecorator('recordDate', {
            rules: [{ type: 'object', required: true, message: '备案日期不能为空' }],
          })(
            <DatePicker style={{ width:'100%' }} disabled/>
          )}
        </FormItem> :  <FormItem
          {...formItemLayout}
          label="备案日期"
        >
          {getFieldDecorator('recordDate', {
            initialValue: moment(this.state.messageList.recordDate, dateFormat),
            rules: [{ type: 'object', required: true, message: '备案日期不能为空' }],
          })(
            <DatePicker style={{ width:'100%' }} disabled/>
          )}
        </FormItem>}

        {/* 
          *2019-5-20 隐藏
         */}
        {/* <FormItem
          {...formItemLayout}
          label="联系电话"
        >
          {getFieldDecorator('telePhone', {
            initialValue:this.state.messageList.telePhone,
            rules: [{
              required: true, message: '请输入联系电话',
            },{
              validator: this.checkLandlinePhone
            }],
          })(
            <Input placeholder="请输入" maxLength={15} disabled/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="安保范围"
        >
          {getFieldDecorator('securityRange', {
            initialValue:this.state.messageList.securityRangeContentArrays,
            rules: [{
              required: true, message: '请选择安保范围',
            }],
          })(
            <Checkbox.Group onChange={this.onChangeCheck} disabled>
              <Row>
                {this.renderList()}
              </Row>
            </Checkbox.Group>
          )}
        </FormItem> */}
        </Form>
        </div>
        {/* <FormItem {...submitFormLayout} style={{ marginTop: 32 }}> */}
        <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 }} htmlType="submit" loading={this.state.loading}>提交</Button> */}
        {/* </FormItem> */}
        </div>
      </Drawer>
    );
  }
}
