package nc.pub.filesystem.newui;

import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.Action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.itf.uap.IVOPersistence;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
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;
import nc.vo.pubapp.pattern.pub.SqlBuilder;

/**
 * 获取发票云发票
 * @author y1456
 * 
 */
public class ThSelectAction extends AbstractNCAction{
	
	private IVOPersistence IVOPersistence = (IVOPersistence) NCLocator.getInstance().lookup(IVOPersistence.class);
	private ThFileContentPanel parentpanel;
	private IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	
	public ThSelectAction(ThFileContentPanel para){
		parentpanel = para;
		this.putValue(AbstractAction.NAME,"发票获取");
		this.putValue(Action.SHORT_DESCRIPTION, "发票获取");
	}

	@Override
	public void actionPerformed(ActionEvent actionevent) {
		MessageDialog.showHintDlg(parentpanel, "提示","开始发票获取！");
		String vdef17 =(String) parentpanel.editor_.getBillCardPanel().getHeadItem("vdef17").getValueObject();//附件id
		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());
		
		//获取token
		String token="";
		JSONObject json = null;
		try {
			 token=ocrservice.getToken(billmaker);
		} catch (Exception e) {
			MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
					,"获取token:\n"+e.getMessage());
			return;
		}
		
		try {
			json = ocrservice.SelectORCInvoice(token);
		} catch (Exception e) {
			MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
					,"获取发票云发票:\n"+e.getMessage());
		}
		try {
			//将该单据对应的老数据删除，赋值新数据
			DeleteDOC(vdef17);
			JSONObject data = json.getJSONObject("data");
			JSONArray infos = data.getJSONArray("infos");
			//票夹不存在发票
			if(infos != null) {
				for(int j = 0;j < infos.size();j++){
					JSONObject info = infos.getJSONObject(j);
					String memo = info.getString("number");//发票号
					String code = info.getString("number");//发票代码
					String fid = info.getString("fid");
					
					//自定义已存在该发票跳过新增
					if(QryOCRNumber(vdef17, code) != null) {
						continue;
					}
					//特殊发票发票号和发票代码不存在
					if(code == null || "".equals(code)) {
						memo = "特殊发票"+fid;
						code = fid;
					}
					String ext = info.getString("ext");
					JSONObject extobj = JSONObject.parseObject(ext);
					String trate = extobj.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 date = pro.getString("date");//发票日期
					String type = pro.getString("type");//发票类型
					String cname = pro.getString("cname");//发票类型名称
					String kind = pro.getString("kind");//开票内容
					JSONObject price = comm_info.getJSONObject("price");
					String amount = "";
					String total = "";
					String dtax = "";
					//专票带税额，不是专票无税金额=价税合计
					if(type.equals("1")||type.equals("28")||type.equals("32")){
						amount = price.getString("amount");//无税金额
						total = price.getString("total");//价税合计
						dtax = price.getString("dtax");//可抵扣税额
					}
					else{
						amount = price.getString("total");//无税金额
						total = amount;//价税合计
						dtax = "0";//可抵扣税额
						trate = "0";//非专票税率也为0
					}
					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");//购买方公司名称
					
					IDefdocService idefservice = NCLocator.getInstance().lookup(IDefdocService.class);
					DefdocVO[] vos = new DefdocVO[1];
					DefdocVO defvo = new DefdocVO();
					//赋值
					//为避免自定义档案code,name重复，加上后缀作为区别,仅限发票云获取发票使用
					defvo.setAttributeValue("code", code+"-"+System.currentTimeMillis());
					defvo.setAttributeValue("name", memo+"-"+System.currentTimeMillis());
					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", dtax);
					defvo.setAttributeValue("pid", date);
					defvo.setAttributeValue("shortname5", cname);
					defvo.setAttributeValue("shortname6", trate);
					defvo.setAttributeValue("enablestate", 2);
					defvo.setAttributeValue("innercode", "1");
					defvo.setAttributeValue("shortname4", kind);
					vos[0] = defvo;
					idefservice.insertDefdocs(pk_group, vos);
					}
				}
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/
						,"保存自定义档案数据:\n"+e.getMessage());
				return;
			}
		MessageDialog.showHintDlg(parentpanel, "提示","获取成功！");
	}
	
    @SuppressWarnings("unchecked")
	private DefdocVO[]  QryDefdocvoInfo(String code) throws Exception{
        String sql = "select * from  bd_defdoc where  nvl(dr, 0) = 0 and pk_defdoclist="
        		+ "(select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0) and code='" + code + "' ";
        ArrayList<Object> arrayvos=null;
			arrayvos=(ArrayList<Object>) iuap.executeQuery(sql, new BeanListProcessor(DefdocVO.class));
        	
        if (arrayvos==null||arrayvos.size()==0) {
      		return new DefdocVO[0];
      	}else {
      		return arrayvos.toArray(new DefdocVO[0]);
      	}
    } 
    
    //查询自定义档案的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 String QryOCRNumber(String vdef17,String number) throws Exception{
    	StringBuffer sql = new StringBuffer();
    	sql.append("SELECT");
    	sql.append(" pk_defdoc ");
    	sql.append(" FROM");
    	sql.append(" bd_defdoc");
    	sql.append(" WHERE");
    	sql.append(" name6 = '"+vdef17+"'");
    	sql.append(" AND code = '"+number+"'");
    	sql.append(" AND nvl( dr, 0 ) = 0");
		String pk_defdoc = (String) iuap.executeQuery(sql.toString(), new ColumnProcessor());
		return pk_defdoc;
    }
    
    
    //将老数据删除
    private void DeleteDOC(String vdef17) throws Exception {
    	SqlBuilder sql = new  SqlBuilder();
    	sql.append(" name6 = '"+vdef17+"'");
    	sql.append(" AND innercode = '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());
    }

}
