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} from 'antd';
import {
  extend,
  extendRule,
  initFilter,
  guid,
  extendGroupRule,
  initFilterGroup,extendFilterGroup,
  extendInclude
} from "../../../utils/common";
import {message} from "antd/lib/index";
import EditBaseComponent from "../../../baseComponents/EditBaseComponent";
import styles from './PdtStockPrintPage.css';
import QRCode from 'qrcode';
import { join } from 'path';
import ReactToPrint from "react-to-print";
//import { getLodop } from '../../../utils/LodopFuncs';
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;


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

  doRenderOrder=(order)=>{
    const {btnConfig={},id}=this.props.data?this.props.data:{};
    return <div>
      <table className={styles["craft-table-wrap"]}>
        <thead>
          <tr>
            <th colSpan='11' className={styles.title}>漳州立达信光电子科技有限公司</th>
          </tr>
          <tr>
            <th colSpan='11' className={styles.script}>入库单</th>
          </tr>
          <tr>
            <th colSpan='11' > 
             <span>生产线别：{order.Nav_Job&&order.Nav_Job.Nav_Line?order.Nav_Job.Nav_Line.NAME:null}   </span> &nbsp;&nbsp;&nbsp;&nbsp;         
             <span> 工厂：3302    </span>      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
             <span>  收货仓库：  </span>          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
             <span>   日期：  </span>    
             </th>
          </tr>
          <tr>
            <th>生产订单号</th>
            <th>物料ID</th>
            <th>物料名称</th>
            <th>检验批/单号</th>
            <th>单位</th>
            <th>送检数</th>
            <th>质检结论</th>
            <th>实收数</th>
            <th>未清数量</th>
            <th>备注</th>
            <th>so</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td><div id={id+btnConfig.id+ order.ID+order.PDT_ORDER_ID}></div></td>
            <td>{order.Nav_Product?order.Nav_Product.CODE:null}</td>
            <td>{order.Nav_Product?order.Nav_Product.NAME:null}</td>
            <td><div id={id+btnConfig.id+order.ID}></div></td>
            <td>{order.Nav_Product?order.Nav_Product.UNIT:null}</td>
            <td><div id={order.QTY}></div></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr> 
          <tr>
            <td colSpan='11'></td>
          </tr>
          <tr>
            <td>制单人</td>
            <td>{this.props.login.user?this.props.login.user.NAME:null}</td>
            <td>送检人</td>
            <td></td>
            <td>品保</td>
            <td colSpan='2'></td>
            <td>监督员</td>
            <td></td>
          </tr> 
        </tbody>
      </table>
    </div>
  }
   
  render() {
    const {orderData}=this.props;
    console.log(orderData);
    const {btnConfig={},id}=this.props.data?this.props.data:{};
    const columns=[ 
      { 
        title: '领料单',
        key: '',
        dataIndex: '',
        render: (text, record, index) => { 
          if(record.ID){
            return <div id={id+btnConfig.id+record.ID}></div>;
          }
        }
      }, 
      { 
        title: '入库单',
        key: '',
        dataIndex: '',
        render: (text, record, index) => { 
          if(record.ID){
            return  <div id={id+btnConfig.id+ record.ID+record.PDT_STOCK_ID}></div>;
          }
        }
      },
      { 
        title: '物料ID',
        key: 'Nav_Product.CODE',
        dataIndex: 'Nav_Product.CODE', 
      },
      { 
        title: '物料名称',
        key: 'Nav_Product.NAME',
        className: "print_materi_name",
        dataIndex: 'Nav_Product.NAME', 
        render: (text, record, index) => {  
          return <div style={{width:100}}>{text}</div>
        }
      },
      { 
        title: '库位ID',
        key: 'Nav_Order.Nav_PdtStock.Nav_Location.CODE',
        dataIndex: 'Nav_Order.Nav_PdtStock.Nav_Location.CODE', 
      },
      { 
        title: '仓库ID',
        key: 'Nav_Order.Nav_PdtStock.Nav_Location.Nav_Warehouse.CODE',
        className: "print_materi_name",
        dataIndex: 'Nav_Order.Nav_PdtStock.Nav_Location.Nav_Warehouse.CODE', 
        render: (text, record, index) => {  
          return <div style={{width:100}}>{text}</div>
        }
      }, 
      { 
        title: '单位',
        key: 'Nav_Product.UNIT',
        dataIndex: 'Nav_Product.UNIT', 
      },
      { 
        title: '入库数',
        key: 'QTY',
        dataIndex: 'QTY', 
      },   
    ]
    const first=orderData&&orderData.length?orderData[0].Nac_QcOrder:null;
    return(
    <div className={styles.printMod}>
      <div className={styles.print_title}>厦门铭鹤</div>
      <hr style={{'borderBottom': '1px solid #000'}}/>
      <div className={styles.print_name}>领料单</div>
      <div className={styles.print_head}>
        <span>产线：</span>
        <span>工厂：3302</span>
        {/* <span>收货仓库：</span> */}
        <span>日期：{moment().format('YYYY.MM.DD')}</span>
      </div>
      <Table
        rowKey="ID"
        bordered
        className="print_table"
        pagination={false}
        dataSource={orderData} 
        columns={columns}
      /> 

      <div className={styles.print_foot}>
        <span>制单人:{this.props.login.user?this.props.login.user.NAME:null}</span>
        {/* <span>送检人:</span>
        <span>品保:</span>
        <span>监督员:</span> */}
      </div>
      
    </div>
    )
  }
}


