package nc.ui.pu.m25.editor.card.afteredit.body;

import java.util.Arrays;
import java.util.Map;

import nc.bs.framework.common.NCLocator;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.ui.pu.pub.editor.card.listener.ICardBodyAfterEditEventListener;
import nc.ui.pub.beans.UIRefPane;
import nc.ui.pub.beans.constenum.DefaultConstEnum;
import nc.ui.pubapp.uif2app.event.card.CardBodyAfterEditEvent;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

public class OcrRefaft implements ICardBodyAfterEditEventListener{
	
	public IUAPQueryBS iuap=(IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	@Override
	public void afterEdit(CardBodyAfterEditEvent arg0) {
		try {
			UIRefPane ref = (UIRefPane) arg0.getBillCardPanel().getBodyItem("OCR").getComponent();
			String[] pks = ref.getRefPKs();
			StringBuffer sbf = new StringBuffer();
			// 处理PK
			if (pks == null || pks.length <= 0) {
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "vbdef15");//销售方公司
			    arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "vbdef17");//发票分类
			    arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "ntaxrate");//税率
		 	    arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "ctaxcodeid");//税码
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "nastnum");//数量
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "nnum");//主数量
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "nastorigprice");//无税单价
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "nastprice");//本币无税单价
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "nprice");//主本币无税单价
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "norigmny");//无税金额
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "nmny");//本币无税金额
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "nastorigtaxprice");//含税单价
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "nasttaxprice");//本币含税单价
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "ntaxprice");//主本币含税单价
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "norigtaxmny");//价税合计
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "ntaxmny");//本币价税合计
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "ntax");//税额
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "vbdef20");//主键
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "vbdef16");//显示名称
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "ncalcostmny");//计成本金额
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "vbdef13");//开票内容
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "vbdef14");//是否一致
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "vbdef12");//显示名称
				arg0.getBillCardPanel().setBodyValueAt(null, arg0.getRow(), "vbdef11");//发票地址
				return;
			}else {
				for (int i = 0; i < pks.length; i++) {
					sbf.append(pks[i]+",");
				}	
			}
			
			
			UFDouble SumAmount = UFDouble.ZERO_DBL;//不含税
			UFDouble SumTotal = UFDouble.ZERO_DBL;//价税合计
			UFDouble SumTax =UFDouble.ZERO_DBL;//税额
			String url = null;
			String shuilv = "";//记录第一条税率，和后面进行对比，若不同则报错不允许保存
			String supplier = "";//记录第一条供应商，和后面进行对比，若不同则报错不允许保存
			Object shuilvpk = "";
			StringBuffer kind = new StringBuffer();
			if(pks.length > 1){
				for(int j = 0;j < pks.length;j++){
					String pk = pks[j];
					String qrysql = "select * from bd_defdoc where dr=0 and pk_defdoc = '"+pk+"'";
					DefdocVO defdocvo;
					defdocvo = (DefdocVO) iuap.executeQuery(qrysql, new BeanProcessor(DefdocVO.class));
					Object shortname6 = defdocvo.getShortname6();
					String name4 = defdocvo.getName4();
					if(shortname6 == null){
						ExceptionUtils.wrappBusinessException("所选发票税率为空，不能保存！");
						return;
					}
					if(j == 0 && shortname6 != null){
						shuilv = shortname6.toString();
					}
					if(j == 0 || supplier == null){
						supplier = name4;
					}
					if(j != 0 && !shortname6.toString().equals(shuilv)){
						ExceptionUtils.wrappBusinessException("所选发票税率不同，不能保存！");
						return;
					}
					if(j != 0 && name4 != null && supplier != null) {
						if(!name4.equals(supplier)) {
							ExceptionUtils.wrappBusinessException("所选发票供应商不同，不能保存！");
							return;
						}
					}
				}
			}
			//不会存在一行选择多张发票了，遵循运行没问题就不改动原则，不再做处理
			for(int i = 0;i < pks.length;i++){
				String pk = pks[i];
				String qrysql = "select * from bd_defdoc where dr=0 and pk_defdoc = '"+pk+"'";
				DefdocVO defdocvo;
				
					defdocvo = (DefdocVO) iuap.executeQuery(qrysql, new BeanProcessor(DefdocVO.class));
					String qryshuilv = "select pk_taxcode from bd_taxrate where nvl(dr,0) = 0 and pk_taxcode not in (select pk_taxcode from bd_taxcode where code = '0') and taxrate = '"+defdocvo.getShortname6()+"'";
					try {
						shuilvpk = iuap.executeQuery(qryshuilv, new ColumnProcessor());
						if(shuilvpk == null){
							ExceptionUtils.wrappBusinessException("税率没有对应税码，请检查！");
							return;
						}
					} catch (BusinessException e1) {
						// TODO 自动生成的 catch 块
						ExceptionUtils.wrappBusinessException(e1.getMessage());
					}
					arg0.getBillCardPanel().setBodyValueAt(defdocvo.getName4(), arg0.getRow(), "vbdef15");//销售方公司
					arg0.getBillCardPanel().setBodyValueAt(defdocvo.getShortname5(), arg0.getRow(), "vbdef17");//发票分类
					arg0.getBillCardPanel().setBodyValueAt(defdocvo.getShortname6(), arg0.getRow(), "ntaxrate");//税率
					arg0.getBillCardPanel().setBodyValueAt(shuilvpk, arg0.getRow(), "ctaxcodeid");//税码
					arg0.getBillCardPanel().setBodyValueAt(defdocvo.getCode(), arg0.getRow(), "vbdef16");//发票fid
					
					StringBuffer sql = new StringBuffer();
					sql.append("SELECT");
					sql.append(" * ");
					sql.append(" FROM");
					sql.append(" ocr_defdoc");
					sql.append(" WHERE");
					sql.append(" vdef17 = '"+defdocvo.getName6()+"' ");
					sql.append(" AND numberid = '"+defdocvo.getCode()+"' ");
					Map<String,String> mapdb = (Map<String, String>) iuap.executeQuery(sql.toString(), new MapProcessor());
					//为null表示为发票上传数据，其次表示为发票云获取的
					//发票上传的数据可直接使用。发票云获取的可能存在二次使用，取中间表的
					if(mapdb.get("kyhsje") == null) {
						Object shortname = defdocvo.getShortname();
						if(shortname != null && shortname.toString() != ""){
							SumAmount = SumAmount.add(new UFDouble(shortname.toString()));
						}
						Object shortname2 = defdocvo.getShortname2();
						if(shortname2 != null && shortname2.toString() != ""){
							SumTotal = SumTotal.add(new UFDouble(shortname2.toString()));
						}
						Object shortname3 = defdocvo.getShortname3();
						if(shortname3 != null && shortname3.toString() != ""){
							SumTax = SumTax.add(new UFDouble(shortname3.toString()));
						}
					}else {
						SumAmount = SumAmount.add(new UFDouble(mapdb.get("kywsje")));
						SumTotal = SumTotal.add(new UFDouble(mapdb.get("kyhsje")));
						SumTax = SumTax.add(new UFDouble(mapdb.get("jyse")));
						
					}
					
					url = mapdb.get("fpxz");
					kind.append(defdocvo.getShortname4()+",");
			}
			//销售方公司和供应商之间校验是否一致
			String vbdef15 = (String) arg0.getBillCardPanel().getBodyValueAt(arg0.getRow(), "vbdef15");//销售方公司
			String headSupplier = (String) arg0.getBillCardPanel().getHeadItem("pk_supplier").getValueObject();//供应商
			if(vbdef15 == null && headSupplier == null) {
				//一致
				arg0.getBillCardPanel().setBodyValueAt("一致", arg0.getRow(), "vbdef14");
			}else if(vbdef15 == null || headSupplier == null) {
				//不一致
				arg0.getBillCardPanel().setBodyValueAt("不一致", arg0.getRow(), "vbdef14");
			}else {
				String sql = "select name from bd_supplier where pk_supplier ='"+headSupplier+"'";
				String name = (String) iuap.executeQuery(sql, new ColumnProcessor());
				// 使用正则表达式替换中文括号为英文括号
				name = name.replaceAll("（", "(").replaceAll("）", ")");
				vbdef15 = vbdef15.replaceAll("（", "(").replaceAll("）", ")");
				if(vbdef15.equals(name)) {
					//一致
					arg0.getBillCardPanel().setBodyValueAt("一致", arg0.getRow(), "vbdef14");
				}else {
					//不一致
					arg0.getBillCardPanel().setBodyValueAt("不一致", arg0.getRow(), "vbdef14");
				}
			}
			
			//价税合计小于0
			if(SumTotal.compareTo(new UFDouble(0)) < 0) {
				arg0.getBillCardPanel().setBodyValueAt(-1, arg0.getRow(), "nastnum");//数量
				arg0.getBillCardPanel().setBodyValueAt(-1, arg0.getRow(), "nnum");//主数量
				arg0.getBillCardPanel().setBodyValueAt(SumTotal.abs(), arg0.getRow(), "nastorigtaxprice");//含税单价
				arg0.getBillCardPanel().setBodyValueAt(SumTotal.abs(), arg0.getRow(), "nasttaxprice");//本币含税单价
				arg0.getBillCardPanel().setBodyValueAt(SumTotal.abs(), arg0.getRow(), "ntaxprice");//主本币含税单价
				arg0.getBillCardPanel().setBodyValueAt(SumAmount.abs(), arg0.getRow(), "nastorigprice");//无税单价
				arg0.getBillCardPanel().setBodyValueAt(SumAmount.abs(), arg0.getRow(), "nastprice");//本币无税单价
				arg0.getBillCardPanel().setBodyValueAt(SumAmount.abs(), arg0.getRow(), "nprice");//主本币无税单价
			}else {
				arg0.getBillCardPanel().setBodyValueAt(1, arg0.getRow(), "nastnum");//数量
				arg0.getBillCardPanel().setBodyValueAt(1, arg0.getRow(), "nnum");//主数量
				arg0.getBillCardPanel().setBodyValueAt(SumTotal, arg0.getRow(), "nastorigtaxprice");//含税单价
				arg0.getBillCardPanel().setBodyValueAt(SumTotal, arg0.getRow(), "nasttaxprice");//本币含税单价
				arg0.getBillCardPanel().setBodyValueAt(SumTotal, arg0.getRow(), "ntaxprice");//主本币含税单价
				arg0.getBillCardPanel().setBodyValueAt(SumAmount, arg0.getRow(), "nastorigprice");//无税单价
				arg0.getBillCardPanel().setBodyValueAt(SumAmount, arg0.getRow(), "nastprice");//本币无税单价
				arg0.getBillCardPanel().setBodyValueAt(SumAmount, arg0.getRow(), "nprice");//主本币无税单价
			}
			
			arg0.getBillCardPanel().setBodyValueAt(url, arg0.getRow(), "vbdef11");//发票地址
			arg0.getBillCardPanel().setBodyValueAt(SumAmount, arg0.getRow(), "norigmny");//无税金额
			arg0.getBillCardPanel().setBodyValueAt(SumAmount, arg0.getRow(), "nmny");//本币无税金额
			arg0.getBillCardPanel().setBodyValueAt(SumAmount, arg0.getRow(), "ncalcostmny");//计成本金额
			arg0.getBillCardPanel().setBodyValueAt(SumTotal, arg0.getRow(), "norigtaxmny");//价税合计
			arg0.getBillCardPanel().setBodyValueAt(SumTotal, arg0.getRow(), "ntaxmny");//本币价税合计
			arg0.getBillCardPanel().setBodyValueAt(SumTax, arg0.getRow(), "ntax");//税额
			
			
			
			//存放PK
		//	ref.setPKs(pks);
			DefaultConstEnum refEnumxz = new DefaultConstEnum(sbf.toString().substring(0, sbf.toString().length()-1), ref.getRefShowName());
			//DefaultConstEnum refEnum = new DefaultConstEnum("1001ZZ1000000097LQJ2", "发票信息已赋值");///默认值（发票信息已赋值）
			//arg0.getBillCardPanel().setBodyValueAt(refEnum, arg0.getRow(), "OCR");//默认
			String vbdef13 = kind.toString();
			byte[] bytes = kind.toString().getBytes("UTF-8");
			if (bytes.length > 101) {
			    byte[] truncatedBytes = Arrays.copyOf(bytes, 101);
			    vbdef13 = new String(truncatedBytes, "UTF-8");
			}
			arg0.getBillCardPanel().setBodyValueAt(vbdef13, arg0.getRow(), "vbdef13");//开票内容
			arg0.getBillCardPanel().setBodyValueAt(sbf.toString().substring(0, sbf.toString().length()-1), arg0.getRow(), "vbdef20");//主键
			arg0.getBillCardPanel().setBodyValueAt(refEnumxz, arg0.getRow(), "vbdef12");//显示名称
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
   }

}