import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Form, Input,Select,Table,InputNumber} from 'antd';
import {   extendRule,  initFilter,   extendInclude, guid, getDataFieldValue,} from "../../../utils/common";
import EditBaseComponent from '../../../baseComponents/EditBaseComponent';

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


class ShowInventoryPage extends EditBaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      inventoryData: [],
    };
  };

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

  componentWillReceiveProps(NextProps) {
    let reload=NextProps.editPage['WH022_reload'];
    if ( reload) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'editPage/save',
        payload: {
          ['WH022_reload']:false,
        },
      });

    }
  }

  loadData=()=> {
    const columns=[  
      {controlType:1,field:'LOCATION',label:'库位'},  
      {controlType:7,field:'LENGTH_LOWER',label:'长度从'},  
      {controlType:7,field:'LENGTH_UPPER',label:'长度至'},  
      {controlType:7,field:'WIDTH_LOWER',label:'宽度从'},  
      {controlType:7,field:'WIDTH_UPPER',label:'宽度至'},  
    ]
    this.setEditConfig({
      editConfig: {columns: columns,id:guid(),}
    });
    const {data}=this.props;
    const {record,pageCode,getFieldValue,thisRef}=data?data:{};
    if(record.PRODUCT_ID) {
      const json = initFilter(this.props.login.OrgId, record.PRODUCT_ID, 'CREATE_TIME', 0);
      json['Parameter1']='true';
      if(getFieldValue&&(pageCode=='WH019_Detail'||pageCode=='PdtOrderBom')) {
        json['Parameter2'] = getFieldValue('PDT_ID',thisRef);
      }
      let warehouseId='';
      if(pageCode=='WH011_Detail'){
        warehouseId= getFieldValue('WAREHOUSE_ID',thisRef);
        if(!warehouseId){
          this.setState({
            inventoryData:[]
          });
          message.error('请先选择仓库');
          return;
        }
      }
      if(pageCode=='WH028_Detail'){
        warehouseId= getFieldValue('ALLOCATE_WAREHOUSE_ID',thisRef);
        if(!warehouseId){
          this.setState({
            inventoryData:[]
          });
          message.error('请先调出仓库');
          return;
        }
      }
      this.props.dispatch({
        type: 'WHShowInventory/getInventoryUsedByProduct',
        payload: json,
        onComplete: (ret) => {
          if (ret) {
            const tmp=[];
            ret.forEach((n,i)=>{
              if(n.Nav_Location&&warehouseId&&n.Nav_Location.WAREHOUSE_ID!=warehouseId) {
                return;
              }
              tmp.push(n);
            });

            const data=[];
            let inventorys = record.Nav_Inventorys;
            tmp.forEach((n, i) => {
              if (inventorys && inventorys.length) {
                inventorys.forEach((n1, i1) => {
                  if (n.InventoryId == n1.INVENTORY_ID||n.InventoryId == n1.EXT_INVENTORY_ID) {
                    n.UsedQty = n1.QTY;
                  }
                });
              }
              if(n.Qty||n.UsedQty){
                data.push(n);
              }
            });
            this.setState({
              inventoryData: data,
            });
          }
        }
      });
    }
    else{
      message.error('请选择物料');
      this.setState({
        inventoryData:[]
      });
    }

  };



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

      if(isError)return;
      if(record){
        const inventorys=[];
        let qty=0;
        stateData.forEach((n,i)=>{
          let isGet=false;
          if(record.Nav_Inventorys&&record.Nav_Inventorys.length){
            record.Nav_Inventorys.forEach((n1,i1)=>{
              if(n.InventoryId == n1.INVENTORY_ID||n.InventoryId == n1.EXT_INVENTORY_ID){
                isGet=true;
                if(n.UsedQty){
                  n1.QTY=n.UsedQty;
                  qty+=n1.QTY;
                  inventorys.push(n1);
                }
                else{
                  if(n1.CREATE_TIME){
                    n1.IS_DELETED=true;
                    inventorys.push(n1);
                  }
                }
              }
            });

          }
          if(!isGet&&n.UsedQty){
            inventorys.push({
              INVENTORY_TYPE:n.InventoryType,
              INVENTORY_ID:((pageCode!='WH011_Detail'&&pageCode!='WH019_Detail')||n.InventoryType==0)?n.InventoryId:null,
              EXT_INVENTORY_ID:(pageCode=='WH011_Detail'||pageCode =='WH019_Detail')&&n.InventoryType==1?n.InventoryId:null,
              QTY:n.UsedQty,
              ORG_ID:this.props.login.OrgId,
              PRODUCT_ID:n.ProductId,
              LOCATION_ID:n.LocationId,
              LENGTH:n.Length,
              WIDTH:n.Width,
              THICKNESS_QTY:n.ThicknessQty,
              STYLE_NO:n.StyleNo,
              COPPER_THICKNESS_QTY:n.CopperThicknessQty,
              BATCH_NUMBER:n.BatchNumber,
            });
            qty+=n.UsedQty;
          }
        });
        if(record.Nav_Inventorys){
          record.Nav_Inventorys.forEach((n,i)=>{
            let isGet=false;
            stateData.forEach((n1,i1)=>{
                if(n.InventoryId == n1.INVENTORY_ID||n.InventoryId == n1.EXT_INVENTORY_ID){
                  isGet=true;
                }
            });
            if(!isGet&&n.CREATE_TIME){
              n.IS_DELETED=true;
              inventorys.push(n);
            }
          });
        }
        record.Nav_Inventorys=inventorys;
        if(pageCode==='PdtOrderBom'){
          record.INVENTORY_QTY=qty;
        }
        else{
          record.QTY=qty;
        }
        onSave(record);
      }

      if(close) {
        close();
      }
    }
  };

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

    const tableColumns=[
      {title: '仓库名称', dataIndex: 'Nav_Location.Nav_Warehouse.NAME', key: 'Nav_Location.Nav_Warehouse.NAME'},
      {title: '仓库代码', dataIndex: 'Nav_Location.Nav_Warehouse.CODE', key: 'Nav_Location.Nav_Warehouse.CODE'},
      {title: '库位名称', dataIndex: 'Nav_Location.NAME', key: 'Nav_Location.NAME'},
      {title: '库位代码', dataIndex: 'Nav_Location.CODE', key: 'Nav_Location.CODE'},
      {title: '批次号', dataIndex: 'BatchNumber', key: 'BatchNumber'},
      {title: '长度', dataIndex: 'Length', key: 'Length'},
      {title: '宽度', dataIndex: 'Width', key: 'Width'},
      {title: '板厚', dataIndex: 'ThicknessQty', key: 'ThicknessQty'},
      {title: '铜箔厚度', dataIndex: 'CopperThicknessQty', key: 'CopperThicknessQty'},
      {title: '库存数量', dataIndex: 'Qty', key: 'Qty'},
      {title: '本次使用库存数', dataIndex: '', key: '', render: colCurrQty},
    ];
    let inventoryData=this.state.inventoryData;
    const stateData=this.state.data?this.state.data:{}; 
    if(stateData.BATCH_NUMBER&&inventoryData&&inventoryData.length){
      inventoryData=inventoryData.filter(t=>{ 
        if(t.BatchNumber&&t.BatchNumber.indexOf(stateData.BATCH_NUMBER)>-1){
          return true;
        }
        return false;
      })
    } 
    if(stateData.WAREHOSE&&inventoryData&&inventoryData.length){
      inventoryData=inventoryData.filter(t=>{
        const name= getDataFieldValue(t,'Nav_Location.Nav_Warehouse.NAME');
        const code=getDataFieldValue(t,'Nav_Location.Nav_Warehouse.CODE');
        if(name&&name.indexOf(stateData.WAREHOSE)>-1||code&&code.indexOf(stateData.WAREHOSE)>-1){
          return true;
        }
        return false;
      })
    }
    if(stateData.LOCATION&&inventoryData&&inventoryData.length){
      inventoryData=inventoryData.filter(t=>{
        const name= getDataFieldValue(t,'Nav_Location.NAME');
        const code=getDataFieldValue(t,'Nav_Location.CODE');
        if(name&&name.indexOf(stateData.LOCATION)>-1||code&&code.indexOf(stateData.LOCATION)>-1){
          return true;
        }
        return false;
      })
    }
    if(stateData.LENGTH_LOWER&&inventoryData&&inventoryData.length){
      inventoryData=inventoryData.filter(t=>t.Length>=stateData.LENGTH_LOWER);
    }
    if(stateData.LENGTH_UPPER&&inventoryData&&inventoryData.length){
      inventoryData=inventoryData.filter(t=>t.Length<=stateData.LENGTH_UPPER);
    }

    if(stateData.WIDTH_LOWER&&inventoryData&&inventoryData.length){
      inventoryData=inventoryData.filter(t=>t.Width>=stateData.WIDTH_LOWER);
    }
    if(stateData.WIDTH_UPPER&&inventoryData&&inventoryData.length){
      inventoryData=inventoryData.filter(t=>t.Width<=stateData.WIDTH_UPPER);
    }

    const headColumnConfig=this.getEditConfig();
    const columns= headColumnConfig?headColumnConfig.columns:[]; 
    return (
      <div>
        <Form>
          <Row>
            搜索
          </Row>
          <Row style={{marginTop:'20px'}}>
            {this.createControls(columns,this.state.data)}
          </Row>
          <Row style={{marginTop:'20px'}}>
          <Table
            rowKey="ID"
            pagination={false}
            dataSource={inventoryData}
            columns={tableColumns}
          />
          </Row>

          <Row style={{marginTop:'20px'}}>
            <Col style={{ textAlign: 'right' }}>
              <Button type={'primary'} icon={'save'} onClick={this.handleOk}>确定</Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  }

}

ShowInventoryPage.propTypes = {
};

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