/**
 * @Description:
 * @author ayawai
 * date 2019/04/07
 */
import React, { Component } from 'react';
import {
  Input,
  Card,
  Button,
  Alert,
  Table,
  Icon,
  Row,
  Col,
} from 'antd';
import { initFilter,extendInclude,extend,guid } from "../../../utils/common";
import { connect } from 'dva';
import styles from './BomWorkTaskRelationPage.css';
import ShowModal from '../../common/ShowModal';
import FormPage from '../../FormPage';

class BomWorkTaskRelationPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      search:{
        productCode:"",
        pdtCode:"",
      },
      pageInfo: {},
      pagination:{
        PageIndex:1,
        pageSize: 10,
        TotalCount: 0,
      },
    };
  }

  componentDidMount() {
   this.pageListSearch("load");
  }

  pageListSearch = (info) => {
    const { dispatch, loading } = this.props;
    const { pagination,search } = this.state;
    const OrgId = localStorage.getItem('ORG_ID');
    let para1="";
    let para2="";
    let pageindex=info=="search"?1:pagination.PageIndex;
    let pageSize=info=="search"?10:pagination.pageSize;
    if(info=="search"){
       para1=search.productCode;
       para2=search.pdtCode;
       pagination.PageIndex=1;
       pagination.pageSize=10;
       this.setState({
        pagination
       });
    }
    const json = initFilter(OrgId, "", 'CREATE_TIME', 0, pageindex, para1,para2);
    json.Limit=pageSize;
    dispatch({
      type: 'WOBomWorkTaskRelation/getPageList',
      payload: json,
      onComplete: res => {
        pagination.TotalCount=res.TotalCount;
        this.setState({
          pageInfo: res.Data,
          pagination
        });
      },
    });
  };

  changeTable = (paginationconfig, filters, sorter) => {
    const {current, pageSize, total} = paginationconfig;
    const { pagination } = this.state;
    pagination.PageIndex=current;
    pagination.pageSize=pageSize;
    this.setState({
        ...pagination
    },()=>{
      this.pageListSearch()
    })
  };

  changeSearch=(e,field)=>{
    const { search } = this.state;
    if(field=="productCode")
    search.productCode=e.target.value;
    if(field=="pdtCode")
    search.pdtCode=e.target.value;
    this.setState({
      search
    })
  }

  regClick = () => {
    let isError = false;
    if (!isError) {
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          "WO026Add": true
        },
      });
    }
    return {
      isReturn: isError
    }
  };

  render() {
    const {
      pageInfo,
      currentValue,
      isTip,
      searchValue,
    } = this.state;
    const columns = [
      { title: '编号', dataIndex: 'CODE', key: 'code' },
      { title: '计划时间', dataIndex: 'PLAN_TIME', key: 'plantime',
      render: text => {
        return text=="0001-01-01 00:00:00"?"":text.substr(0,10)
      }
     },
      { title: '产品编号', dataIndex: 'Nav_Product.CODE', key: 'pcode' },
      {title: '物料名称',dataIndex: 'Nav_Product.NAME',key: 'pname',
        render: text => {
          if (text) {
            return <span title={text}>{`${text.substr(0, 5)  }${text.length > 5 ? "..." : ""}`}</span>
          }
          return null
        }
      },
      { title: '工单', dataIndex: 'TASK_CODES', key: 'taskCodes' },
      {
        title: '是否需要打印SN',
        dataIndex: 'IS_NEED_PRINT',
        key: 'isNeedPrint',
        render: text => {
         return text==false?"否":"是"
        }
      },
      { title: '关联的小卡工单', dataIndex: 'CHILD_PDT', key: 'childPdt' },
      { title: '', dataIndex: '', key: 'operat', render:(text,record,index) =>{
        const close = (type) => {
          if (type === undefined || type === 0) {
            const tmpFunc = this.state['closeModelFunc'+record.ID];
            if (tmpFunc) {
              tmpFunc();
            }
          }
        };
        const closeFunc = (fun) => {
          const data = {};
          data['closeModelFunc' +record.ID] = fun;
          this.setState(data);
        };
        const that=this;
        const regClick= async function () {
          await that.props.dispatch({
            type: 'custom/save',
            payload: {
              ['bomWorkTask'+(record? record.ID:'')]:true
            },
          });
        };
        // const regClick = () => {
        //   let isError = false;
        //   if (!isError) {
        //     this.props.dispatch({
        //       type: 'custom/save',
        //       payload: {
        //         ["WO026Add"+record.ID]: true
        //       },
        //     });
        //   }
        //   return {
        //     isReturn: isError
        //   }
        // };
      //  const showData={};
        let clickKey = "bomWorkTask";
        const btnParam={};
        const showData={regClose: closeFunc,};
        let tempData = {
          id: (record ? record.ID : ''),
          isInoreId:true,
          clickKey,
          parentRecord: record,
          onSave: () => {
            close();
            //this.loadTableData({ tableCode });
          },
          onCancel: () => {
           // close();
          },
          onRegDestroyCacheDataFunc: (ret) => {
            //if (!this.regDestroyCacheDataFunc) {
            //  this.regDestroyCacheDataFunc = {};
            //}
           // this.regDestroyCacheDataFunc[clickKey + (record ? record.ID : '')] = ret;
          }
        };
        // if (btnParam.data) {
        //   tempData = {
        //     ...tempData,
        //     ...btnParam.data,
        //   }
        // }
        btnParam.content = <FormPage formCode={'WO025'} data={tempData} />;
        btnParam.click = () => { return regClick() };
        showData.close = () => {
          // if (this.regDestroyCacheDataFunc && this.regDestroyCacheDataFunc[clickKey + (record ? record.ID : '')]) {
          //   this.regDestroyCacheDataFunc[clickKey + (record ? record.ID : '')]();
          // }
        }
        if (btnParam) {
          extend(showData, btnParam);
        }
        if(record.IS_TOP){
          return (
            <div>
             <ShowModal key={ record.ID+'edit'} title={'编辑'} data={showData}>
             <Button type="primary">编辑</Button>
            </ShowModal>
             </div>
             )
        }
      }, },
    ];
    const customExpandIcon = (props) => {
      if (!props.record.Nav_Childrens.length) return <a className="expand-row-icon" />;
      let i = null;
      if (props.expanded) {
        i = "minus-square";
      } else {
        i = "plus-square";
      }
      return (
        <Icon
          onClick={e => props.onExpand(props.record, e)}
          style={{ cursor: 'pointer', marginRight: 6 }}
          type={i}
        />
      )
    }
    const paginationConfig = {
      pageSizeOptions: ['5', '10', '20', '50', '100'],
      current: this.state.pagination.PageIndex, //this.state.data.PageIndex,
      pageSize: this.state.pagination.pageSize,
      total: this.state.pagination.TotalCount,
      showSizeChanger: true,
      showTotal: () => `共 ${this.state.pagination.TotalCount} 条`
    };
    const closeFunc = (fun) => {
      const data = {};
      data['closeModelFunc' ] = fun;
      this.setState(data);
    };
    const showData={regClose: closeFunc,};
    const btnParam={};
    const close = (type) => {
      if (type === undefined || type === 0) {
        const tmpFunc = this.state['closeModelFunc'];
        if (tmpFunc) {
          tmpFunc();
        }
      }
    };
    const clickKey = "WO026Add";
    let tempData = {
      id: "",
      parentRecord: '', 
      isInoreId:true,
      clickKey,
      onSave: () => {
        close();
        this.pageListSearch("load");
      },
      onCancel: () => {
      },
      onRegDestroyCacheDataFunc: (ret) => {
        if (!this.regDestroyCacheDataFunc) {
          this.regDestroyCacheDataFunc = {};
        }
        this.regDestroyCacheDataFunc[clickKey + ('')] = ret;
      }
    };
    btnParam.content = <FormPage formCode={'WO026'} data={tempData} />;
    btnParam.click = this.regClick;
    showData.close = () => {
      if (this.regDestroyCacheDataFunc && this.regDestroyCacheDataFunc[clickKey + ('')]) {
        this.regDestroyCacheDataFunc[clickKey + ('')]();
      }
    }
    if (btnParam) {
      extend(showData, btnParam);
    }
    return (
      <div>
        
         
            <Card
              bordered={false}
              style={{ marginBottom: 15, overflow: "auto" }}
              bodyStyle={{padding: "12px 0"}}
            >
              <Row className={styles.searchHead}>
              <Col span={8} >
                </Col>
                <Col span={16}>
                  <Row>
                    <Col span={10}>
                      <Row gutter={16}>
                        <Col span={10} style={{textAlign: "right"}}><label>产品编号</label></Col>
                        <Col span={14}><Input value={this.state.search.productCode} key="productCode"  onChange={(e) => this.changeSearch(e,"productCode")} /></Col>
                      </Row>
                    </Col>
                    <Col span={10}>
                      <Row gutter={16}>
                        <Col span={10} style={{textAlign: "right"}}><label>工单编号</label></Col>
                        <Col span={14}><Input value={this.state.search.pdtCode} key="pdtCode" onChange={(e) => this.changeSearch(e,"pdtCode")}  /></Col>
                      </Row>
                    </Col>
                    <Col span={4} style={{paddingLeft: 10}}>
                      <Button type="primary" onClick={(e)=>{this.pageListSearch("search")}}>查询</Button>
                    </Col>
                  </Row>
                </Col>
              </Row>
              <Row>
              <Col span={8} style={{textAlign: "left"}}>
                <ShowModal key={'edit'} title={'新增'} data={showData}>
                <Button type="primary">新增</Button>
                </ShowModal>
                </Col>
              </Row>
              <Table
                rowKey={e => e.ID}
                columns={columns}
                childrenColumnName="Nav_Childrens"
                //defaultExpandAllRows
                dataSource={pageInfo.length>0?pageInfo:[]}
                expandIcon={customExpandIcon}
                pagination={paginationConfig}
                onChange={this.changeTable}
              //  rowClassName={rowClass}
              />
            </Card>
      
       
      </div>
    );
  }
}
export default connect(({ login, loading,app,custom })=> ({ login, loading,app,custom }))(BomWorkTaskRelationPage);
