import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Form, Input, Spin, Select, Icon, Table, InputNumber, DatePicker, message} 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 PdtOrderBomPage 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['pdtOrderBomClick'+id]) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          ['pdtOrderBomClick'+id]:false
        },
      });
    }
  }

  loadData=()=> {
    const {data,formId}=this.props;
    const {id}=data?data:{};
    if(id){
      const json = initFilter(this.props.login.OrgId);
      extendRule(json,'ID',1,id);
      extendInclude(json,'Nav_Product');
      extendInclude(json,'Nav_PdtBOMs.Nav_Inventorys');
      extendInclude(json,'Nav_PdtBOMs.Nav_Product');
      extendInclude(json,'Nav_PdtBOMs.Nav_PdtProcessDetail');
      this.props.dispatch({
        type: 'WOPdtOrder/getPdtOrderById',
        payload: json,
        onComplete: (ret) => {
          if(ret){
            if(ret.Nav_PdtBOMs){
              ret.Nav_PdtBOMs.sort((x, y) => (x.PRE_TIME&&y.PRE_TIME&& moment(x.PRE_TIME).isBefore(y.PRE_TIME) ? 1 : -1));
            }
            this.setState({
              data: ret,
            });
          }
        }
      });
    }

    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) {
          return <Button type={item.CSS} icon={item.ICON} key={item.ID} disabled={this.props.data.isShow}
                         onClick={() => this.handleOk()}>{item.LABEL}</Button>;
        }
      });
    }
  };

  handleOk = () => {
    const {form,dispatch,data} = this.props;
    const {validateFieldsAndScroll} = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      let updateData={...this.state.data};
      let isError=false;
      if(updateData.Nav_PdtBOMs){
        const tmpBoms=[];
        updateData.Nav_PdtBOMs.forEach((n,i)=>{
          if(!n.PRODUCT_ID){
            isError=true;
            message.error('请选择材料');
            return;
          }
          if(!n.PRE_TIME){
            isError=true;
            message.error('请选择预投日期');
            return;
          }
          if(!n.QTY){
            isError=true;
            message.error('请选择需求数量');
            return;
          }
          const tmp= getOnlyPropertyData(n);
          if(n.Nav_Inventorys){
            tmp.Nav_Inventorys=[];
            n.Nav_Inventorys.forEach((n1,i1)=>{
              tmp.Nav_Inventorys.push(getOnlyPropertyData(n1));
            });
          }
          tmpBoms.push(tmp);
        });
        updateData.Nav_PdtBOMs=tmpBoms;
      }
      if(isError)return;
      dispatch({
        type: 'WOPdtOrder/savePdtOrderBom',
        payload: updateData,
        onComplete: (ret) => {
          if(ret) {
            if(data.close){
              data.close();
            }
            message.success('执行成功');
          }
        }
      });
    })
  };




  handleAddEmPoposal=()=>{
    const data={...this.state.data};
    const tmp={
      ID:guid(),
      ORG_ID:this.props.login.OrgId,
    };
    data.Nav_PdtBOMs.push(tmp);
    this.setState({
      data
    });
  };

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

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


  render() {
    const {loading} = this.props;
    const enums=this.props.app.enums;
    const doChange=(record, field,value)=>{
      const tmp={...this.state.data};
      if(tmp.Nav_PdtBOMs) {
        tmp.Nav_PdtBOMs.map(t => {
          if (t.ID == record.ID) {
            t[field]=value;
          }
        });
      }
      this.setState({
        data:tmp,
      });
    };



    const tableColumns=[
      {title: <>预投日期<span style={{color: 'red'}}>*</span></>, dataIndex: '', key: '', render: (text, record, index)=>{
         return <DatePicker disabled={this.props.data.isShow} value={record.PRE_TIME?moment(record.PRE_TIME):null}
                      format={"YYYY-MM-DD"}  onChange={(value,dateString)=>{doChange(record,'PRE_TIME',dateString)}} />;
      }},
      {title: <>材料编号<span style={{color: 'red'}}>*</span></>, dataIndex: '', key: '',width:100,  render: (text, record, index)=>{
        const tmpRecord=record;
         return <DropDownPagination inputDataApi={'WH/Inventory/InvProductOrderPaged'} fieldName={'Nav_Product.CODE'}  disabled={this.props.data.isShow} onFilter={({params})=>{
           params['Parameter3']=true;
           params['Parameter4']=this.state.data.ID;
         }} data={record} onSelect={({record})=>{tmpRecord.PRODUCT_ID=(record?record.ID:null); tmpRecord.Nav_Product=record; this.saveRecord(tmpRecord); }} disabled={this.props.data.isShow} />
      }},
      {title: '材料名称', dataIndex: 'Nav_Product.NAME', key: 'Nav_Product.NAME'},
      {title: '工序名称', dataIndex: 'Nav_PdtProcessDetail.NAME', key: 'Nav_PdtProcessDetail.NAME'},
      {title: <>需求数量<span style={{color: 'red'}}>*</span></>, dataIndex: 'QTY', key: 'QTY', render: (text, record, index)=>{
          return <InputNumber min={0} disabled={this.props.data.isShow}  value={record.QTY}
                         onChange={(e)=>{ doChange(record,'QTY',e)}} />;
        }},
      {title: '已领数量', dataIndex: 'PICK_QTY', key: 'PICK_QTY'},
      {title: '总需求数量', dataIndex: 'TOTAL_PLAN_QTY', key: 'TOTAL_PLAN_QTY'},
      {title: <>库存数</>, dataIndex: '', key: '', render: (text, record, index)=>{
          const editFormData= {
            pageCode:'PdtOrderBom',
            record: record,
            onSave: (record)=>{this.saveRecord(record);},
            isShow:this.props.data.isShow ,
            isPermit:false,
            stateData:this.state.data.Nav_PdtBOMs,
            getFieldValue:(fieldName)=>{
              if(fieldName=='PDT_ID')
                return this.state.data.ID;
            }
          }
          return<>
            <InputNumber value={record.INVENTORY_QTY}  disabled={true} style={{ width: '80%' }}/>
            <FormModal
              formCode={'WH022'}
              data={editFormData}>
              <Icon type="edit" style={{ marginLeft: 8, fontSize: 20 }}  />
            </FormModal></>
      }},
      {title: '', dataIndex: '', key: '', render: (text, record, index)=>{
          return <Button type={'danger'} disabled={this.props.data.isShow}    onClick={(e)=>this.handleDeleteEmPoposal(record.ID)}  icon={'delete'}>删除</Button>;
      }},
    ]

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

    return (
      <Spin spinning={loading.global}>
        <Form>
          <div>
            <h2>生产订单预投料</h2>
          </div>
          <Row>
            <Col span={12}>
                <Form.Item
                  label={'生产订单'}
                  {...formItemLayout}
                >
                  <Input disabled={true} value={this.state.data.PDT_CODE} />
                </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'产品名称'}
                {...formItemLayout}
              >
                <Input disabled={true} value={(this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.NAME)} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'产品编号'}
                {...formItemLayout}
              >
                <Input disabled={true} value={this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.CODE} />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label={'交货方式'}
                {...formItemLayout}
              >
               <Input disabled={true} value={this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.SPLIT_QTY} />
              </Form.Item>
            </Col>


            <Col span={12}>
              <Form.Item
                label={'拼版尺寸'}
                {...formItemLayout}
              >
                <Input disabled={true} value={this.state.data.Nav_Product==null?'':this.state.data.Nav_Product.SPLIT_SIZE} />
              </Form.Item>
            </Col>


            <Col span={12}>
              <Form.Item
                label={'数量'}
                {...formItemLayout}
              >
                <Input disabled={true} value={this.state.data.QTY} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'交期'}
                {...formItemLayout}
              >
                <Input disabled={true} value={this.state.data.DUE_TIME?this.state.data.DUE_TIME.toString().substring(0,10):null } />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label={'紧急程度'}
                {...formItemLayout}
              >
                <Select  value={this.state.data.EMERGENCY_DEGREE_TYPE}  disabled={true}>
                  {
                    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'}}>
            <Button type={'primary'} disabled={this.props.data.isShow}   onClick={this.handleAddEmPoposal}  icon={'plus'}>新增</Button>
            <Table
              rowKey="ID"
              pagination={false}
              dataSource={this.state.data.Nav_PdtBOMs}
              columns={tableColumns}
              style={{marginTop:'20px'}}
            />
          </Row>


        </Form>
      </Spin>
    );
  }

}

PdtOrderBomPage.propTypes = {
};

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