import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Form, Input,Select,Checkbox,Modal,Transfer,Spin ,Table,InputNumber} from 'antd';
import {  extend,  extendRule,  initFilter,  initQueryFilter,  getOnlyPropertyData,  extendInclude,getDataFieldValue} from "../../../utils/common";

import {message} from "antd/lib/index";

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


class SelectInventoryPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      visible:false
    };
  };

  componentDidMount() {

  }

  componentWillReceiveProps(NextProps) {
    // if (NextProps.data.mrpClick ) {
    //   this.props.form.resetFields();
    //   this.loadData();
    //   this.props.dispatch({
    //     type: 'login/save',
    //     payload: {
    //       mrpClick:false
    //     },
    //   });
    // }
  }

  loadData=()=> {
    const {data,formId,login,dispatch}=this.props;
    const {productId,onInventorys,soOrderDetailId,soDetailRecord}=data?data:{};

    if(productId){
      const json = initFilter(this.props.login.OrgId, productId, 'CREATE_TIME', 0);
      json['Parameter1']='true';
      json['Parameter3'] = soOrderDetailId;
      this.props.dispatch({
        type: 'WHSelectInventory/getInventoryUsedByProduct',
        payload: json,
        onComplete: (ret) => {
          if(ret){
            let inventorys=null;
            if(onInventorys)
            {
              inventorys=onInventorys();
            }
            let qty=soDetailRecord.PLAN_QTY-soDetailRecord.DELIVERYED_QTY;
            ret.forEach((n,i)=>{
              if(!qty)return;
              if(!n.UsedQty){
                let q=n.Qty;
                if(qty>q){
                  qty-=q;
                  n.UsedQty=q;
                }
                else{
                  n.UsedQty=qty;
                  qty=0;
                }
              }
            });
            ret.forEach((n,i)=>{
              if(inventorys&&inventorys.length){
                inventorys.forEach((n1,i1)=>{
                  if(n.InventoryId==n1.InventoryId){
                    n.UsedQty=n1.Qty;
                  }
                });
              }
            });
            this.setState({
              data: ret,
            });
          }
        }

      });




    }
    else{
      this.setState({
        data:[]
      });
    }

  };


  handleShowModal = () => {
    this.loadData();
    this.setState({
      visible: true,
    });
  };
  handleCloseModal = () => {
    this.setState({
      visible: false
    });
  };


  handleOk = () => {
    const {form,dispatch,data} = this.props;
    const {onSave}=data?data:{};
    if(onSave){
      let isError=false;
      if(this.state.data){
        this.state.data.forEach((n,i)=>{
          if(n.Qty<n.UsedQty){
            message.error('库位 '+(n.Nav_Location==null?'':n.Nav_Location.NAME)+' ：本次使用数量不能超过库存数');
            isError=true;
          }
        });
      }
      if(isError)return;
      this.handleCloseModal();
      onSave(this.state.data);
    }
  };






  render() {
    const {form, location, dispatch, match,loading} = this.props;
    const {getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue} = form;


    const colCurrQty = (text, record, index) => {
      const onChange = (e) => {
        let value=(e?e:0)
        const tmp=[...this.state.data];
        if(tmp) {
          tmp.map(t => {
            if (t.ID == record.ID) {
              t.UsedQty=value;
            }
          });
        }
        this.setState({
          data:tmp,
        });
      }
      return <InputNumber value={record.UsedQty} min={0} onChange={(e) => onChange(e)} disabled={record.PICK_QTY} />
    };

    const tableColumns=[
      {title: '库位名称', dataIndex: 'Nav_Location.NAME', key: 'Nav_Location.NAME'},
      {title: '库位代码', dataIndex: 'Nav_Location.CODE', key: 'Nav_Location.CODE'},
      {title: '库存数量', dataIndex: 'Qty', key: 'Qty'},
      {title: '本次使用库存数', dataIndex: '', key: '', render: colCurrQty},
    ]

    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14},
    };



    return (
      <div>
        <span onClick={this.handleShowModal}>{this.props.children}</span>
        <Modal visible={this.state.visible} maskClosable={false} onCancel={this.handleCloseModal} footer={false} width={"80%"}>
        <Form>
          <Row>
            <Col span={12}>
              <Form.Item
                label={'产品名称'}
                {...formItemLayout}
              >
                {getFieldDecorator('PRODUCT_NAME', {
                  initialValue: (this.props.Nav_Product==null?'':this.props.Nav_Product.NAME),
                })(<Input disabled={true}/>)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'产品编号'}
                {...formItemLayout}
              >
                {getFieldDecorator('PRODUCT_CODE', {
                  initialValue: (this.props.Nav_Product==null?'':this.props.Nav_Product.CODE),
                })(<Input disabled={true}/>)}
              </Form.Item>
            </Col>

          </Row>

          <Row>
            <Col style={{ textAlign: 'right' }}>
               <Button type={'primary'} onClick={this.handleOk}>确定</Button>
            </Col>
          </Row>
          <Table
            rowKey="ID"
            pagination={false}
            dataSource={this.state.data}
            columns={tableColumns}

          />
        </Form>
        </Modal>
      </div>
    );
  }

}

SelectInventoryPage.propTypes = {
};

export default connect(({ login, loading,  }) => ({ login, loading,  }))(Form.create()(SelectInventoryPage));