class PickingStockPrintPage extends EditBaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {}, 
    };
    this.canvas = {};
  };
  onLoadData(){
    super.onLoadData();
    const { dispatch,data,formCode, } = this.props; 
    const {getIds}=data;
    if(getIds){
      const ids=getIds();
      if(ids){
        const tempIds= ids.split(','); 
        const json=initFilter(this.props.login.OrgId,'','CREATE_TIME',1);
        let group=initFilterGroup(false);
        tempIds.forEach(n => {
            extendGroupRule(group,'WH_ORDER_ID',1,n);  
        });
        extendFilterGroup(json,group); 
        // extendInclude(json,'Nav_PdtOrder.Nav_Product');
        extendInclude(json,'Nav_Order.Nav_PdtStock.Nav_Location.Nav_Warehouse');
        //extendInclude(json,'');
        extendInclude(json,'Nav_Order');
        extendInclude(json,'Nav_Product');
        const {btnConfig={},}=data?data:{};
        let url='WH/PickingStockDetail/OrderEntities';
        if(btnConfig&&btnConfig.api){
          url=btnConfig.api;
        } 
        dispatch({
          type: 'app/getDataByPost',
          payload: json,
          url: url,
          onComplete: (ret) => {
            const temps=[]; 
            if (ret) {
              tempIds.forEach(n=>{
                const xx=ret.filter(t=>t.WH_ORDER_ID===n)[0]; 
                if(xx){
                  temps.push(xx);
                }
              }); 
            } 
            this.fillQcOrders(temps);
          }
        });}
    }
  }
 
  
  fillQcOrders=(orders)=>{
    const that=this;
    if(that.canvas) {
      Object.keys(that.canvas).forEach((n) => {
        if(n) {
          const container = document.getElementById(n);
          if (container&&that.canvas[n]) {
            try {
              container.removeChild(that.canvas[n]);
            }
            catch(e) { }
          }
        }
      });
      that.canvas = {};
    }

    this.setState({
      orderData:orders,
    },()=>{
      if(orders&&orders.length){
        const {btnConfig={},id}=that.props.data?that.props.data:{};
        orders.forEach((n,i)=>{
          if(n.Nav_Order&&n.Nav_Order.Nav_PdtStock){
          QRCode.toCanvas(n.Nav_Order.Nav_PdtStock.CODE, { errorCorrectionLevel: 'L',width:60 }, function (err, canvas) {
            if (err) throw err;

            // <td><div id={id+btnConfig.id+ order.ID+order.PDT_ORDER_ID}></div></td>
            // <td>{order.Nav_Product?order.Nav_Product.CODE:null}</td>
            // <td>{order.Nav_Product?order.Nav_Product.NAME:null}</td>
            // <td><div id={id+btnConfig.id+order.ID}></div></td> 
            const key=(id+ btnConfig.id+n.ID+n.PDT_STOCK_ID);
            var container = document.getElementById(key);
            if(container) {
              try {
                container.appendChild(canvas);
              }
              catch (e) { }
              that.canvas[key]=canvas;
            }
          });
        }
        if(n.Nav_Order.CODE){
          QRCode.toCanvas(n.Nav_Order.CODE, { errorCorrectionLevel: 'H',width:60 }, function (err, canvas) {
            if (err) throw err;  
            const key=(id+ btnConfig.id+n.ID);
            var container = document.getElementById(key);
            if(container) {
              try {
                container.appendChild(canvas);
              }
              catch (e) { }
              that.canvas[key]=canvas;
            }
          });
          
      }
        });
      }
    });
  }
//   printPageView = () => {
//     let LODOP = getLodop();
//     if(LODOP){
//       LODOP.PRINT_INIT("react使用打印插件CLodop");  //打印初始化
//      // let strStyle = `<style> 打印的样式需要写在这里，下面引入</style> `;

//       LODOP.ADD_PRINT_BARCODE(0,0,200,100,"QRCode","*123ABC4567890*");
//       LODOP.SET_PRINT_STYLEA(0,"QRCodeVersion",7);
//       //LODOP.ADD_PRINT_HTM(100, "5%", "90%", 450, strStyle + document.getElementById("print").innerHTML);
//       LODOP.PREVIEW();  //最后一个打印(预览)语句
//     }
// };
  render() { 
    const {orderData}=this.state;
    return (
      <div>
        <ReactToPrint
          trigger={() => <Button type={'primary'} icon={'printer'} >打印</Button>}
          content={() => this.componentRef} 
        />
        <div style={{marginTop:'25px'}}>
        <DoPickingStockPrintPage ref={el => (this.componentRef = el)}  orderData={orderData} {...this.props} />
        </div>

{/* <div>
                <Button type="primary" onClick={this.printPageView} >打印</Button>
                <div id="print"> <DoQcOrderPrintPage ref={el => (this.componentRef = el)}  orderData={orderData} {...this.props} /></div>
            </div> */}
      </div>
    );
  }

}
 

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