import React from 'react';
import {
  Form,
  Input,
  Button,
  DatePicker,
  Icon,
  Radio,
  Upload,
  notification
} from 'antd';
import moment from 'moment';
import {
  enterpriseComContractGetComContractById,
  uploadUrl,
  enterpriseComContractInsertComContract
} from '../../../services/api';
import PDrawer from '../../../components/Pro/PDrawer';
import PSelect from '../../../components/Pro/PSelect';
import bcx_utils from '../../../common/bcx_utils';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
@Form.create()
export default class DrawRenew extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      dataSource: {
        contractType: '', //合同类型
        contractName: '', //合同名称
        comFileNo: '', //企业档案编号
        comParty: '', //我方为 1 甲方，2 乙方
        firstPartyName: '', //甲方名称
        firstPartyTel: '', //甲方联系电话
        secondPartyName: '', //乙方名称
        secondPartyTel: '', //乙方联系电话
        effectStartDate: bcx_utils.currentData(), //生效开始日期
        effectEndDate: bcx_utils.currentData(), //生效结束日期
        payAmount: '', //付费金额
        payDate: '', //付费日期
        agreementSignDate: '', //协议签订日期
        remark: '' //合同备注日期
      }
    };
  }

  /******************************生命周期******************************/

  componentDidMount = () => {
  };

  componentWillReceiveProps = (nextProps) => {
    if (!this.props.visible && nextProps.visible && nextProps.comContractId) {
      this.ajaxContractDetail(nextProps.comContractId);
    }
  };

  /******************************ajax请求******************************/
  //获取订单详情
  ajaxContractDetail = comContractId => {
    enterpriseComContractGetComContractById({ comContractId }).then(
      ({ data }) => {
        if (!data) {
          return;
        }
        const dataSource = { ...this.state.dataSource };
        this.setState({ dataSource: { ...dataSource, ...data } });
      },
      err => {
        console.log(err);
      }
    );
  };
  /******************************相关事件******************************/
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (
          values.agreementSignDate &&
          values.agreementSignDate !== undefined &&
          values.agreementSignDate !== null
        ) {
          values.agreementSignDate = values['agreementSignDate'].format(
            'YYYY-MM-DD'
          );
        } else {
          values.agreementSignDate = '';
        }
        if (
          values.effectDate
        ) {
          values.effectStartDate = values['effectDate'][0].format('YYYY-MM-DD');
          values.effectEndDate = values['effectDate'][1].format('YYYY-MM-DD');
          delete values.effectDate;
        } else {
          values.effectStartDate = '';
          values.effectEndDate = '';
          delete values.effectDate;
        }
        if (
          values.payDateSd 
        ) {
          values.payDate = values['payDateSd'].format('YYYY-MM-DD');
        } else {
          values.payDate = '';
        }
        if (values.contractUrl && values.contractUrl.fileList) {
          values.contractUrl = values.contractUrl.fileList[0].response.data;
        } else {
          values.contractUrl = '';
        }

        // 隐藏的字段
        values.comContractId = this.state.dataSource.comContractId;
        values.comId = this.state.dataSource.comId;
        values.contractStatus = this.state.dataSource.contractStatus;
        enterpriseComContractInsertComContract({ ...values }, true).then(
          () => {
            notification.success({message: '续签成功'});
            this.props.changeTable();
            this.props.confirDrawer();
          },
          err1 => {
            console.log(err1);
            this.props.confirDrawer();
          }
        ).catch(res => {
          notification.error({message: res.msg});
        });
      }
    });
  };

  closeDrawer = () => {
    this.props.closeDrawer();
  };

  /******************************render******************************/

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

    const {
      contractType,
      contractName,
      comFileNo,
      comParty,
      firstPartyName,
      firstPartyTel,
      secondPartyName,
      secondPartyTel,
      effectStartDate,
      effectEndDate,
      payAmount,
      payDate,
      agreementSignDate,
      remark,
      contractUrl
    } = this.state.dataSource;

    const dateFormat = 'YYYY-MM-DD';
    return (
      <PDrawer
        title="续签合同"
        visible={visible}
        okText="确认"
        cancelText="返回"
        onCancel={this.closeDrawer}
        onOk={this.handleSubmit}
        destroyOnClose={true}
      >
        <div>
          <Form
            onSubmit={this.handleSubmit}
            style={{ width: 390, margin: '6px 0 81px 0' }}
          >
            <FormItem
              {...formItemLayout1}
              label="合同类型"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('contractType', {
                initialValue: contractType,
                rules: [{
                  required:true,
                  message: "请选择合同类型"
                }]
              })(<PSelect type="contractType" style={{ width: 294 }} />)}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="合同名称"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('contractName', {
                initialValue: contractName,
                rules: [{
                  required:true,
                  message: '请输入合同名称'
                }]
              })(<Input style={{ width: 294 }} />)}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="企业档案编号"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('comFileNo', {
                initialValue: comFileNo,
                rules: [{
                  required:true,
                  message: '请输入企业档案编号'
                }]
              })(<Input style={{ width: 294 }} />)}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="我方为"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('comParty', {
                initialValue: comParty,
                rules: [{
                  required:true
                }]
              })(
                <RadioGroup>
                  <Radio value="1">甲方</Radio>
                  <Radio value="2">乙方</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="甲方"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('firstPartyName', {
                initialValue: firstPartyName,
                rules: [{
                  required:true,
                  message: '请输入甲方姓名'
                }]
              })(<Input style={{ width: 294 }} />)}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="联系电话"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('firstPartyTel', {
                initialValue: firstPartyTel,
                rules: [{
                  required:true,
                  message: '请输入甲方电话'
                }]
              })(<Input style={{ width: 294 }} />)}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="乙方"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('secondPartyName', {
                initialValue: secondPartyName,
                rules: [{
                  required:true,
                  message: '请输入乙方姓名'
                }]
              })(<Input style={{ width: 294 }} />)}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="联系电话"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('secondPartyTel', {
                initialValue: secondPartyTel,
                rules: [{
                  required:true,
                  message: '请输入联系电话'
                }]
              })(<Input style={{ width: 294 }} />)}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="合同有效期"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('effectDate', {
                initialValue: [
                  effectStartDate? moment(effectStartDate.slice(0, 10), dateFormat): '',
                  effectEndDate? moment(effectEndDate.slice(0, 10), dateFormat): ''
                ],
                rules: [{
                  required:true,
                  message: '请选择合同有效期'
                },{
                  validator: (rule, value, cb) => {
                    if(!value) {
                      cb('请选择时间');
                    }
                    if(value[0] == '') {
                      cb('请选择时间');
                    }
                    if(value[1] == '') {
                      cb('请选择时间');
                    }
                    cb();
                  }
                }]
              })(<DatePicker.RangePicker style={{ width: 294 }} />)}
            </FormItem>
            {/* <FormItem
              {...formItemLayout1}
              label="付费金额"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('payAmount', {
                initialValue: payAmount,rules: [{
                  required:true
                }]
              })(<Input style={{ width: 294 }} />)}
            </FormItem> */}
            {/* <FormItem
              {...formItemLayout1}
              label="付费日期"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('payDate', {
                initialValue: !!payDate
                  ? moment(payDate.slice(0, 10), dateFormat)
                  : undefined,
                  rules: [{
                    required:true
                  }]
              })(<DatePicker style={{ width: 294 }} />)}
            </FormItem> */}
            {/* <FormItem
              {...formItemLayout1}
              label="协议签订日期"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('agreementSignDate', {
                initialValue:agreementSignDate?moment(agreementSignDate.slice(0, 10), dateFormat): '',
                rules: [{
                  required:true
                }]
              })(<DatePicker style={{ width: 294 }} />)}
            </FormItem> */}
            <FormItem
              {...formItemLayout1}
              label="合同备注信息"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('remark', {
                initialValue: remark
              })(<Input.TextArea style={{ width: 294 }} />)}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="合同文件备份"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('contractUrl', {
                initialValue: '',
                // initialValue: contractUrl,
                rules: [{
                  required:true,
                  message: '请上传文件'
                }]
              })(
                <Upload name="xfile" action={uploadUrl} listType="picture">
                  <Button>
                    <Icon type="upload" /> 上传文件
                  </Button>
                  支持扩展名：.doc\.docx\.pdf\.jpg\.png\.jpeg
                </Upload>
              )}
            </FormItem>
          </Form>
        </div>
      </PDrawer>
    );
  }
}

const formItemLayout1 = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 12 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 }
  }
};
