import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Input,
  Button,
  Form,
  DatePicker,
  InputNumber,
  Modal,
  Drawer
} from 'antd';
import moment from 'moment';
import $perModal from '../../../utils/modal/perModal';

// import Drawer from 'react-motion-drawer';
import PSelect from '../../../components/Pro/PSelect';
import './less/devices.less';
import * as api from '../../../services/api';

import PartmentButton from '../../../components/PartmentButton';

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

@connect(state => ({ profile: state.profile }))
@Form.create()
export default class CheckInOutDrawer extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      lostState: 'no',
      open: this.props.visible, //出入库
      comEquipId: 0,
      comEquipList: {
        equipNo: '', //设备编号
        equipName: '', //设备名称
        equipType: '', //设备类型
        totalNum: '', //总库存
        curNum: '' //当前库存
      },
      perId: '', //人员id
      checkedkeys: '',
      getDevInfo: true,
      visibleModal: false //提示框状态
    };
  }
  onChangeRadio = e => {
    this.setState({ lostState: e.target.value });
  };
  componentWillReceiveProps(nextProps) {
    this.setState({ open: nextProps.visible });
    this.setState(
      {
        comEquipId: nextProps.comEquipId
      },
      () => {
        if (this.state.comEquipId !== 0 && this.state.getDevInfo && nextProps.visible) {
          api
            .enterpriseEquipComEquipGetComEquipById({
              comEquipId: nextProps.comEquipId
            })
            .then(data => {
              this.setState({
                comEquipList: data.data,
                getDevInfo: false
              });
            });
        }
      }
    );
  }

  //表单提交
  handleAddDeviceSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // values.perIdStr=values.perIdStr[0];
        // values.perIdStr = this.state.perId;
        values.operaDate = values['operaDate'].format('YYYY-MM-DD HH:mm');
        values.comEquipId = this.state.comEquipId;
        delete values.storage;
        delete values.equipName;
        delete values.equipNo;
        delete values.equipType;
        // delete values.perId;
        Reflect.deleteProperty(values, 'name');
        api.comEquipInOutAddComEquipInOut({ ...values }).then(
          () => {
            this.props.tableUpdate();
            this.setState({
              open: false,
              getDevInfo: true
            });
          },
          err1 => {
            console.log(err1);
          }
        );
      }
    });
  };

  //保证数量小于实际库存
  checkNumber = (rule, value, callback) => {
    const stockType = this.props.form.getFieldValue('inOutStockType');
    const curNum = this.state.comEquipList.curNum;
    const totalNum = this.state.comEquipList.totalNum;
    const outNum = totalNum - curNum;
    if (stockType === undefined) {
      callback('请先选择出入库类型！');
    } else if (stockType === '2' && value > outNum) {
      callback('设备入库数量不能大于实际出库数量！');
    } else if (stockType === '1' && value > curNum) {
      callback('设备出库数量不能大于实际库存数量！');
    } else if (stockType === '4' && value > totalNum) {
      callback('设备损耗数量不能大于库存总数量！');
    } else if (value && !/^[1-9]\d*$/.test(value)) {
      callback('输入格式不正确！');
    } else {
      callback();
    }
  };

  //抽屉视图处理
  changeDrawer = () => {
    this.setState({ open: true });
  };

  handleOperationDate = (value) => {
    if(!value) {
      this.props.form.setFieldsValue({
        operaDate: moment(new Date())
      });
    }
  }

  hideDrawer = () => {
    // this.setState({ open: false, getDevInfo: true});
    const values = this.props.form.getFieldsValue();
    if(values.operaDate){
      const operaValue = values['operaDate'];
      values.operaDate = operaValue.format('YYYY-MM-DD');
    }
    const updateDate = values.inOutStockType || values.perId || values.operaDate || values.remark;
    if(this.state.lostState === 'no'){
      if(updateDate || values.operaNum) {
        this.setState({
          visibleModal: true,
        });
      } else {
        this.handleModalOk();
      }
    } else if(updateDate || values.storageNumber || values.loseNumber || values.loseRemark){
      this.setState({
        visibleModal: true,
      });
    } else {
      this.handleModalOk();
    }
  };

  handleModalOk = () => {
    this.setState({
      open:false,
      getDevInfo: true,
      visibleModal:false
    });
  }

  handleModalCancel = () =>{
    this.setState({
      visibleModal: false
    });
  }

  render() {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 17
        },
        md: {
          span: 17
        }
      }
    };

    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const lostView =
      this.state.lostState === 'no' ? (
        <FormItem {...formItemLayout} label="数量">
          {getFieldDecorator('operaNum', {
            rules: [
              {
                required: true,
                message: '数量不能为空！'
              },
              {
                validator: this.checkNumber
              }
            ]
          })(<InputNumber style={{ width: 294 }} min={1} max={100000} />)}
        </FormItem>
      ) : (
        <div>
          <FormItem {...formItemLayout} label="实际入库数量">
            {getFieldDecorator('storageNumber', {
              rules: [
                {
                  required: false
                }
              ]
            })(<InputNumber style={{ width: 294 }} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="损耗设备数量">
            {getFieldDecorator('loseNumber', {
              rules: [
                {
                  required: false
                }
              ]
            })(<InputNumber />)}
          </FormItem>
          <FormItem {...formItemLayout} label="耗损说明">
            {getFieldDecorator('loseRemark')(
              <TextArea style={{ width: 294 }} rows={4} />
            )}
          </FormItem>
        </div>
      );
    const config = {
      rules: [
        {
          type: 'object',
          required: true,
          message: '请选择日期!'
        }
      ]
    };
    return (
      <div>
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          placement="right"
          visible={this.state.open}
          destroyOnClose
          zIndex={11}
          title="出库入库"
          width={600}
          onChange={open => {
            this.props.onChange(open);
            this.setState({ open });
            if (open === false) {
              const { form } = this.props;
              form.setFieldsValue({
                perId: '',
                inOutStockType: '',
                operaNum: '',
                storageNumber: '',
                loseNumber: '',
                loseRemark: '',
                remark: ''
              });
              if (form.getFieldValue('operaDate')) {
                form.setFieldsValue({ operaDate: null });
              }
            }
          }}
          onClose={() => {
            this.setState({ open: false, getDevInfo: true });
          }}
        >
          <div>
            <div>
              <Form onSubmit={this.handleAddDeviceSubmit}>
                <FormItem {...formItemLayout} label="设备编号">
                  {getFieldDecorator('equipNo', {
                    initialValue: this.state.comEquipList.equipNo
                  })(<Input style={{ width: 294 }} disabled />)}
                </FormItem>
                <FormItem {...formItemLayout} label="设备名称:">
                  {getFieldDecorator('equipName', {
                    initialValue: this.state.comEquipList.equipName
                  })(<Input style={{ width: 294 }} disabled />)}
                </FormItem>
                <FormItem {...formItemLayout} label="设备类型">
                  {getFieldDecorator('equipType', {
                    initialValue: this.state.comEquipList.equipType
                  })(
                    <PSelect
                      style={{ width: 294 }}
                      placeholder="请选择"
                      type="equipType"
                      onChange={this.pSelectChange}
                      disabled
                    />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="出入库类型">
                  {getFieldDecorator('inOutStockType', {
                    rules: [
                      {
                        required: true,
                        message: '请选择出入库类型'
                      }
                    ]
                  })(
                    <PSelect
                      style={{ width: 294 }}
                      type="inOutStockType"
                      onChange={this.pSelectChange}
                      onSelect={() => {
                        this.props.form.setFieldsValue({ operaNum: '' });
                      }}
                    />
                  )}
                </FormItem>
                {/*<FormItem {...formItemLayout} label="是否有设备耗损">*/}
                {/*{getFieldDecorator('loseState')(*/}
                {/*<RadioGroup style={{width:294}} onChange={this.onChangeRadio}>*/}
                {/*<Radio value={'no'}>否</Radio>*/}
                {/*/!*<Radio style={{marginLeft:94}} value={'yes'}>是</Radio>*!/*/}
                {/*</RadioGroup>*/}
                {/*)}*/}
                {/*</FormItem>*/}
                {lostView}
                <FormItem {...formItemLayout} label="实际库存">
                  {getFieldDecorator('storage')(
                    <p>
                      <span style={{ color: 'red' }}>
                        {this.state.comEquipList.curNum}
                      </span>
                      <span style={{ color: '#333' }}>
                        /{this.state.comEquipList.totalNum}
                      </span>
                    </p>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="负责人">
                  {getFieldDecorator('perIdStr', {
                    rules: [
                      {
                        required: true,
                        message: '请选择负责人'
                      }
                    ]
                  })(
                    <Input
                      style={{display: 'none'}}
                      placeholder="请选择"
                    />
                  )}
                  {getFieldDecorator('name', {
                  })(
                    <Input
                      readOnly
                      style={{ width: '292px' }}
                      onClick={() => {
                        const { setFieldsValue, getFieldValue } = this.props.form;
                        $perModal({
                          type: 'radio',
                          value: [{
                            perId: getFieldValue('perIdStr'),
                            name: getFieldValue('name')
                          }],
                          onOk: (values, close) => {
                            
                            const { perId, name } = values[0];
                            setFieldsValue({perIdStr: perId, name});
                            close();
                          }
                        });
                      }}
                      placeholder="请选择"
                    />
                  )}
                </FormItem>

                <FormItem {...formItemLayout} label="操作日期">
                  {getFieldDecorator('operaDate', config)(
                    <DatePicker
                      format="YYYY-MM-DD HH:mm"
                      showTime={{ format: 'HH:mm' }}
                      style={{ width: 294 }}
                      onOk={this.handleOperationDate}
                    />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="备注">
                  {getFieldDecorator('remark', {
                    initialValue: ''
                  })(
                    <TextArea style={{ width: 294 }} maxLength={400} rows={4} />
                  )}
                </FormItem>
              </Form>
            </div>
            <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
                // onClick={() => {
                //   this.setState({ open: false, getDevInfo: true });
                // }}
                onClick={this.hideDrawer}
              >
                取消
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                onClick={this.handleAddDeviceSubmit}
                style={{ marginLeft: 8 }}
              >
                确定
              </Button>
            </div>
          </div>
        </Drawer>
        <Modal
          title="提示"
          visible={this.state.visibleModal}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}>
          <p>当前信息未保存，是否确认返回？</p>
        </Modal>
      </div>
    );
  }
}
