import React from 'react';
import { connect } from 'dva';
import DropDownPagination from '../../common/DropDownPaginationEx'
import {  Select, Switch, Button, Table, Input, Popconfirm, Form, Row, Col } from 'antd';
import styles from './ApplyOrderToOrderPage.css';
import {
  guid,
  extendRule,
  initFilter,
  initQueryFilter,
  getOnlyPropertyData,
  getDataFieldValue,
  setDataFieldValue
} from "../../../utils/common";
import {message} from "antd/lib/index";
import storage from "../../../utils/storage";
const Option = Select.Option;


const data = [];

const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);
class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === 'text') {
      return <Input />;
    }
    return <Input />;
  };

  render() {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      ...restProps
    } = this.props;

    return (
      <EditableContext.Consumer>
        {(form) => {
          const { getFieldDecorator } = form;
          return (
            <td {...restProps}>
              {editing ? (
                <FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [{
                      required: true,
                      message: `Please Input ${title}!`,
                    }],
                    initialValue: record[dataIndex],
                  })(this.getInput())}
                </FormItem>
              ) : restProps.children}
            </td>
          );
        }}
      </EditableContext.Consumer>
    );
  }
}
class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data,
      editingKey: ''
    };
    this.columns = [
      {

        title: '材料名称',
        dataIndex: 'Nav_Product.NAME',
        width: '15%',
        editable: false,
      },
      {

        title: '材料编号',
        dataIndex: 'Nav_Product.CODE',
        width: '10%',
        editable: false,
      },
      {

        title: '规格',
        dataIndex: 'Nav_Product.SPEC',
        width: '10%',
        editable: false,
      },
      {

        title: '类型',
        dataIndex: 'Nav_Product.PRODUCT_TYPE',
        width: '10%',
        editable: false,
      },
      {

        title: '标准单价',
        dataIndex: 'Nav_Product.PRICE',
        width: '10%',
        editable: false,
      },
      {

        title: '采购单价',
        dataIndex: 'Nav_OrderDetail.UNIT_PRICE',
        width: '10%',
        editable: true,
      },
      {
        title: '采购数量',
        dataIndex: 'QTY',
        width: '10%',
        editable: true,
      },
      {
        title: '计划交期',
        dataIndex: 'DELIVERY_TMIE',
        width: '20%',
        editable: true,
        render: (text) => {
          if(text)
          return text.slice(0, 10)
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) => {
          const editable = this.isEditing(record);
          return (
            <div>
              {editable ? (
                <span>
                  <EditableContext.Consumer>
                    {form => (
                      <a
                        href="javascript:;"
                        onClick={() => this.save(form, record.key)}
                        style={{ marginRight: 8 }}
                      >
                        保存
                      </a>
                    )}
                  </EditableContext.Consumer>
                  <Popconfirm
                    title="确定取消?"
                    onConfirm={() => this.cancel(record.key)}
                  >
                    <a>取消</a>
                  </Popconfirm>
                </span>
              ) : (
                <a onClick={() => this.edit(record.key)}>编辑</a>
              )}
              <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record.key)}>
                <a href="javascript:;">   删除</a>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
  }
  componentDidMount(){
    this.setState({
      data:this.props.dataSource,
    })
  };
  componentWillReceiveProps(NextProp) {
    this.setState({
      data: NextProp.dataSource
    })
  }

  isEditing = (record) => {
    return record.key === this.state.editingKey;
  };


  edit(key) {
    this.setState({ editingKey: key });
  }

  save(form, key) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.data];
      const index = newData.findIndex(item => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        this.setState({ data: newData, editingKey: '' });
      } else {
        newData.push(row);
        this.setState({ data: newData, editingKey: '' });
      }

    });
  };
  handleDelete = (key) => {
    const data = [...this.state.data];
    this.props.handleDel(data, key)
    // const dataSource = [...this.state.data];
    // this.setState({ data: dataSource.filter(item => item.key !== key) });

  };
  cancel = () => {
    this.setState({ editingKey: '' });
  };

  render() {
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const columns = this.columns.map((col) => {
      //console.log(col)
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'DELIVERY_TMIE' ? 'DateTime' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <Table
        rowKey='ID'
        components={components}
        bordered
        dataSource={this.state.data}
        columns={columns}
        rowClassName="editable-row"
      />
    );
  }
}
class ApplyOrderToOrderPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      expand: false,
      ProviderList:[],
      saveData:{
        FORM_ID:'',
        ORG_ID:'',
        ENABLE_STATUS:0,
        CODE:'',
        ENABLE_FLOW:true,
        REMARK:'',
        isUpdateSubSource:true,
        PROVIDER_ID:'',
        Nav_OrderDetail:[]
      },
    };
  };

  LoadCilentData=()=> { //获取日历模板的数据

    const orgId = storage('lacal').getItem('webOrgId').val;
    let json = initQueryFilter(orgId, 1, 100, "CREATE_TIME", 0);
    extendRule(json, "ENABLE_STATUS", 1, 0);//过滤启用状态
    // extendInclude(json,"Nav_CalendarClass.Nav_Class.Nav_ClassDetail");
    // //extendInclude(json,"Nav_Class");
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'PO/Provider/OrderPaged',
      payload: json,
      onComplete: (ret) => {
        this.setState({
          ProviderList: ret
        });
      }
    });
  }

  getFormID=()=> { //获取表单FORM_ID的数据
    const orgId = storage('lacal').getItem('webOrgId').val;
    // const OJson = initFilter(orgId);
    // extendRule(OJson, 'CODE', 1, 'PO004');
    const OJson = {'Key':'PO004','orgid':orgId};
    //extendRule(OJson, 'CODE', 1, formCode);
    this.props.dispatch({
      type: 'app/getFormByRedis',
      payload: OJson,
      onComplete: (ret) => {
        if(ret) {
          this.setState({
            saveData:{
              ...this.state.saveData,
              FORM_ID:ret.ID,
              ORG_ID:orgId
            }
          });
        }
      }
    });
  }
  componentDidMount() {
    this.LoadCilentData();
    this.getFormID();
    // console.log(this.props.data)
    const {data, formId, login, dispatch} = this.props;

    //console.log(login.orgid);
    const json=initFilter(login.OrgId);
    json.Count=1;
    json.CodeType=6000

    dispatch({
      type: 'app/genSystemCode',
      payload: json,
      onComplete: (ret) => {
        if (ret) {

          this.props.form.setFieldsValue({'orderCode':ret})
        }
      }
    })
    this.props.form.resetFields();
    this.loadData();
  }

  componentWillReceiveProps(NextProps) {
    if (NextProps.custom.poApplyOrderToPOOrderEditClick ) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          poApplyOrderToPOOrderEditClick:false
        },
      });
    }
  }
  loadData=()=>{
    if(this.props.custom.poApplyOrderToPOOrderEditRecords) {
      const tmp= this.props.custom.poApplyOrderToPOOrderEditRecords();
      let dataSource=[];
      if(tmp&&tmp.length){
        dataSource=[...tmp];
        dataSource.forEach((n,i)=>{
          if(n.Nav_Product){
            n.LENGTH=n.Nav_Product.LENGTH;
            n.WIDTH=n.Nav_Product.WIDTH;
          }
        })
      }
      this.setState({
        dataSource:dataSource
      })
    }

  };

  handleAdd = () => {
    const { dataSource } = this.state;
    const newData = {
      key: guid(),
      class_tpye:'',
      START_TIME:'',
      END_TIME: '',

    };
    this.setState({
      dataSource: [...dataSource, newData],

    });
   // console.log(this.state.dataSource)
  };
  handleDel = (data, key) => {
    this.setState({ dataSource: data.filter(item => item.key !== key) })
  };
  handleSave = (e) => {
    const {dispatch} = this.props;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) {
        return ;
      }

      let FlowStatus=this.props.form.getFieldValue('isEnableFlow');
      if(typeof(FlowStatus)==='undefined')
      {
        FlowStatus=true;
      }
      let tmp=getOnlyPropertyData(this.state.saveData);
      tmp={
        ...tmp,
        Nav_OrderDetail:this.state.dataSource,
        REMARK:this.props.form.getFieldValue('remark'),
        CODE:this.props.form.getFieldValue('orderCode'),
        ENABLE_FLOW:FlowStatus
      }

     // console.log(this.state.saveData)
      dispatch({
        type: 'POApplyOrderToOrder/FullUpdate',
        payload: tmp,
        onComplete: (ret) => {
          if(ret) {
            message.success('执行成功');
            if(this.props.data.close){
              this.props.data.close();
            }
          }
        }
      });



    });
   //console.log(this.props.form.getFieldValue('remark'))
    //console.log(this.state.FORM_ID)
  };

  handleProviderChange=(value)=>{
   // console.log(`selected ${value}`);

    this.setState({
      saveData:{
        ...this.state.saveData,
        PROVIDER_ID:value
      }
    })
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    //const { TextArea } = Input;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    const onSelectUser=({record})=>{
      const saveData= {...this.state.saveData};
      setDataFieldValue(saveData,'Nav_User.NAME',getDataFieldValue(record,'NAME',null));
      setDataFieldValue(saveData,'USER_ID',getDataFieldValue(record,'ID',null));
      this.setState({
        saveData,
      });
    }

    return (
      <div>
        <div>
        <p>编辑</p>
          <hr/>
        </div>
        <div className={styles.div}>
          <Form
            onSubmit={this.handleSave}
          >
            <Row gutter={16} >
              <Col span={12}>
                <FormItem label="采购单编号：" {...formItemLayout}>
                  {getFieldDecorator('orderCode', {
                    rules: [{
                      required: true,
                      message: '请输入采购单编号!',
                    }],
                  })(
                    <Input placeholder="请输入采购单编号" style={{ width: 250 }}/>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="供应商：" {...formItemLayout}>
                  {getFieldDecorator('provider', {
                    rules: [{
                      required: true,
                      message: '请选择供应商!',
                    }],
                  })(
                    <Select
                      style={{ width: 250 }}
                      showSearch
                      placeholder='请选择供应商'
                      optionFilterProp="children"
                      onChange={this.handleProviderChange}
                      filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    >
                      {//map 循环 填充下拉项目
                        this.state.ProviderList.map(item => {
                          return <Option key={item.ID} value={item.ID}>{item.NAME}</Option>
                        })
                      }
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="是否送审：" {...formItemLayout}>
                  {getFieldDecorator('isEnableFlow', {
                    rules: [{
                      required: false,
                      message: '请输入采购单编号!',
                    }],
                  })(
                    <Switch defaultChecked  />
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="请购人：" {...formItemLayout}>
                    <DropDownPagination inputDataApi={'FM/User/OrderPaged'} fieldName={'Nav_User.NAME'} inpuNavField={'NAME,ID'}
                                        data={this.state.saveData} onSelect={onSelectUser} onFilter={({params})=>{
                                         extendRule(params,'ENABLE_STATUS',1,0);
                                        }} />
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="备注" {...formItemLayout}>
                  {getFieldDecorator('remark', {
                    rules: [{
                      required: false,
                      message: '!',
                    }],
                  })(
                    <Input autosize={true} placeholder="请输入备注" style={{ width: 250 }} />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={24} style={{ textAlign: 'right' }}>
                <Button type="primary" htmlType="submit">保存</Button>
              </Col>
            </Row>
          </Form>

        </div>
        <div className={styles.div}>
          <EditableTable dataSource={this.state.dataSource} handleDel={this.handleDel}  />
        </div>
      </div>
    );
  }
}

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