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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import nc.bs.arap.plugin.GetDataUtil;
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.uap.IUAPQueryBS;
import nc.itf.uap.pf.IPFBusiAction;
import nc.itf.uap.pf.IWorkflowMachine;
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.workflownote.WorkflownoteVO;

/**
 * 单据审批接口
 */
public class ApproveBillImpl 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().setUserId(json.getString("approver"));// 用户主键
			billno = json.getString("billno");
			String pkTradetype = json.getString("pkTradetype");
			approveBill(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 approveBill(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() != 3) {
				throw new Exception("单据号:" + vbillcode + "单据状态不允许审批！");
			}
			// 根据主键查询AggVO
			IArapPayBillQueryService service = NCLocator.getInstance().lookup(IArapPayBillQueryService.class);
			AggPayBillVO[] aggvo = (AggPayBillVO[]) service.findBillByPrimaryKey(new String[] { headerVO.getPk_paybill() });
			// 调用单据审批
			IWorkflowMachine iworkmachine = NCLocator.getInstance().lookup(IWorkflowMachine.class);// 工作流
			WorkflownoteVO workflownoteVO = iworkmachine.checkWorkFlow("APPROVE", "F3", aggvo[0], null);
			workflownoteVO.setApproveresult("Y");// 审批意见
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			ipf.processAction("APPROVE", "F3", workflownoteVO, aggvo[0], null, null);

		} else if ("D1".equals(pkTradetype)) {// 应付单(非项目)
			// SQL查询出单据主键
			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() != 3) {
				throw new Exception("单据号:" + vbillcode + "单据状态不允许审批！");
			}
			// 根据主键查询AggVO
			IArapPayableBillQueryService service = NCLocator.getInstance().lookup(IArapPayableBillQueryService.class);
			AggPayableBillVO[] aggvo = (AggPayableBillVO[]) service.findBillByPrimaryKey(new String[] { headerVO.getPk_payablebill() });
			// 调用单据审批
			IWorkflowMachine iworkmachine = NCLocator.getInstance().lookup(IWorkflowMachine.class);// 工作流
			WorkflownoteVO workflownoteVO = iworkmachine.checkWorkFlow("APPROVE", "D1", aggvo[0], null);
			workflownoteVO.setApproveresult("Y");// 审批意见
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			ipf.processAction("APPROVE", "D1", workflownoteVO, aggvo[0], null, null);

		} else if ("F1-Cxx-02".equals(pkTradetype) || "F1-Cxx-04".equals(pkTradetype) || "F1-Cxx-05".equals(pkTradetype)) {// 应付单(项目)||预算核销(非项目)||预算核销(项目)
			// SQL查询出单据主键
			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() != 3) {
				throw new Exception("单据号:" + vbillcode + "单据状态不允许审批！");
			}
			// 根据主键查询AggVO
			IArapPayableBillQueryService service = NCLocator.getInstance().lookup(IArapPayableBillQueryService.class);
			AggPayableBillVO[] aggvo = (AggPayableBillVO[]) service.findBillByPrimaryKey(new String[] { headerVO.getPk_payablebill() });
			// 调用单据审批
			IWorkflowMachine iworkmachine = NCLocator.getInstance().lookup(IWorkflowMachine.class);// 工作流
			WorkflownoteVO workflownoteVO = iworkmachine.checkWorkFlow("APPROVE", "F1", aggvo[0], null);
			workflownoteVO.setApproveresult("Y");// 审批意见
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			ipf.processAction("APPROVE", "F1", workflownoteVO, aggvo[0], null, null);

		} else if ("25".equals(pkTradetype)) {// 采购发票
			// SQL查询出单据主键
			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() != 1) {
				throw new Exception("单据号:" + vbillcode + "单据状态不允许审批！");
			}
			// 根据主键查询AggVO
			InvoiceVO aggvo = (InvoiceVO) service.queryBillOfNCObjectByPKWithDR(InvoiceVO.class, headerVO.getPk_invoice(), true).getContainmentObject();
			// 调用单据审批
			IWorkflowMachine iworkmachine = NCLocator.getInstance().lookup(IWorkflowMachine.class);// 工作流
			WorkflownoteVO workflownoteVO = iworkmachine.checkWorkFlow("APPROVE", "25", aggvo, null);
			workflownoteVO.setApproveresult("Y");// 审批意见
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			ipf.processAction("APPROVE", "25", workflownoteVO, aggvo, null, null);

		} else if ("21".equals(pkTradetype)) {// 采购订单
			// SQL查询出单据主键
			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 + "不存在！");
			}
			if (headerVO.getForderstatus() != 1) {
				throw new Exception("单据号:" + vbillcode + "单据状态不允许审批！");
			}
			// 根据主键查询AggVO
			OrderVO aggvo = (OrderVO) service.queryBillOfNCObjectByPKWithDR(OrderVO.class, headerVO.getPk_order(), true).getContainmentObject();
			// 调用单据审批
			IWorkflowMachine iworkmachine = NCLocator.getInstance().lookup(IWorkflowMachine.class);// 工作流
			WorkflownoteVO workflownoteVO = iworkmachine.checkWorkFlow("APPROVE", "21", aggvo, null);
			workflownoteVO.setApproveresult("Y");// 审批意见
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			ipf.processAction("APPROVE", "21", workflownoteVO, aggvo, null, null);
		}
	}

}
