package nc.ui.pubapp.uif2app.actions;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.itf.bd.defdoc.IDefdocService;
import nc.itf.th.IThOcrService;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.IVOPersistence;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.log.NcLog;
import nc.ui.ml.NCLangRes;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.UIButton;
import nc.ui.pub.beans.UIDialog;
import nc.ui.pub.beans.UIPanel;
import nc.ui.pub.bill.BillCardPanel;
import nc.ui.uif2.editor.BillForm;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
public class MultiSelectDialog extends UIDialog {

	/**
	 * 从发票云获取发票界面
	 */
	
	private static final long serialVersionUID = 1L;
	private BillForm editor;
	private JTable table;
	/** 确定按钮 */
	private UIButton btnOK;
	private ActionHandler actionHandler = new ActionHandler();
	private UIPanel btnUIPanel;
	private IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	private IVOPersistence IVOPersistence = (IVOPersistence) NCLocator.getInstance().lookup(IVOPersistence.class);
	private List<DefdocVO> listDefdocVO = new ArrayList<DefdocVO>();
	private IDefdocService idefservice = NCLocator.getInstance().lookup(IDefdocService.class);
	private String billmaker = InvocationInfoProxy.getInstance().getUserId();
	private String pk_group = InvocationInfoProxy.getInstance().getGroupId();
	private String vdef17 = null;
	private IFileSystemService fileservice = NCLocator.getInstance().lookup(IFileSystemService.class);
	private IThOcrService  ocrservice = (IThOcrService) NCLocator.getInstance().lookup(IThOcrService.class.getName());
	//获取发票附件地址
	//private String noauth = "https://dl.mypiaojia.com/api/noauth/?id=";
	private String noauth = "https://api.mypiaojia.com/api/invoiceApi/file/download?id=";
	
	public MultiSelectDialog(BillForm editor) throws Exception {
		this.editor = editor;
		BillCardPanel cpanel=editor.getBillCardPanel();
		vdef17 = (String) cpanel.getHeadItem("vdef17").getValueObject();
		initialize();
		addComponents();
	}

	/**
	 * 初始化
	 */
	private void initialize() {
		setLayout(new BorderLayout());
		this.setBounds(500, 400, 1500, 700);
		this.setResizable(true);
		add(this.getBtnUIPanel(), BorderLayout.SOUTH);
		// 添加监听
		this.addActionListener();
	}
	
	/**
	 * 界面的监听
	 */
	private void addActionListener() {
		this.getBtnOK().addActionListener(this.actionHandler);

	}
	
	
	public UIPanel getBtnUIPanel() {
		if (btnUIPanel == null) {
			btnUIPanel = new nc.ui.pub.beans.UIPanel();
			btnUIPanel.add(this.getBtnOK(), this.getBtnOK().getName());
		}
		return this.btnUIPanel;
	}
	
	private UIButton getBtnOK() {
		if (btnOK == null) {
			btnOK = new UIButton();
			btnOK.setName("btnOK");
			btnOK.setText("确定(Y)");
		}
		return this.btnOK;
	}
	@Override
	public String getTitle() {
		// TODO 自动生成的方法存根
		return "从发票云获取发票界面";
	}
	
