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


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


class MrpPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      btns:[],
      checked:true,
    };
  };

  componentDidMount() {
    this.props.form.resetFields();
    this.loadData();
  }

  componentWillReceiveProps(NextProps) {
    const {data}=this.props;
    let {id}=data?data:{};
    if(!id)
      id='';
    if (NextProps.custom['mrpClick'+id] ) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          ['mrpClick'+id]:false
        },
      });
    }
  }

  loadData=()=> {
    const {data, formId, login, dispatch}=this.props;
    const {ids}=data?data:{};

    if(ids){
      const json = initFilter(this.props.login.OrgId);
      json['Keyword']= ids;
      this.props.dispatch({
        type: 'SOMrp/getMrpData',
        payload: json,
        onComplete: (ret) => {
          if(ret){
            this.setState({
              data: ret,
            });
          }
        }
      });
    }
    else{
      this.setState({
        data:{}
      });
    }
    if(formId){
      const btnJson = initFilter(this.props.login.OrgId,'','NUM',0);
      extendRule(btnJson, 'PAGE_CUSTOM_FORM_ID', 1, formId);
      this.props.dispatch({
        type: 'FMRoleEdit/getBtnList',
        payload: btnJson,
        onComplete: (ret) => {
          if(ret){
            this.setState({
              btns: ret,
            });
          }
        }
      });
    }
  };


  getBtns=()=>{
    if(this.state.btns){
      return this.state.btns.map(item=>{
        if (item.BTN_TYPE == 1) {
          return <Button type={item.CSS} icon={item.ICON} key={item.ID} onClick={() => this.handleOk()}>{item.LABEL}</Button>;
        }
      });
    }
  };

  handleOk = () => {
    const {form,dispatch,data} = this.props;
    const {getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue} = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      let updateData={...this.state.data};
      dispatch({
        type: 'SOMrp/saveMrpData',
        payload: updateData,
        onComplete: (ret) => {
          if(ret) {
            if(data.close){
              data.close();
            }
            message.success('执行成功');
          }
        }
      });
    })
  };


  refreshData=(type=0)=> {
    const data = {...this.state.data};
    const product=data.Nav_Product;
    if(product==null)return;

    if(data.InventoryQty<0)
      data.InventoryQty=0;
    let remainQty=data.OrderQty-data.InventoryQty;
    if(remainQty<0)
      remainQty=0;
    if(type==0||type==3) {
      if (product.PRODUCT_SOURCE_TYPE == 0) {
        remainQty = remainQty * (product.LOSS_RATIO + 1);
        if (remainQty > 0) {
          remainQty = Math.ceil(remainQty);
        }
        remainQty = remainQty - data.PurchaseQty;
        if (remainQty < 0)
          remainQty = 0
        data.WorkQty = remainQty;
      }
      else if (product.PRODUCT_SOURCE_TYPE == 1) {
        remainQty = remainQty - data.WorkQty;
        if (remainQty < 0)
          remainQty = 0;
        data.PurchaseQty = remainQty;
      }
    }
     if(type==1) {//本次自制数量
      remainQty = remainQty - data.WorkQty;
      if (remainQty < 0)
        data.PurchaseQty = 0;
    }
     if(type==2) {//本次采购数量
      remainQty = remainQty - data.PurchaseQty;
      if (remainQty < 0)
        data.WorkQty = 0;
    }
    data.SumQty=data.PurchaseQty+data.WorkQty;
    this.refreshBomData(data.Nav_BomDetails,null,data.WorkQty);

    this.setState({
      data:data,
    });
  };


  refreshBomData=(data,parentId,qty)=>{
    if(qty<0)
      qty=0;
    if(data){
      data.map(item=>{
        if(item.ParentId==parentId){
          let tmp=item.CurrInventoryQty-item.Nav_Product.INVENTORY_MIN_LIMIT_NUMBER;
          item.PlanQty= Math.ceil(qty*item.Nav_BomDetail.PERCENTAGE*(1+item.Nav_BomDetail.CONSUME_RATE));
          item.ApplyQty=item.PlanQty-tmp;
          if(item.ApplyQty<0)
            item.ApplyQty=0;
          this.refreshBomData(data,item.ID,item.ApplyQty);
        };
      });
    };
  };




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


    const colApplyQty = (text, record, index) => {
      const onBlur=(e)=>{
        const data={...this.state.data};
        this.refreshBomData(data.Nav_BomDetails,record.ID,e.target.value);
        this.setState({
          data:data,
        });
      };
      const onChange = (e) => {
        const tmp={...this.state.data};
        if(tmp.Nav_BomDetails) {
          tmp.Nav_BomDetails.map(t => {
            if (t.ID == record.ID) {
              t.ApplyQty=e;
            }
          });
        }
        this.setState({
          data:tmp,
        });
      }
      return <InputNumber value={record.ApplyQty} onBlur={onBlur} min={0} onChange={(e) => onChange(e)}/>
    };

    const tableColumns=[
      {title: '名称', dataIndex: 'Nav_Product.NAME', key: 'Nav_Product.NAME'},
      {title: '编号', dataIndex: 'Nav_Product.CODE', key: 'Nav_Product.CODE'},
      {title: '规格', dataIndex: 'Nav_Product.SPEC', key: 'Nav_Product.SPEC'},
      {title: '计划数量', dataIndex: 'PlanQty', key: 'PlanQty'},
      {title: '当前可用库存', dataIndex: 'CurrInventoryQty', key: 'CurrInventoryQty'},
      {title: '最低库存', dataIndex: 'Nav_Product.INVENTORY_MIN_LIMIT_NUMBER', key: 'Nav_Product.INVENTORY_MIN_LIMIT_NUMBER'},
      {title: '建议申请数量', dataIndex: '', key: '', render: colApplyQty},
    ]

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

    const onBlur=(type)=> {
      this.refreshData(type);
    };

    const onChange=(field,value,type)=>{
      const data={...this.state.data};
      value =(value?value:0);
      if(type==3){
        if(data.CurrInventoryQty<value) {
          message.info('不允许超过最大库存');
          value = data.CurrInventoryQty;
        }
      }
      data[field]=value;
      this.setState({
        data:data,
      });
    }


    return (
      <div>
          <Form>
            <div>
              <h2>MRP</h2>
            </div>
            <Row>
              <Col span={12}>
                <Form.Item
                  label={'产品名称'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('PRODUCT_NAME', {
                    initialValue: (this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.NAME),
                  })(<Input disabled={true}/>)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={'产品编号'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('PRODUCT_CODE', {
                    initialValue: (this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.CODE),
                  })(<Input disabled={true}/>)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={'订单数量'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('OrderQty', {
                    initialValue: this.state.data.OrderQty,
                  })(<Input  disabled={true}/>)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={'产品损耗率'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('ProductLossRaitoStr', {
                    initialValue: this.state.data.ProductLossRaitoStr,
                  })(<Input  disabled={true}/>)}
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  label={'当前库存数量'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('CurrInventoryQty', {
                    initialValue: this.state.data.CurrInventoryQty,
                  })(<Input  disabled={true}/>)}
                </Form.Item>
              </Col>



              <Col span={12}>
                <Form.Item
                  label={'本次使用库存数量'}
                  {...formItemLayout}
                >
                  <InputNumber value={this.state.data.InventoryQty}  min={0} onChange={(e)=>{onChange('InventoryQty',e,3);}}   onBlur={(e)=>{onBlur(3);}} />
                </Form.Item>
              </Col>


              <Col span={12}>
                <Form.Item
                  label={'本次自制数量'}
                  {...formItemLayout}
                >
                  <InputNumber value={this.state.data.WorkQty}  min={0} onChange={(e)=>{onChange('WorkQty',e,1);}} onBlur={(e)=>{ onBlur(1);}} />
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  label={'本次采购数量'}
                  {...formItemLayout}
                >
                  <InputNumber value={this.state.data.PurchaseQty}  min={0} onChange={(e)=>{onChange('PurchaseQty',e,2);}}   onBlur={(e)=>{onBlur(2);}} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={'总需求量'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('SumQty', {
                    initialValue: this.state.data.SumQty,
                  })(<Input  disabled={true}/>)}
                </Form.Item>
              </Col>
            </Row>

            <Row>
              <Col style={{ textAlign: 'right' }}>
                {
                  this.getBtns()
                }
              </Col>
            </Row>
            <h3>BOM 明细</h3>
            <Table
              rowKey="ID"
              pagination={false}
              dataSource={this.state.data.Nav_BomDetails}
              columns={tableColumns}
            />


          </Form>
      </div>
    );
  }

}

MrpPage.propTypes = {
};

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