import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Button, Row, Col, Form, Input,Select,Checkbox,Modal,Transfer,Spin ,Table,DatePicker,InputNumber,message,Upload,Icon} from 'antd';
import {
  extend,
  extendRule,
  initFilter,
  guid,
  extendGroupRule,
  initFilterGroup,
  extendInclude, getOnlyPropertyData
} from "../../../utils/common";
import config from "../../../config";
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;

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

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

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

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

    this.setState({
      data: {},
      selectedRowKeys:[],
      updateLoadFileList:[],
    });
  };

  onSelectChange = (selectedRowKeys,selectedRows) => {  // 选择菜单行
    this.setState({selectedRowKeys:selectedRowKeys});
  };

  handleOk = () => {
    const {form,dispatch,data} = this.props;
    const {getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue} = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      let updateData={};
      const details=[];
      if(this.state.data.Nav_Details){
        this.state.data.Nav_Details.map(t=>{
            let isSelect=false;
            if(this.state.selectedRowKeys&&this.state.selectedRowKeys.length){
              this.state.selectedRowKeys.forEach((n,i)=>{
                if(t.ID==n){
                  isSelect=true;
                }
              });
            }
            if(!isSelect)return;
             var d=getOnlyPropertyData(t);
             var m=getOnlyPropertyData(t.Nav_Order);
             d.Nav_Order=m;
             details.push(d);
        });
      };
      if(!details.length){
        message.error('请选择导入文件或者记录');
        return;
      }
      updateData.Nav_Details=details;

      dispatch({
        type: 'SOOrderImport/saveImport',
        payload: updateData,
        onComplete: (ret) => {
          if(ret) {
            if(data.close){
              data.close();
            }
            this.setState({
              data: {},
              selectedRowKeys:[],
            });
            message.success('执行成功');
          }
        }
      });
    })
  };

  fillImportData=(ret)=>{
    if(!ret){
      this.setState({
        data:ret.Data,
        selectedRowKeys:[],
      })
    }
    if(ret.ErrorMessage){
      message.error(ret.ErrorMessage);
    }
    if(ret.Data&&ret.Data.MessageList&&ret.Data.MessageList.length){
      ret.Data.MessageList.forEach((n,i)=>{
        message.warning(n);
      });
    }
    const selectedRowKeys=[];
    if(ret.Data&&ret.Data.Nav_Details){
      ret.Data&&ret.Data.Nav_Details.forEach((n,i)=>{
        selectedRowKeys.push(n.ID);
      });
    }
    this.setState({
      data:(ret.Data?ret.Data:{}),
      selectedRowKeys
    });
  }




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

    const {selectedRowKeys} =this.state;

    const rowSelection = {
      selectedRowKeys:selectedRowKeys,
      fixed: false,
      columnWidth: 20,
      onChange: this.onSelectChange,
      hideDefaultSelections:false
    };
    const colDateFormat=(text)=>{//格式化日期  只取日期部分
      if(text){
        return text.toString().substring(0,10);
      }
    };
    const tableColumns=[
      {title: '销售订单', dataIndex: 'Nav_Order.CODE', key: 'Nav_Order.CODE'},
      {title: '客户', dataIndex: 'Nav_Order.Nav_Client.NAME', key: 'Nav_Order.Nav_Client.NAME'},
      {title: '交货地点', dataIndex: 'DELIVERY_SITE', key: 'DELIVERY_SITE'},
      {title: '品名', dataIndex: 'Nav_Product.NAME', key: 'Nav_Product.NAME'},
      {title: '拼版尺寸', dataIndex: 'Nav_Product.SPLIT_SIZE', key: 'Nav_Product.SPLIT_SIZE'},
      {title: '拼版数量', dataIndex: 'Nav_Product.SPLIT_QTY', key: 'Nav_Product.SPLIT_QTY'},
      {title: '外部ID', dataIndex: 'PRODUCT_OTHER_CODE', key: 'PRODUCT_OTHER_CODE'},
      {title: '产品长描述', dataIndex: 'PRODUCT_DESCRIPTION', key: 'PRODUCT_DESCRIPTION'},
      {title: '订单数量', dataIndex: 'PLAN_QTY', key: 'PLAN_QTY'},
      {title: '订单交期', dataIndex: 'PLAN_DELIVERY_TMIE', key: 'PLAN_DELIVERY_TMIE',render:colDateFormat},
      {title: '来源行号', dataIndex: 'SRC_ROW_NUM', key: 'SRC_ROW_NUM'},
    ];

    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14},
    };
    const that=this;
    const uploadProps = {
      name: 'file',
      action: config.serviceHost('api/DT/Import/ImportSaleOrder'),
      data:{OrgId:this.props.login.OrgId},
      fileList:this.state.updateLoadFileList,
      accept:'.xls,.xlsx',
      onChange(info) {
        that.setState({
          updateLoadFileList:info.fileList,
        });

        if (info.file.status === 'done') {
          that.fillImportData(info.file.response);
        } else if (info.file.status === 'error') {
          if(info.file.response&&info.file.response.ErrorMessage){
            message.error(`${info.file.name} 导入错误，详情：${info.file.response.ErrorMessage}`);
          }
          else{
            message.error(`${info.file.name} 导入错误`);
          }

        }
      },
    };


    return (
      <div>
          <Form>
            <Row style={{marginTop:'10px'}}>
              <Upload {...uploadProps}>
                <Button>
                  <Icon type="upload" /> 选择导入文件
                </Button>
              </Upload>
            </Row>


            <Row style={{marginTop:'20px'}}>
              <Table
                rowKey="ID"
                pagination={false}
                dataSource={this.state.data.Nav_Details}
                columns={tableColumns}
                rowSelection={rowSelection}
              />
            </Row>
            <Row style={{marginTop:'20px'}}>
              <Col style={{ textAlign: 'right' }}>
                <Button type={'primary'} icon={'save'} onClick={() => this.handleOk()}>保存</Button>
              </Col>
            </Row>
          </Form>
      </div>
    );
  }

}

OrderImportPage.propTypes = {
};

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