import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form,
  Input,
  Select,
  Button,
  Drawer,
  DatePicker,
  Checkbox,
  Row,
  Col,
  message,
  Modal
} from 'antd';
import * as ajax from '../../../services/api';
import moment from 'moment';
import './less/report.less';
// import Drawer from 'react-motion-drawer';

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

const confirm = Modal.confirm;

const dateFormat = 'YYYY-MM-DD';

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class AssOverseasDetails extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open2: this.props.visible,
      loading: false,
      overseaManageId: this.props.overseaManageId, //传过来的方案id
      nationality: [],
      manageList: [],
      securityRange: [],
      securityRangeContentArrays: [], //安保范围数组
      overseasList: {
        nationality: '',
        recordPoliceName: '',
        recordDate: '',
        startDate: '',
        endDate: '',
        securityRange: [],
        securityRangeContentArrays: [],
        manageMode: ''
      },
      fan: false
    };
  }
  componentWillReceiveProps(props) {
    // if (this.state.open2 !== props.visible) {
      this.setState(
        { open2: props.visible, overseaManageId: props.overseaManageId }
      );
      // this.renderOverseas();
      // this.getDictionaryData(); //获取所有所需要字典数据
    // }
  }
  componentDidMount() {
    this.props.onRef(this);
    this.renderOverseas();
    this.getDictionaryData(); //获取所有所需要字典数据
  }

  //获取所有所需要字典数据
  getDictionaryData = () => {
    ajax
      .publicCommonDictGetDictByCodeTypes({
        codeTypes: ['nationality', 'manageMode', 'securityRange']
      })
      .then(data => {
        //判断获取数据是否为空
        if (data.data) {
          this.setState({
            nationality: data.data.nationality, //国籍选择
            manageList: data.data.manageMode,
            securityRange: data.data.securityRange
          });
        }
      });
  };

  //重置表单
  resetFrom = () => {
    const { setFieldsValue } = this.props.form;
    setFieldsValue({
      nationality: '',
      recordPoliceName: '',
      recordDate: null,
      startDate: null,
      endDate: '',
      securityRange: [],
      securityRangeContentArrays: [],
      manageMode: ''
    });
  };

  renderOverseas = () => {
    if (this.state.overseaManageId !== '00') {
      ajax
        .comStockGetOverseaManageById({
          overseaManageId: this.state.overseaManageId
        })
        .then(data => {
          this.setState({
            overseasList: data.data
          });
        });
    }
  };

  //国家下拉选择值
  renderNationality = () => {
    return this.state.nationality.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  //国家选中值
  handleChangeNation = value => {
    this.setState({
      nation: value
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.recordDate = values['recordDate'].format('YYYY-MM-DD');
        values.startDate = values['startDate'].format('YYYY-MM-DD');
        values.endDate = values['endDate'].format('YYYY-MM-DD');
        values.securityRangeContentArrays = values.securityRange;
        // values.comId = this.state.comId;
        if (this.state.crossManageId !== '00') {
          values.overseaManageId = this.state.overseaManageId;
        }
        const d1 = new Date(values.startDate.replace(/\-/g, '/'));
        const d2 = new Date(values.recordDate.replace(/\-/g, '/'));
        const d3 = new Date(values.endDate.replace(/\-/g, '/'));
        if (d1 < d2) {
          message.error('海外经营开始日期不能早于备案日期');
        } else if (d3 < d1) {
          message.error('经营结束日期不能早于经营开始日期');
        } else {
          this.setState({ loading: true });
          ajax.stockSubmitComStockSaveOverseaManage({ ...values }).then(
            data => {
              // message.success('海外经营详情保存成功！');
              this.setState(
                {
                  fan: true,
                  loading: false
                },
                () => {
                  this.props.close();
                }
              );
            },
            err => {
              this.setState({ loading: false });
            }
          );
        }
      }
    });
  };
  callback = key => {
  };
  onChangeCheck = checkedValues => {
  };

  //经营模式选择
  manageMode = () => {
    return this.state.manageList.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  //安保范围选择
  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>
        <div className="check_item" key={key} span={8} style={{ marginTop: '5px' }}>
          <Checkbox value={val.codeValue + ''}>{val.label}</Checkbox>
        </div>
      );
    });
  };

  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();
          // _that.setState({
          //   open2: false
          // });
          _that.props.onChange(false);
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

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

    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
        title="新增记录"
        placement="right"
        visible={this.props.visible}
        width={600}
        onClose={() => {
          this.props.onChange(false);
        }}
        maskClosable={false} // 不允许点击遮罩关闭
      >
        <div>
          <Form onSubmit={this.handleSubmit} style={{ marginTop: 32 }}>
            <FormItem {...formItemLayout} label="涉外经营国别">
              {getFieldDecorator('nationality', {
                initialValue: this.state.overseasList.nationality,
                rules: [{ required: true, message: '请选择涉外经营国别' }]
              })(
                <Select
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  onChange={this.handleChangeNation}
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                >
                  <Option value="">请选择</Option>
                  {this.renderNationality()}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="备案公安机关名称">
              {getFieldDecorator('recordPoliceName', {
                initialValue: this.state.overseasList.recordPoliceName,
                rules: [
                  {
                    required: true,
                    message: '请输入备案公安机关名称'
                  },
                  {
                    pattern: /^[\u4E00-\u9FA5\（\）]{1,20}$/,
                    message: '请输入中文最大长度20'
                  }
                ]
              })(<Input placeholder="请输入" maxLength={20} />)}
            </FormItem>
            {this.state.overseaManageId === '00' ? (
              <FormItem {...formItemLayout} label="备案日期">
                {getFieldDecorator('recordDate', {
                  rules: [
                    {
                      required: true,
                      message: '请选择备案日期'
                    }
                  ]
                })(<DatePicker style={{ width: '100%' }} />)}
              </FormItem>
            ) : (
              <FormItem {...formItemLayout} label="备案日期">
                {getFieldDecorator('recordDate', {
                  initialValue: moment(
                    this.state.overseasList.recordDate,
                    dateFormat
                  ),
                  rules: [
                    {
                      required: true,
                      message: '请选择备案日期'
                    }
                  ]
                })(<DatePicker style={{ width: '100%' }} />)}
              </FormItem>
            )}
            {this.state.overseaManageId === '00' ? (
              <FormItem {...formItemLayout} label="海外经营开始日期">
                {getFieldDecorator('startDate', {
                  rules: [
                    {
                      required: true,
                      message: '请选择海外经营开始日期'
                    }
                  ]
                })(<DatePicker style={{ width: '100%' }} />)}
              </FormItem>
            ) : (
              <FormItem {...formItemLayout} label="海外经营开始日期">
                {getFieldDecorator('startDate', {
                  initialValue: moment(
                    this.state.overseasList.startDate,
                    dateFormat
                  ),
                  rules: [
                    {
                      required: true,
                      message: '请选择海外经营开始日期'
                    }
                  ]
                })(<DatePicker style={{ width: '100%' }} />)}
              </FormItem>
            )}
            {this.state.overseaManageId === '00' ? (
              <FormItem {...formItemLayout} label="海外经营结束日期">
                {getFieldDecorator('endDate', {
                  rules: [
                    {
                      required: true,
                      message: '请选择海外经营结束日期'
                    }
                  ]
                })(<DatePicker style={{ width: '100%' }} />)}
              </FormItem>
            ) : (
              <FormItem {...formItemLayout} label="海外经营结束日期">
                {getFieldDecorator('endDate', {
                  initialValue: moment(
                    this.state.overseasList.endDate,
                    dateFormat
                  ),
                  rules: [
                    {
                      required: true,
                      message: '请选择海外经营结束日期'
                    }
                  ]
                })(<DatePicker style={{ width: '100%' }} />)}
              </FormItem>
            )}
            <FormItem {...formItemLayout} label="安保范围">
              {getFieldDecorator('securityRange', {
                initialValue: this.state.overseasList
                  .securityRangeContentArrays,
                rules: [
                  {
                    required: true,
                    message: '请选择'
                  }
                ]
              })(
                <Checkbox.Group onChange={this.onChangeCheck}>
                  <Row className="check_items">{this.renderList()}</Row>
                </Checkbox.Group>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="经营模式">
              {getFieldDecorator('manageMode', {
                initialValue: this.state.overseasList.manageMode,
                rules: [{ required: true, message: '请选择经营模式' }]
              })(
                <Select placeholder="请选择" onChange={this.handleChangeMode}>
                  <Option value="">请选择</Option>
                  {this.manageMode()}
                </Select>
              )}
            </FormItem>
            {/* <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
                        <Button loading={submitting} onClick={this.fan}>
                            返回
                        </Button>
                        <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit" loading={this.state.loading}>提交</Button>
                    </FormItem> */}
            <div
              style={{
                position: 'absolute',
                left: 0,
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e9e9e9',
                padding: '10px 16px',
                background: '#fff',
                textAlign: 'right'
              }}
            >
              <Button
                loading={submitting}
                onClick={this.fan}
                style={{ marginRight: '8px' }}
              >
                返回
              </Button>
              <Button
                type="primary"
                style={{ marginLeft: 8 }}
                htmlType="submit"
                loading={this.state.loading}
                onSubmit={this.handleSubmit}
              >
                提交
              </Button>
            </div>
          </Form>
        </div>
      </Drawer>
    );
  }
}
