package nc.pub.filesystem.newui;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.swing.AbstractAction;
import javax.swing.Action;
import nc.vo.pub.filesystem.NCFileVO;
import nc.vo.pub.lang.UFDouble;

import org.apache.commons.httpclient.HttpException;

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.framework.common.RuntimeEnv;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.funcnode.ui.action.AbstractNCAction;
import nc.itf.bd.defdoc.IDefdocService;
import nc.itf.th.IThOcrService;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.ui.ml.NCLangRes;
import nc.ui.pub.beans.MessageDialog;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.pub.BusinessException;



public class ThOCRAction extends AbstractNCAction{

	/**
	 * OCR识别
	 */
	private static final long serialVersionUID = -5178574564280732585L;
	//获取发票附件地址
	private String noauth = "https://api.mypiaojia.com/api/invoiceApi/file/download?id=";
	
	private IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	private ThFileContentPanel parentpanel ;
	public ThOCRAction(ThFileContentPanel para){
		parentpanel = para;
		this.putValue(AbstractAction.NAME,"OCR识别");
		this.putValue(Action.SHORT_DESCRIPTION, "OCR识别");
	}

	@Override
	public void actionPerformed(ActionEvent actionevent) {
		MessageDialog.showHintDlg(parentpanel, "提示","开始OCR识别！");
		
		String vdef17 =(String) parentpanel.editor_.getBillCardPanel().getHeadItem("vdef17").getValueObject();//附件id
		String pk_org = (String) parentpanel.editor_.getBillCardPanel().getHeadItem("pk_org").getValueObject();
		String pk_group = (String) parentpanel.editor_.getBillCardPanel().getHeadItem("pk_group").getValueObject();
		String billmaker = InvocationInfoProxy.getInstance().getUserId();
		IThOcrService  ocrservice=(IThOcrService) NCLocator.getInstance().lookup(IThOcrService.class.getName());
		
		List<String> filewjlis=ocrservice.getInvoiceInfo(vdef17);//获取"+vdef17+"文件夹下所有发票名
		
		 if(null==filewjlis||filewjlis.size()==0){
	        	MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
						,"请先上传发票，再进行OCR识别！");
				return;
	      }
		 
		 
		//获取token
		String token="";
		try {
			 token=ocrservice.getToken(billmaker);
		} catch (Exception e) {
			MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
					,"获取token:\n"+e.getMessage());
			return;
		}

		StringBuffer sb=new StringBuffer();
		StringBuffer sb2=new StringBuffer();
		for(int i=0;i<filewjlis.size();i++){
			NCFileVO oldvo = (NCFileVO) parentpanel.getfiletablemodel()
					.getVO(i);
			NCFileVO newvo = oldvo.clone();
			//已识别的发票不需要再次查询
			String filedesc = newvo.getFiledesc();
			if(filedesc != null) {
				continue;
			}
			//发票上传
			String idjson="";
			try {
				idjson=ocrservice.uploadInvoice(token, vdef17,newvo.getName());
			} catch (Exception e) {
				MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
						,"发票上传:\n"+e.getMessage());
				return;
			}
			
			sb.append(idjson).append("\n");
			
			
			JSONObject json = null;
			String checkresult;
			try {
				//发票识别
				String ocrinvoicejson=ocrservice.ocrIdentification(token,idjson);
				sb2.append(ocrinvoicejson).append("\n");
				 //识别数据保存数据库 add by pcy
				json = JSONObject.parseObject(ocrinvoicejson);
				checkresult = checkJson(json);
				if(checkresult != null){
					MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
							,"ocr返回数据校验:\n"+checkresult);
					return;
				}
				
			} catch (Exception e) {
				MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
						,"ocr返回数据校验:\n"+e.getMessage());
			}
			//发票的url地址
			//String url = JSONObject.parseObject(idjson).getJSONObject("data").getString("url");
			JSONObject data = json.getJSONObject("data");
			JSONArray infos = data.getJSONArray("infos");
			for(int j = 0;j < infos.size();j++){
				String message = "OCR已识别";//发票识别标识
				JSONObject info = infos.getJSONObject(j).getJSONObject("info");
				String ret = infos.getJSONObject(j).getString("ret");
				String is_valid = infos.getJSONObject(j).getString("is_valid");
				String name =newvo.getName();
				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";
				}
				if(!"0".equals(ret)) {					
					message = infos.getJSONObject(j).getString("message");					
				}
				//发票识别之后进行发票查验
				//是否需要查验 0不需要 1需要
				if("OCR已识别".equals(message) && "1".equals(is_valid)) {
					try {
						ocrservice.InvoiceCheck(token,fid);
					} catch (Exception e) {
						message = e.getMessage();
					}
				}
				
				
				//添加描述
				newvo.setFiledesc(message);
				// 修改人
				newvo.setModifier(InvocationInfoProxy.getInstance()
						.getUserId());
				// 修改的时间
				Date date2 = new Date();
				newvo.setModifytime(date2.getTime());
				// 保存
				IFileSystemService service = NCLocator.getInstance()
						.lookup(IFileSystemService.class);
				
				try {
					boolean b = service.updateFileAttribute(newvo, oldvo
							.getFullPath());
					if (b) {
						// 更新table
						oldvo.setFiledesc(message);
						oldvo.setModifier(newvo.getModifier());
						oldvo.setModifytime(newvo.getModifytime());
						parentpanel.getfiletablemodel().clearTable();
						parentpanel.getfiletablemodel().addVO(
								parentpanel.getTreenodefilecacheMap().get(
										"root").toArray(new NCFileVO[0]));
						parentpanel.getfiletablemodel().refreshTable();
					} else {
						MessageDialog.showErrorDlg(parentpanel, NCLangRes
								.getInstance().getStrByID("sftemp",
										"PasteAttachAction-0001")/* 错误 */,
								NCLangRes.getInstance().getStrByID(
										"sftemp",
										"FilePatchAttrDialog-0000")/*
																	 * 文件名重复!
																	 */);
					}

				} catch (BusinessException e1) {
					MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
							,"识别标识:\n"+e1.getMessage());
				   return;				

				}
				if(!"OCR已识别".equals(message)) {
					continue;
				}
				
				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 comm_info = info.getJSONObject("comm_info");
				JSONObject pro = comm_info.getJSONObject("pro");
				String date = pro.getString("date");//发票日期
				String cname = pro.getString("cname");//发票类型名称
				String kind = extobj.getString("content");
				JSONObject price = comm_info.getJSONObject("price");
				String amount = "";
				String total = price.getString("total");//价税合计
				String dtax = price.getString("dtax");//可抵扣税额
				String ttax = "";
				//如有可抵扣税额，无税金额等于无税金额，税额等于可抵扣税额，税率等于税率
				//如没有可抵扣税额，无税金额等于无税金额+税额，税额等于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");//购买方公司名称
				JSONObject modify_info = info.getJSONObject("modify_info");
				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;
				    }
				}
				IDefdocService idefservice = NCLocator.getInstance().lookup(IDefdocService.class);
				DefdocVO[] vos = new DefdocVO[1];
				DefdocVO defvo = new DefdocVO();
				//赋值
				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", 0);
				defvo.setAttributeValue("shortname4", kind);
				defvo.setAttributeValue("innercode", codenumber);
				defvo.setAttributeValue("modifier", dtax);
				vos[0] = defvo;
				try {
					idefservice.insertDefdocs(pk_group, vos);
					
					Map<String,String> map = new HashMap<String,String>();
					map.put("KYHSJE", total);
					map.put("KYWSJE", amount);
					map.put("JYSE", ttax);
					map.put("FPXZ", noauth+furl+"&fid="+fid);
					map.put("VDEF17",vdef17);
					map.put("NUMBERID",code);
					ocrservice.addORC(map);
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
								,"保存自定义档案数据:\n"+e.getMessage());
					return;
				}
				
			}
		}
		MessageDialog.showHintDlg(parentpanel, "提示","识别结束！");
	}
	

    
    private String checkJson(JSONObject json) throws Exception {
		
  		StringBuffer mags = new StringBuffer();
  		Boolean empty = true;
  		
  		JSONObject oprepObjectBs = json.getJSONObject("data");
  		
  		if (oprepObjectBs == null || oprepObjectBs.size() == 0) {
  			return "返回值不可为空！";
  		}
  		
  		
  		return null;
  	}
      
      //查询自定义档案的pk
      private String QryOCRPk(){
      	String sql = "select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0";
      	Object object = null;
  		try {
  			object = iuap.executeQuery(sql, new ColumnProcessor());
  		} catch (BusinessException e) {
  			// TODO 自动生成的 catch 块
  			e.printStackTrace();
  		}
  		if (object==null) {
  			return null;
  		}else {
  			return object.toString();
  		}
      }
}
