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 ProductBatchImport extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      selectedRowKeys:[],
    };
  };

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

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

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

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

  handleOk = () => {
    const {form,dispatch,data,login} = 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);
             d.ORG_ID=login.OrgId;
             details.push(d);
        });
      };
      if(!details.length){
        message.error('请选择导入文件或者记录');
        return;
      }
      updateData.Nav_Details=details;

      dispatch({
        type: 'FMProduct/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 {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: 'CODE', key: 'CODE'},
      {title: '产品名称', dataIndex: 'NAME', key: 'NAME'},
      {title: '外部ID1', dataIndex: 'OTHER_CODE_1', key: 'OTHER_CODE_1'},
      {title: '长描述1', dataIndex: 'DESCRIPTION_1', key: 'DESCRIPTION_1'},
      {title: '外部ID2', dataIndex: 'OTHER_CODE_2', key: 'OTHER_CODE_2'},
      {title: '长描述2', dataIndex: 'DESCRIPTION_2', key: 'DESCRIPTION_2'},
      {title: '单位*', dataIndex: 'Nav_Unit.CODE', key: 'Nav_Unit.CODE'},
      {title: '板厚', dataIndex: 'THICKNESS', key: 'THICKNESS'},
    ];

    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14},
    };
    const that=this;
    const uploadProps = {
      name: 'file',
      action: config.serviceHost('api/DT/Import/ImportBatchProduct'),
      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>
            <div>
              <h2>产品外部ID导入</h2>
            </div>

            <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>
    );
  }

}

ProductBatchImport.propTypes = {
};

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