import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form, Input, Select, Button, Radio, DatePicker, Checkbox, Row, Col, message, Modal, Drawer
} 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 OverseasDetails extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open: 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) {
    // console.log(this.state.open);
    // console.log(props.visible);
    // if (this.state.open !== props.visible) {
      this.setState({ open: props.visible, overseaManageId: props.overseaManageId });
      // this.renderOverseas();
      // this.getDictionaryData(); //获取所有所需要字典数据
    // }
  }
  componentDidMount() {
    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
          });
        }
      });
  };

  renderOverseas = () => {
    if (this.state.overseaManageId !== '00') {
      ajax.comStockGetOverseaManageById({
        overseaManageId: this.state.overseaManageId
      }).then((data) => {
        console.log('获取海外经营信息', data, 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) => {
    console.log(`selected ${value}`);
    this.setState({
      nation: value,
    });
  };


  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('values', values);
        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) => {
            // 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);
  };

  //经营模式选择
  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>
      return <div className="check_item" key={key} style={{ marginTop: '5px', color: 'red'}}><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({
            open: 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
        overlayColor="rgba(0, 0, 0,0)"
        placement="right"
        title="修改记录"
        visible={this.state.open}
        destroyOnClose
        width={600}
        zIndex={11}
        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> */}
        <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: /^[a-zA-Z\u4e00-\u9fa5]+$/,
                  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>
          </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',
            }}>
            {/* <div> */}
              <Button loading={submitting} onClick={this.fan}>
                返回
              </Button>
              <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit" loading={this.state.loading} onClick={this.handleSubmit}>提交</Button>
            </div>
            {/* </FormItem> */}
      </Drawer>
        );
      }
    }
