import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Form, Input, Icon, Spin, Select, Table, InputNumber, DatePicker, message, Popconfirm} from 'antd';
import {
  extend,
  extendRule,
  initFilter,
  initQueryFilter,
  getOnlyPropertyData,
  extendInclude,
  getDataFieldValue,
  setDataFieldValue,
  empty,
  guid
} from "../../../utils/common";
import moment from 'moment';

import FormModal from '../../FormModal';

import  DropDownPagination from '../../common/DropDownPaginationEx';

const Option = Select.Option;

//投料方案
class FeedProposalPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      btns:[],
      checked:true,
      isEnoughWorkQty:true,
    };
  };

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

  componentWillReceiveProps(NextProps) {
    const {data}=this.props;
    let {id}=data?data:{};
    if(!id)
      id='';
    if (NextProps.custom['emFeedProposalClick'+id]) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          ['emFeedProposalClick'+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;
      json['Parameter1']='2';
      this.props.dispatch({
        type: 'EMFeedProposal/getMrpData',
        payload: json,
        onComplete: (ret) => {
          if(ret){
            let remain=  ret.OrderQty;
            if(remain<0)
              remain=0;
            let workQty= Math.ceil(remain*(1+(ret.Nav_Product==null?0:ret.Nav_Product.LOSS_RATIO)));
            if(ret.Nav_Product&&ret.Nav_Product.SPLIT_QTY){
              workQty= Math.ceil(workQty/ret.Nav_Product.SPLIT_QTY)*ret.Nav_Product.SPLIT_QTY;
            }
            ret.WorkQty=0;
            ret.MinWorkQty=workQty;
            ret.InventoryQty=0;
            ret.PdtDueTime=null;
            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: 'EMFeedProposal/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) {
          if(this.state.isEnoughWorkQty) {
            return <Button type={item.CSS} icon={item.ICON} key={item.ID}
                           onClick={() => this.handleOk()}>{item.LABEL}</Button>;
          }
          else{
            return <Popconfirm title="当前下单数量小于最低下单数,是否继续?" key={item.ID} onConfirm={() => this.handleOk()} >
              <Button type={item.CSS} icon={item.ICON} >{item.LABEL}</Button>
            </Popconfirm>
          }
        }
      });
    }
  };

  checkIsEnoughWorkQty=()=>{
    this.setState({
      isEnoughWorkQty:this.state.data.WorkQty>=this.state.data.MinWorkQty
    });
  }

  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};
      if(empty(getDataFieldValue(updateData,'WorkQty'))){
        message.error('请输入下单数量');
        return;
      }
      if(this.state.data.Nav_Product&&this.state.data.Nav_Product.SPLIT_QTY){
        if(updateData.WorkQty%this.state.data.Nav_Product.SPLIT_QTY>0)
        {
          message.error('下单数量必须是交货方式的整数倍');
          return;
        }
      }

      if(updateData.WorkQty<updateData.MinWorkQty){
        message.warning('当前下单数量小于最低下单数')
      }
      if(empty(getDataFieldValue(updateData,'PdtDueTime'))){
        message.error('请输入生产交期');
        return;
      }
      let isError=false;
      if(updateData.Nav_EmProposals){
        updateData.Nav_EmProposals.forEach((n,i)=>{
          if(n.ProposalType==0&&!n.ProductId)
          {
            message.error('请选择产品');
            isError=true;
            return;
          }
          if(n.PurchaseQty&&empty(getDataFieldValue(updateData,'PurchasePlanDeliveryTime'))){
            message.error('请输入期望采购交期');
            isError=true;
            return;
          }
        });
      }
      if(isError)return;

      dispatch({
        type: 'EMFeedProposal/saveMrpData',
        payload: updateData,
        onComplete: (ret) => {
          if(ret) {
            if(data.close){
              data.close();
            }
            message.success('执行成功');
          }
        }
      });
    })
  };


  refreshWorkQty=()=>{
    const data={...this.state.data};
    if(data.Nav_EmProposals){
      let workQty=0;
      data.Nav_EmProposals.forEach((n,i)=>{
        if(n.OutputPCSQty){
          workQty+=n.OutputPCSQty;
        }
      });
      data.WorkQty=workQty;
    }
    this.setState({
      data,
    },()=>{
      this.checkIsEnoughWorkQty();
    })
  };


  handleAddEmPoposal=()=>{
    const data={...this.state.data};
    const tmp={
      ID:guid(),
      isMenuAdd:true,
      ProposalType:0,
    };
    data.Nav_EmProposals.push(tmp);
    this.setState({
      data
    });
  };

  handleDeleteEmPoposal=(id)=>{
    const data={...this.state.data};
    if(data.Nav_EmProposals){
      const tmp=[];
      data.Nav_EmProposals.forEach((n,i)=>{
        if(n.ID!=id){
          tmp.push(n);
        }
      });
      data.Nav_EmProposals=tmp;
    }
    this.setState({
      data
    });
  };

  saveRecord=(record)=>{
    const data={...this.state.data};
    if(data.Nav_EmProposals){
      const tmp=[];
      data.Nav_EmProposals.forEach((n,i)=>{
        if(n.ID!=record.ID){
          tmp.push(n);
        }
        else{
          tmp.push(record);
        }
      });
      data.Nav_EmProposals=tmp;
    }
    this.setState({
      data
    });
  }


  render() {
    const {form, location, dispatch, match,loading} = this.props;
    const {getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue} = form;
    const enums=this.props.app.enums;
    const doChange=(record, field,value)=>{
      const tmp={...this.state.data};
      if(tmp.Nav_EmProposals) {
        tmp.Nav_EmProposals.map(t => {
          if (t.ID == record.ID) {
            t[field]=value;
            if(field=='FeedQty'){
              const pcs=getDataFieldValue(t,'Nav_ProposalDetail.PCS');
              t.OutputPCSQty= pcs*value;
              t.FeedAreaQty=t.Length*t.Width*value/1000000;
            }
          }
        });
      }
      this.setState({
        data:tmp,
      },()=>{
        if(field=='FeedQty'){
          this.refreshWorkQty();
        }
      });
    };

    const renderProposal=(field,record)=>{
      if(field=='Delete'){
        if(record.isMenuAdd){
          return <Button type={'danger'}   onClick={(e)=>this.handleDeleteEmPoposal(record.ID)}  icon={'delete'}>删除</Button>
        }
        return null;
      }
      if(record.ProposalType==0){
        if(field=='Description'){
          const onSelectValue = ({record:selectRecord}) => {
            const data = {...this.state.data};
            if (data.Nav_EmProposals) {
              data.Nav_EmProposals.map(t => {
                if (t.ID == record.ID) {
                  setDataFieldValue(t, 'Length', getDataFieldValue(selectRecord, 'LENGTH'));
                  setDataFieldValue(t, 'Width', getDataFieldValue(selectRecord, 'WIDTH'));
                  setDataFieldValue(t, 'ProductId', getDataFieldValue(selectRecord, 'ID'));
                  setDataFieldValue(t, 'Description', getDataFieldValue(selectRecord, 'NAME'));;
                }
                else{
                  setDataFieldValue(t,'Nav_ProposalDetail.SPLIT_QTY',0);
                }
              })
            };
            this.setState({
              data: data,
            });
          }
          return <DropDownPagination inputDataApi={'FM/Product/OrderPaged'} fieldName={'Description'} inpuNavField={''}
                                     data={record} onSelect={onSelectValue} disabled={this.props.data.isShow} onFilter={({params}) => {
            extendRule(params, 'PRODUCT_TYPE', 1, 2);
          }}
          />;
        }
        else if(field=='PurchaseQty'){
          return <InputNumber value={record.PurchaseQty} min={0} onChange={(e)=>doChange(record,field,(e? e:0))}/>;
        }
        else if(field=='ShowInventory'){
          record.PRODUCT_ID=record.ProductId;
          const editFormData= {
            pageCode:'FeedProposalPage',
            record: record,
            onSave: (record)=>{record.CurrInventoryQty=record.QTY; this.saveRecord(record);},
            isShow:false,
            isPermit:false,
            stateData:this.state.data.Nav_EmProposals,
          }
          return<>
            <InputNumber value={record.QTY}  disabled={true} style={{ width: '80%' }}/>
            <FormModal
            formCode={'WH022'}
            data={editFormData}>
            <Icon type="edit" style={{ marginLeft: 8, fontSize: 20 }} />
          </FormModal></>
        }

        if(field=='Nav_ProposalDetail.SPLIT_QTY'||field=='Nav_ProposalDetail.SET'||field=='Nav_ProposalDetail.SPLIT_QTY'||field=='FeedQty'||field=='Nav_ProposalDetail.PCS'||
          field=='OutputPCSQty'){
          return;
        }
        return getDataFieldValue(record,field);
      }

      if(field=='FeedQty'){
        return <InputNumber value={record.FeedQty} min={0} onChange={(e)=>doChange(record,field,(e? e:0))}/>;
      }
      else if(field=='CurrInventoryQty'||field=='Nav_Product.INVENTORY_MIN_LIMIT_NUMBER'||field=='PurchaseQty'||field=='ShowInventory')
        return;
      return getDataFieldValue(record,field);
    }

    const tableColumns=[
      {title: '', dataIndex: '', key: '',width:100,  render: (text, record, index)=>{return renderProposal('Description',record)}},
      {title: '长度', dataIndex: '', key: '', render: (text, record, index)=>{return renderProposal('Length',record)}},
      {title: '宽度', dataIndex: '', key: '', render: (text, record, index)=>{return renderProposal('Width',record)}},
      {title: 'PCS/拼版', dataIndex: '', key: '', render: (text, record, index)=>{return renderProposal('Nav_ProposalDetail.PCS',record)}},
      {title: 'SET/拼版', dataIndex: '', key: '', render: (text, record, index)=>{return renderProposal('Nav_ProposalDetail.SET',record)}},
      {title: '可切割数', dataIndex: '', key: '', render: (text, record, index)=>{return renderProposal('Nav_ProposalDetail.SPLIT_QTY',record)}},
      {title: '投料数量', dataIndex: '', key: '', render: (text, record, index)=>{return renderProposal('FeedQty',record)}},
      {title: '投料面积', dataIndex: '', key: '', render: (text, record, index)=>{return renderProposal('FeedAreaQty',record)}},
      {title: '产出PCS', dataIndex: '', key: '', render: (text, record, index)=>{return renderProposal('OutputPCSQty',record)}},
      {title: '', dataIndex: '', key: '', render: (text, record, index)=>{return renderProposal('Delete',record)}},
    ]

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

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

    };

    const onChange=(field,value,type)=>{
      const data={...this.state.data};

      if(type==3){
        if(data.CurrInventoryQty<value) {
          message.info('不允许超过最大库存');
          value = data.CurrInventoryQty;
        }
        let remain = data.OrderQty - (value?value:0);
        if (remain < 0)
          remain = 0;
        let workQty = Math.ceil(remain * (1 + (data.Nav_Product == null ? 0 : data.Nav_Product.LOSS_RATIO)));
        if (data.Nav_Product && data.Nav_Product.SPLIT_QTY) {
          workQty = Math.ceil(workQty / data.Nav_Product.SPLIT_QTY) * data.Nav_Product.SPLIT_QTY;
        }
        data.MinWorkQty = workQty;
      }
      data[field]=value;
      this.setState({
        data:data,
      },()=>{
        if(type==3) {
          this.checkIsEnoughWorkQty();
        }
      });
    }

    const selectEmProposal=({record})=>{
      const {dispatch} = this.props;
      if(record) {
        const json = initFilter(this.props.login.OrgId, record.ID);
        dispatch({
          type: 'EMFeedProposal/getMrpEmProposals',
          payload: json,
          onComplete: (ret) => {
            const data = {...this.state.data};
            if (ret) {
              data.EmProposalId=record.ID;
              data.Nav_EmProposals = ret.Nav_EmProposals;
              data.Nav_EmProposal=ret.Nav_EmProposal;
            }
            else {
              data.EmProposalId=null;
              data.Nav_EmProposals = [];
              data.Nav_EmProposal={};
            }

            this.setState({
              data
            });
          }
        });
      }
      else{
        const data = {...this.state.data};
        data.EmProposalId=null;
        data.Nav_EmProposals = [];
        data.Nav_EmProposal={};
        this.setState({
          data
        });
      }
    }



    return (
      <Spin spinning={loading.global}>
        <Form>
          <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('PRODUCT_SPLIT_QTY', {
                  initialValue: (this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.SPLIT_QTY),
                })(<Input disabled={true}/>)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'单PCS尺寸'}
                {...formItemLayout}
              >
                {getFieldDecorator('PRODUCT_PCS_SIZE', {
                  initialValue: (this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.PCS_SIZE),
                })(<Input disabled={true}/>)}
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label={'拼版尺寸'}
                {...formItemLayout}
              >
                {getFieldDecorator('PRODUCT_SPLIT_SIZE', {
                  initialValue: (this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.SPLIT_SIZE),
                })(<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('Nav_Mould.NAME', {
                  initialValue: (this.state.data.Nav_Product==null||this.state.data.Nav_Product.Nav_Mould==null?'':this.state.data.Nav_Product.Nav_Mould.NAME),
                })(<Input disabled={true}/>)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'板厚'}
                {...formItemLayout}
              >
                {getFieldDecorator('THICKNESS', {
                  initialValue: (this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.THICKNESS),
                })(<Input disabled={true}/>)}
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label={'铜箔厚度'}
                {...formItemLayout}
              >
                {getFieldDecorator('METAL_THICKNESS', {
                  initialValue: (this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.METAL_THICKNESS),
                })(<Input disabled={true}/>)}
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label={'阻焊油墨'}
                {...formItemLayout}
              >
                {getFieldDecorator('ZH_PRINTING_INK', {
                  initialValue: (this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.ZH_PRINTING_INK),
                })(<Input disabled={true}/>)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'文字油墨'}
                {...formItemLayout}
              >
                {getFieldDecorator('PRINTING_INK', {
                  initialValue: (this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.PRINTING_INK),
                })(<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}
              >
                <Input value={this.state.data.MinWorkQty} disabled={true} />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label={<label><span style={{color:'red'}}>*</span>下单数量</label> }
                {...formItemLayout}
              >
                <InputNumber value={this.state.data.WorkQty}  disabled={true} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'外部生产订单交期'}
                {...formItemLayout}
              >
                {getFieldDecorator('MinPlanDeliveryTime', {
                  initialValue: (this.state.data.MinPlanDeliveryTime?this.state.data.MinPlanDeliveryTime.toString().substring(0,10):''),
                })(<Input  disabled={true}/>)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={<label><span style={{color:'red'}}>*</span>生产交期</label> }
                {...formItemLayout}
              >
                <DatePicker disabled={this.props.data.isShow} value={this.state.data.PdtDueTime?moment(this.state.data.PdtDueTime):null}
                            format={"YYYY-MM-DD"}  onChange={(value,dateString)=>{onChange('PdtDueTime',dateString,0)}} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'紧急程度'}
                {...formItemLayout}
              >
                <Select  value={this.state.data.EmergencyDegreeType} onChange={(e)=>{onChange('EmergencyDegreeType',e);}}>
                  {
                    enums&&enums.WOPdtOrderEmergencyDegreeTypeEnum&&enums.WOPdtOrderEmergencyDegreeTypeEnum.options?enums.WOPdtOrderEmergencyDegreeTypeEnum.options.map(t=>{
                      return  <Option value={t.value}>{t.label}</Option>
                    }):null
                  }
                </Select>
              </Form.Item>
            </Col>

          </Row>

          <Row style={{marginTop:'20px'}} >
            <Col style={{ textAlign: 'right' }}>
              {
                this.getBtns()
              }
            </Col>
          </Row>

          <Row style={{marginTop:'20px'}} >
            <Col span={12}>
              <Form.Item
                label={<label><span style={{color:'red'}}>*</span>工程方案</label>}
                {...formItemLayout}
              >
                  <DropDownPagination inputDataApi={'EM/Proposal/OrderPaged'} fieldName={'Nav_EmProposal.NAME'} inpuNavField={''}
                                      data={this.state.data} onSelect={selectEmProposal} disabled={this.props.data.isShow} onFilter={({params}) => {
                    params['Sort']='CREATE_TIME';
                    params['Order']=1;
                    extendRule(params, 'ENABLE_STATUS', 1, 0);
                    extendRule(params,'PRODUCT_ID',1,(this.state.data.Nav_Product?this.state.data.Nav_Product.ID:null));
                  }}
                  />
              </Form.Item>
            </Col>
          </Row>
          <Row style={{marginTop:'20px'}}>
            <Table
              rowKey="ID"
              pagination={false}
              dataSource={this.state.data.Nav_EmProposals}
              columns={tableColumns}
            />
          </Row>


        </Form>
      </Spin>
    );
  }

}

FeedProposalPage.propTypes = {
};

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