	private void addComponents() throws Exception {
	    JPanel panel = new JPanel(new BorderLayout());
	    IThOcrService  ocrservice=(IThOcrService) NCLocator.getInstance().lookup(IThOcrService.class.getName());
	  //获取token
	  	final String token;
	  	JSONObject json = null;
	  	try {
			token = ocrservice.getToken(billmaker);
		} catch (Exception e) {
			throw new Exception("获取发票云token失败:"+e.getMessage());
		} 	
	  	try {
			json = ocrservice.SelectORCInvoice(token);
	  } catch (Exception e) {
		  	
			throw new Exception("获取发票云发票:"+e.getMessage());
		}
	    try {
	    	JSONObject data = json.getJSONObject("data");
			JSONArray infos = data.getJSONArray("infos");
			//票夹不存在发票
			if(infos != null) {
				List<Object[]> dataList = new ArrayList<Object[]>();
				for(int j = 0;j < infos.size();j++){
					JSONObject info = infos.getJSONObject(j);
					String memo = info.getString("number");//发票号
					String code = info.getString("fid");
					String fid = info.getString("fid");
					String codenumber = info.getString("code"); //发票代码
					//特殊发票发票号和发票代码不存在
					if(codenumber == null || "".equals(codenumber)) {
						codenumber = "0";
					}
					if(memo == null || "".equals(memo)) {
						memo = "0";
					}
					String ext = info.getString("ext");
					JSONObject extobj = JSONObject.parseObject(ext);
					String trate = extobj.getString("trate");//税率
					//多行明细存在税率不一致的情况，外部税率字段会为空，转取明细第一行税率
					if(trate == null || "".equals(trate)) {
						JSONArray products = extobj.getJSONArray("products");
						trate = products.getJSONObject(0).getString("trate");
					}
					JSONObject modify_info = info.getJSONObject("modify_info");
					String name = modify_info.getString("fname");
					JSONObject comm_info = info.getJSONObject("comm_info");
					JSONObject pro = comm_info.getJSONObject("pro");
					String furl = modify_info.getString("furl");//发票图片id 或者链接
					if (furl == null || "".equals(furl)) {
					    String pdf = modify_info.getString("pdf");
					    if(pdf == null || "".equals(pdf)) {
					    	furl = pro.getString("pi");
					    }else {
					    	furl = pdf;
					    }
					}
					String date = pro.getString("date");//发票日期
					String type = pro.getString("type");//发票类型
					String cname = pro.getString("cname");//发票类型名称
					//String kind = pro.getString("kind");//开票内容
					String kind = extobj.getString("content");
					JSONObject price = comm_info.getJSONObject("price");
					String amount = "0";
					String total = price.getString("total");//价税合计
					//没有价税合计表示这条数据不是发票，直接跳过
					if(total == null || "".equals(total) || total == "0") {
						continue;
					}
					String dtax = price.getString("dtax") == null ? "0" : price.getString("dtax");//可抵扣税额
					String ttax = "0";
					//如有可抵扣税额，无税金额等于无税金额，税额等于可抵扣税额，税率等于税率
					//如没有可抵扣税额，无税金额等于无税金额+税额，税额等于0，税率等于0
					if("0".equals(dtax)) {
						//无税金额+税额 = 价税合计
						amount = total;
						ttax = "0";//税额
						trate = "0";//税率
					}else {
						amount = price.getString("amount");//无税金额
						ttax = extobj.getString("ttax");//税额
					}
					JSONObject buyer = comm_info.getJSONObject("buyer");
					String mnecode = buyer.getString("tcode");//购买方纳税人识别号
					String name2 = buyer.getString("company");//购买方公司名称
					JSONObject payer = comm_info.getJSONObject("payer");
					String name3 = payer.getString("tcode");//销售方纳税人识别号
					String name4 = payer.getString("company");//购买方公司名称
					Map<Object,Object> mappo =  QryNorigtaxmny(code);
					UFDouble norigtaxmny =  new UFDouble(mappo.get("norigtaxmny") == null ? 0.00 : Double.valueOf(mappo.get("norigtaxmny").toString()),2);//已使用价税合计
					UFDouble norigmny = new UFDouble(mappo.get("norigmny") == null ? 0.00 : Double.valueOf(mappo.get("norigmny").toString()),2);//已使用无税金额
					UFDouble ntax = new UFDouble(mappo.get("ntax") == null ? 0.00 : Double.valueOf(mappo.get("ntax").toString()),2);//已使用税额
					
					UFDouble norigtaxmnys = new UFDouble(total ==  null ? 0.00 : Double.parseDouble(total),2);//发票价税合计
					UFDouble norigmnys = new UFDouble(amount ==  null ? 0.00 : Double.parseDouble(amount),2);//发票无税金额
					UFDouble ntaxs = new UFDouble(ttax ==  null ? 0.00 : Double.parseDouble(ttax),2);//发票税额
					DefdocVO defvo = new DefdocVO();
					long l = System.currentTimeMillis();
					//发票可以重复获取，避免自定义档案保存保存，加上时间戳保证唯一
					code += "—"+l;
					memo += "—"+l;
					defvo.setAttributeValue("code",code);
					defvo.setAttributeValue("name",memo);
					defvo.setAttributeValue("memo", name );
					defvo.setAttributeValue("mnecode", mnecode);
					defvo.setAttributeValue("name2", name2);
					defvo.setAttributeValue("name3", name3);
					defvo.setAttributeValue("name4", name4);
					defvo.setAttributeValue("name5", fid);
					defvo.setAttributeValue("name6", vdef17);
					defvo.setAttributeValue("pk_defdoclist", QryOCRPk());
					defvo.setAttributeValue("pk_group", pk_group);
					defvo.setAttributeValue("pk_org", pk_group);
					defvo.setAttributeValue("datatype", 1);
					defvo.setAttributeValue("enablestate", 2);
					defvo.setAttributeValue("shortname", amount);
					defvo.setAttributeValue("shortname2", total);
					defvo.setAttributeValue("shortname3", ttax);
					defvo.setAttributeValue("pid", date);
					defvo.setAttributeValue("shortname5", cname);
					defvo.setAttributeValue("shortname6", trate);
					defvo.setAttributeValue("dataoriginflag", 1);//0本地上传 1发票云获取
					defvo.setAttributeValue("shortname4", kind);
					defvo.setAttributeValue("innercode", codenumber);
					defvo.setAttributeValue("modifier", dtax);
					listDefdocVO.add(defvo);
					Boolean blen = QryOCRNumber(code, "1")  == null ? false : true;
					String url = noauth+furl+"&fid="+fid;
					String link = "<html><a href="+url+">"+name+"</a></html>";
					//可用无税金额norigmnys.sub(norigmny)  无税金额amount
					Object[] obj = {blen,cname,norigtaxmnys.sub(norigtaxmny),norigmnys.sub(norigmny),ntaxs.sub(ntax),total,amount,trate
							,ttax,dtax,codenumber,memo,link,mnecode,name2,name3,name4,kind,date,code};
					dataList.add(obj);
				}
				String[] columnNames = {"全选","发票类型" ,"可用含税金额","可用无税金额","可用税额","票面含税金额","票面无税金额","票面税率","票面税额"
						,"票面可抵扣金额","发票代码","发票号","发票名称","购买方纳税人识别号","购买方公司名称","销售方纳税人识别号","销售方公司名称"
						,"开票内容","发票时间","fid"};
				Object[][] dataArray = new Object[dataList.size()][columnNames.length];
				for (int i = 0; i < dataList.size(); i++) {
		            Object[] rowData = dataList.get(i);
		            dataArray[i] = rowData;
		        }
				DefaultTableModel model = new DefaultTableModel(dataArray, columnNames) {
			        @Override
			        public boolean isCellEditable(int row, int column) {
			            return (column == 0); // 只允许第一列可编辑
			        }
			    };

			    table = new JTable(model);
			    table.getColumnModel().getColumn(0).setPreferredWidth(50);
			    table.getColumnModel().getColumn(0).setMaxWidth(50);
			    table.getColumnModel().getColumn(0).setCellRenderer(new CheckBoxRenderer());
			    table.getColumnModel().getColumn(0).setCellEditor(new CheckBoxEditor());
			    // 禁用列拖动功能
			    table.getTableHeader().setReorderingAllowed(false);

			    TableColumnModel columnModel = table.getColumnModel();
			    // 遍历所有列，设置宽度为150像素
		        for (int i = 0; i < columnModel.getColumnCount(); i++) {
		        	if(i >= 10 || i == 1) {
		        		table.getColumnModel().getColumn(i).setPreferredWidth(150);
		        	}
		        }

			    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			    // 添加鼠标点击事件监听器
			    table.addMouseListener(new MouseAdapter() {
			        public void mouseClicked(MouseEvent e) {
			            int row = table.rowAtPoint(e.getPoint());
			            int column = table.columnAtPoint(e.getPoint());
			           
			            // 如果点击的是链接列
			            if (column == 12) {
			                String htmlLink = ((String) table.getValueAt(row, column)).replaceAll(".*<a href=(.*?)>.*", "$1");
			                // 使用Desktop类打开默认浏览器
			                try {
			                    Desktop.getDesktop().browse(new URI(htmlLink+"&token="+token));
			                } catch (Exception ex) {
			                    ex.printStackTrace();
			                }
			            }
			        }
			    });

			    table.setRowSelectionAllowed(false);
			    JScrollPane scrollPane = new JScrollPane(table);
			    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
			    panel.add(scrollPane, BorderLayout.CENTER);


			    panel.add(scrollPane, BorderLayout.CENTER);

			    getContentPane().add(panel);

		        // 设置标题行的复选框点击事件监听器
		        addSelectAllMouseListener();
			}else {
				throw new Exception("当前用户票夹中无发票！");
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	    
	}
	boolean isSelectAll = false;
	private void addSelectAllMouseListener() {
	    JTableHeader header = table.getTableHeader();
	    header.addMouseListener(new MouseAdapter() {
	        @Override
	        public void mouseClicked(MouseEvent e) {
	            int column = table.columnAtPoint(e.getPoint());
	            if (column == 0) {
	                boolean isAllSelected = true;
	                
	                // 判断是否有行未被选择
	                for (int i = 0; i < table.getRowCount(); i++) {
	                	boolean isSelected = ((Boolean) table.getValueAt(i, column)).booleanValue();
	                    if (!isSelected) {
	                        isAllSelected = false;
	                        break;
	                    }
	                }
	                
	                // 如果有行未被选择，则将其它列全部选择
	                if (!isAllSelected) {
	                    for (int i = 0; i < table.getRowCount(); i++) {
	                        table.setValueAt(true, i, column);
	                    }
	                }
	                
	                // 否则将其它列全部取消选择
	                else {
	                    for (int i = 0; i < table.getRowCount(); i++) {
	                        table.setValueAt(false, i, column);
	                    }
	                }
	            }
	            
	            // 如果点击的不是全选列，则直接取消全选状态
	            else {
	                if (isSelectAll) {
	                    isSelectAll = false;
	                    table.setValueAt(false, 0, 0);
	                }
	            }
	        }
	    });
	}

	private static class CheckBoxRenderer extends DefaultTableCellRenderer {
	    private final JCheckBox checkBox;

	    public CheckBoxRenderer() {
	        checkBox = new JCheckBox();
	        checkBox.setHorizontalAlignment(JCheckBox.CENTER);
	    }

	    @Override
	    public Component getTableCellRendererComponent(JTable table, Object value,
	                                                   boolean isSelected, boolean hasFocus,
	                                                   int row, int column) {
	        if (value instanceof Boolean) {
	            checkBox.setSelected((Boolean) value);
	        }
	        
	        // 让复选框可以被选择
	        checkBox.setEnabled(true);
	        
	        return checkBox;
	    }
	}
	
	private class CheckBoxEditor extends DefaultCellEditor {
	    private JCheckBox checkBox;

	    public CheckBoxEditor() {
	        super(new JCheckBox());
	        checkBox = (JCheckBox) getComponent();
	        checkBox.setHorizontalAlignment(JCheckBox.CENTER);
	    }

	    @Override
	    public Object getCellEditorValue() {
	        return checkBox.isSelected();
	    }
	}
	
	class ActionHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == MultiSelectDialog.this.getBtnOK()) {
				// 确定按钮执行事件
				MultiSelectDialog.this.doOKAction();
			}
			
		}
	}
	
	private void doOKAction(){
		try {
			chend();
			List<Object[]> list  = getSelectedData();
			for (int i = 0; i < list.size(); i++) {
				//选中的code
				String code = list.get(i)[19].toString();
				for (int j = 0; j < listDefdocVO.size(); j++) {
					//获取的code
					String codes = listDefdocVO.get(j).getCode();
					//匹配选中值，插入自定义档案
					if(code.equals(codes)) {
						DefdocVO  defdoc = QryOCRNumber(code,null);
						if(defdoc == null) {
							//插入
							DefdocVO defdocVO = listDefdocVO.get(j);
							idefservice.insertDefdocs(pk_group,new DefdocVO[] { defdocVO });
							Map<String,String> map = new HashMap<String,String>();
							map.put("KYHSJE", list.get(i)[2].toString());
							map.put("KYWSJE", list.get(i)[3].toString());
							map.put("JYSE", list.get(i)[4].toString());
							String htmlLink =  list.get(i)[12].toString().replaceAll(".*<a href=(.*?)>.*", "$1");
							map.put("FPXZ", htmlLink);
							map.put("NUMBERID", list.get(i)[19].toString());
							map.put("VDEF17",vdef17);
							ocrservice.addORC(map);
							break;
						}					
					}
				}
				
			}
			this.dispose();
		} catch (Exception e) {
			MessageDialog.showErrorDlg(null, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
					,e.getMessage());
		}
		
	}
	
	private void chend() throws Exception {
		//发票云未选择发票
		List<Object[]> unlist = getUnselectedData();
		int count =editor.getBillCardPanel().getBodyPanel().getTable().getRowCount();//明细行条数
		//获取参照已经勾选的发票数据
		List<String> lisvdef20 = new ArrayList<String>();
		for(int i = 0;i<count;i++){
			Object objvbdef20 = editor.getBillCardPanel().getBodyValueAt(i, "vbdef20");//主键
			if(null != objvbdef20){
				String vbdef20 = objvbdef20.toString();
				String[] vbd20arry = vbdef20.split(",");
				for(int j = 0;j < vbd20arry.length;j++){
					lisvdef20.add(vbd20arry[j]);
				}
			}
		 }
		
//		List<String> memoarry = QryDefMemo(lisvdef20);
//		String number = "";//发票号
//		for (int i = 0; i < unlist.size(); i++) {
//			//如果发票参照没有选择数据，可直接删除
//			if(memoarry.size() == 0) {
//				String code = unlist.get(i)[19].toString();
//				number += code.substring(0, code.indexOf("—")) +",";
//			}
//			//未选中的发票名称
//			String name = unlist.get(i)[12].toString().replaceAll("<[^>]*>", "");
//			for (int j = 0; j < memoarry.size(); j++) {
//				//参照已选中的发票
//				String names = memoarry.get(j);
//				if(name.equals(names)) {
//					throw new Exception(name+":发票已经被勾选，不允许取消勾选！");
//				}
//				//如果发票参照选择了数据，匹配后没有相同项，可删除
//				if((j+1) == memoarry.size()) {
//					String code = unlist.get(i)[19].toString();
//					number += code.substring(0, code.indexOf("—")) +",";
//				}
//			}
//		}
		List<String> memoarry = QryDefMemo(lisvdef20);
		String number = "";//发票号
		for (int i = 0; i < unlist.size(); i++) {
			//如果发票参照没有选择数据，可直接删除
			if(memoarry.size() == 0) {
				String code = unlist.get(i)[19].toString();
				number += code.substring(0, code.indexOf("—")) +",";
			}
			//弹框未选中的code
			String code = unlist.get(i)[19].toString();
			for (int j = 0; j < memoarry.size(); j++) {
				
				//参照已选中的发票
				String codes = memoarry.get(j);
				//发票名称
				String name = unlist.get(i)[12].toString().replaceAll("<[^>]*>", "");
				if(code.substring(0, code.indexOf("—")).equals(codes.substring(0, codes.indexOf("—")))) {
					throw new Exception(name+":发票已经被勾选，不允许取消勾选！");
				}
				//如果发票参照选择了数据，匹配后没有相同项，可删除
				if((j+1) == memoarry.size()) {
					number += code.substring(0, code.indexOf("—")) +",";
				}
			}
		}
		if(!"".equals(number)) {
			DeleteDOC(number);
			ocrservice.deleteORC(number, vdef17,1);
		}
		
	}
	
	
    //vdef17+"/"+defdocVO.getMemo()
    private void DeleteFile(String pjnames) throws Exception {
    	String[] names = pjnames.split(",");
		for(int i=0;i<names.length;i++){
			names[i]=vdef17+"/"+names[i];
		}

    	fileservice.deleteNCFileNodes(names);
				
    	
    }
	
	//获取选中的数据
	private List<Object[]> getSelectedData() {
	    List<Object[]> selectedData = new ArrayList<Object[]>();

	    for (int i = 0; i < table.getRowCount(); i++) {
	        boolean isSelected = (Boolean) table.getValueAt(i, 0);
	        if (isSelected) {
	            Object[] rowData = new Object[table.getColumnCount()];
	            for (int j = 0; j < table.getColumnCount(); j++) {
	                rowData[j] = table.getValueAt(i, j);
	            }
	            selectedData.add(rowData);
	        }
	    }

	    return selectedData;
	}
	
	//获取没选中的数据
	private List<Object[]> getUnselectedData() {
	    List<Object[]> unselectedData = new ArrayList<Object[]>();

	    for (int i = 0; i < table.getRowCount(); i++) {
	        boolean isSelected = (Boolean) table.getValueAt(i, 0);
	        if (!isSelected) { // 修改条件判断为 !isSelected
	            Object[] rowData = new Object[table.getColumnCount()];
	            for (int j = 0; j < table.getColumnCount(); j++) {
	                rowData[j] = table.getValueAt(i, j);
	            }
	            unselectedData.add(rowData);
	        }
	    }

	    return unselectedData;
	}

	
    //查询自定义档案的pk
    private String QryOCRPk() throws Exception{
    	String sql = "select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0";
    	Object object = null;
			object = iuap.executeQuery(sql, new ColumnProcessor());
		if (object==null) {
			return null;
		}else {
			return object.toString();
		}
    }
	
    //查询发票是否在自定义已存在
    private DefdocVO QryOCRNumber(String number,String dataoriginflag) throws Exception{
    	//去掉拼接时间戳
    	String code = number.substring(0, number.indexOf("—"));
    	StringBuffer sql = new StringBuffer();
    	sql.append("SELECT");
    	sql.append(" name6, ");
    	sql.append(" dataoriginflag ");
    	sql.append(" FROM");
    	sql.append(" bd_defdoc");
    	sql.append(" WHERE");
    	sql.append("  code like '"+code+"%'");
    	sql.append(" AND name6 = '"+vdef17+"'");
    	if(dataoriginflag != null) {
    		sql.append(" AND dataoriginflag = '"+dataoriginflag+"'");
    	}
    	
    	sql.append(" AND nvl( dr, 0 ) = 0");
		return (DefdocVO) iuap.executeQuery(sql.toString(), new BeanProcessor(DefdocVO.class));
    }
    

    //将不需要的发票从临时表删除
    private void DeleteDOC(String number) throws Exception {
    	String[] arrNumber = number.split(",");
    	SqlBuilder sql = new  SqlBuilder();
    	sql.append(" name6 = '"+vdef17+"'");
    	if(arrNumber.length == 1) {
    		sql.append(" AND SUBSTR(code, 1, INSTR(code, '—')-1) = '"+arrNumber[0].toString()+"'");
    	}else {
    		SqlBuilder sqlb = new SqlBuilder();
			sqlb.append("SUBSTR(code, 1, INSTR(code, '—')-1)", arrNumber);
    		sql.append(" AND  "+sqlb.toString());
    	}
    	
    	sql.append(" AND dataoriginflag = '1'");
    	sql.append(" AND pk_defdoclist = ( SELECT pk_defdoclist FROM bd_defdoclist WHERE code = 'OCRTHNC' AND nvl( dr, 0 ) = 0 )");
    	IVOPersistence.deleteByClause(DefdocVO.class, sql.toString());
    }
    
	private List<String> QryDefMemo(List<String> lisvdef20) throws Exception{
		 String[] arraydef20 = lisvdef20.toArray(new String[0]);
		 List<String> arrayvos = new ArrayList<String>();
		 if(null == arraydef20 || arraydef20.length == 0){
			 return arrayvos; 
		 }
		 
		 SqlBuilder	sqlb = new SqlBuilder();
		 sqlb.append("select code  ");
		 sqlb.append("from  bd_defdoc ");
		 sqlb.append("where nvl(dr, 0) = 0 and pk_defdoclist= ");
		 sqlb.append("(select pk_defdoclist ");
		 sqlb.append("from bd_defdoclist ");
		 sqlb.append("where code='OCRTHNC' and nvl(dr,0)=0) ");
		 sqlb.append("and ");
		 sqlb.append("pk_defdoc", arraydef20);
		 ArrayList<String> objts = (ArrayList<String>) iuap.executeQuery(sqlb.toString(), new ColumnListProcessor("code"));
		 if(null != objts && objts.size()>0){
			 arrayvos = objts;
		}
		
		 return arrayvos;
		
	}
	/**
	 * 查询该发票已使用价税合计,无税金额，税额
	 * @param code 发票号
	 * @return
	 * @throws Exception
	 */
	private Map<Object,Object> QryNorigtaxmny(String code) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT");
		sql.append(" SUM( po_invoice_b.norigtaxmny ) as norigtaxmny,");
		sql.append(" SUM( po_invoice_b.norigmny ) as norigmny,");
		sql.append(" SUM( po_invoice_b.ntax ) as ntax");
		sql.append(" FROM");
		sql.append(" po_invoice po_invoice");
		sql.append(" LEFT JOIN po_invoice_b po_invoice_b ON po_invoice.pk_invoice = po_invoice_b.pk_invoice ");
		sql.append(" WHERE");
		sql.append(" po_invoice.fbillstatus <> '0' ");
		sql.append(" AND po_invoice.fbillstatus <> '1' ");
		sql.append(" AND po_invoice_b.vbdef20 IN ( SELECT pk_defdoc FROM bd_defdoc WHERE code LIKE '"+code+"%' )");
		sql.append(" AND nvl(po_invoice.dr,0) = 0");
		sql.append(" AND nvl(po_invoice_b.dr,0) = 0");
		return (Map<Object, Object>) iuap.executeQuery(sql.toString(), new MapProcessor());
	}
}

