package nc.bs.arap.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nc.bs.arap.plugin.GetDataUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.servlet.service.BaseServlet;
import nc.itf.arap.pay.IArapPayBillQueryService;
import nc.itf.arap.payable.IArapPayableBillQueryService;
import nc.itf.pu.m21.IOrderMaintain;
import nc.itf.pu.m25.IInvoiceMaintain;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.pf.IPFBusiAction;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.log.NcLog;
import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.arap.pay.PayBillVO;
import nc.vo.arap.payable.AggPayableBillVO;
import nc.vo.arap.payable.PayableBillVO;
import nc.vo.pu.m21.entity.OrderHeaderVO;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pu.m25.entity.InvoiceHeaderVO;
import nc.vo.pu.m25.entity.InvoiceVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.workflownote.WorkflownoteVO;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 单据删除接口
 */
public class DeleteBillImpl extends BaseServlet implements IHttpServletAdaptor {
	private static IUAPQueryBS iuap = (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	private IMDPersistenceQueryService service = NCLocator.getInstance().lookup(IMDPersistenceQueryService.class);

	@Override
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String billno="";
		try {
			NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(), "pfxx".getBytes());
			String createStr = buildJson(req, resp, this.getClass().getName());
			JSONObject json = JSON.parseObject(createStr);
			NcLog.info("单据:" + json.toString());
//			InvocationInfoProxy.getInstance().setUserDataSource("NC6337");
			String pk_group = GetDataUtil.getGroupPK("00");
			InvocationInfoProxy.getInstance().setGroupId(pk_group);//指定集团pk
			InvocationInfoProxy.getInstance().setBizDateTime(System.currentTimeMillis());
			billno= json.getString("billno");
			String pkTradetype = json.getString("pkTradetype");
			delBill(billno, pkTradetype);
			resp.getWriter().write(formatRSJsonData("0", billno, "单据删除成功！").toString());
		} catch (Exception e) {
			resp.getWriter().write(formatRSJsonData("失败",e.getMessage() == null ? "" : e.getMessage(),billno).toString());
			StringWriter stringWriter = new StringWriter();
			e.printStackTrace(new PrintWriter(stringWriter));
			// 获取详细信息
			String msg = stringWriter.getBuffer().toString();
			NcLog.info("单据:" + msg);
		}
	}

	/**
	 * 根据单据号和不同的单据类型删除单据
	 * @param vbillcode
	 * @param pkTradetype
	 * @throws Exception
	 */
	private void delBill(String vbillcode, String pkTradetype) throws Exception {
		if ("F3-Cxx-04".equals(pkTradetype)||"F3-Cxx-05".equals(pkTradetype)) {// 对外预付款(非项目)||对外预付款(项目)
			// sql查询出单据主键
			String sql = "select * from ap_paybill where billno ='" + vbillcode + "' and nvl(dr,0)=0";
			PayBillVO headerVO = (PayBillVO) iuap.executeQuery(sql, new BeanProcessor(PayBillVO.class));
			if (headerVO == null) {
				throw new Exception("单据号:" + vbillcode + "不存在！");
			}
			if(headerVO.getApprovestatus()!=-1){	
				updateBillState("approvestatus",-1,"ap_paybill","billno",vbillcode);
			}
			// 根据主键查询AggVO
			IArapPayBillQueryService service = NCLocator.getInstance().lookup(IArapPayBillQueryService.class);
			AggPayBillVO[] aggvo = (AggPayBillVO[]) service.findBillByPrimaryKey(new String[] { headerVO.getPk_paybill() });
			WorkflownoteVO Workflownote = new WorkflownoteVO();		
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			ipf.processAction("DELETE", "F3", Workflownote, aggvo[0], null, null);
			
		} else if ("D1".equals(pkTradetype)) {//应付单(非项目)
			String sql = "select * from ap_payablebill where billno ='" + vbillcode + "' and nvl(dr,0)=0";
			PayableBillVO headerVO = (PayableBillVO) iuap.executeQuery(sql, new BeanProcessor(PayableBillVO.class));
			if (headerVO == null) {
				throw new Exception("单据号:" + vbillcode + "不存在！");
			}
			if(headerVO.getApprovestatus()!=-1){	
				updateBillState("approvestatus",-1,"ap_payablebill","billno",vbillcode);
			}
			IArapPayableBillQueryService service = NCLocator.getInstance().lookup(IArapPayableBillQueryService.class);
			AggPayableBillVO[] aggvo = (AggPayableBillVO[]) service.findBillByPrimaryKey(new String[] { headerVO.getPk_payablebill() });
			WorkflownoteVO Workflownote = new WorkflownoteVO();
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			ipf.processAction("DELETE", "D1", Workflownote, aggvo[0], null, null);
			
		} else if ("F1-Cxx-02".equals(pkTradetype)||"F1-Cxx-04".equals(pkTradetype)||"F1-Cxx-05".equals(pkTradetype)) {//应付单(项目)||预算核销(非项目)||预算核销(项目)
			String sql = "select * from ap_payablebill where billno ='" + vbillcode + "' and nvl(dr,0)=0";
			PayableBillVO headerVO = (PayableBillVO) iuap.executeQuery(sql, new BeanProcessor(PayableBillVO.class));
			if (headerVO == null) {
				throw new Exception("单据号:" + vbillcode + "不存在！");
			}
			if(headerVO.getApprovestatus()!=-1){	
				updateBillState("approvestatus",-1,"ap_payablebill","billno",vbillcode);
			}
			IArapPayableBillQueryService service = NCLocator.getInstance().lookup(IArapPayableBillQueryService.class);
			AggPayableBillVO[] aggvo = (AggPayableBillVO[]) service.findBillByPrimaryKey(new String[] { headerVO.getPk_payablebill() });		
			WorkflownoteVO Workflownote = new WorkflownoteVO();
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			ipf.processAction("DELETE", "F1", Workflownote, aggvo[0], null, null);
			
		} else if ("25".equals(pkTradetype)) {//采购发票
			String sql = "select * from po_invoice where vbillcode ='" + vbillcode + "' and nvl(dr,0)=0";
			InvoiceHeaderVO headerVO = (InvoiceHeaderVO) iuap.executeQuery(sql, new BeanProcessor(InvoiceHeaderVO.class));
			if (headerVO == null) {
				throw new Exception("单据号:" + vbillcode + "不存在！");
			}
			if(headerVO.getFbillstatus()!=0){	
				updateBillState("fbillstatus",0,"po_invoice","vbillcode",vbillcode);
			}
			InvoiceVO aggvo = (InvoiceVO) service.queryBillOfNCObjectByPKWithDR(InvoiceVO.class, headerVO.getPk_invoice(),true).getContainmentObject();
			IInvoiceMaintain invoiceMaintain = NCLocator.getInstance().lookup(IInvoiceMaintain.class);
			invoiceMaintain.delete(new InvoiceVO[]{aggvo} , null);

		} else if ("21".equals(pkTradetype)) {//采购订单
			String sql = "select * from po_order where vbillcode ='" + vbillcode + "' and nvl(dr,0)=0";
			OrderHeaderVO headerVO = (OrderHeaderVO) iuap.executeQuery(sql, new BeanProcessor(OrderHeaderVO.class));
			if (headerVO == null) {
				throw new Exception("单据号:" + vbillcode + "不存在！");
			}
//			OrderVO aggvo = (OrderVO) service.queryBillOfNCObjectByPKWithDR(OrderVO.class, headerVO.getPk_order(),true).getContainmentObject();
//			IOrderApprove orderApprove = NCLocator.getInstance().lookup(IOrderApprove.class);
			if(headerVO.getForderstatus()!=0){
//				orderApprove.unapprove(new OrderVO[]{aggvo}, null);
//				WorkflownoteVO workflownoteVO=new WorkflownoteVO();
//				IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
//				ipf.processAction("UNAPPROVE", "21", workflownoteVO, aggvo, null, null);	
				updateBillState("forderstatus",0,"po_order","vbillcode",vbillcode);
			}
			OrderVO aggvo = (OrderVO) service.queryBillOfNCObjectByPKWithDR(OrderVO.class, headerVO.getPk_order(),true).getContainmentObject();
			IOrderMaintain orderMaintain = NCLocator.getInstance().lookup(IOrderMaintain.class);
			orderMaintain.delete(new OrderVO[]{aggvo}, null);
		}
	}
	
	
	private void updateBillState(String out,int outValue,String tableName,String fromTo,String value) throws BusinessException{
		BaseDAO dao = new BaseDAO();
		String sql = "update "+tableName+" set "+out+" = "+outValue+" where "+fromTo+" ='" + value + "' and nvl(dr,0)=0";
		dao.executeUpdate(sql);
	}

}
