package nc.itf.fa.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

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

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.comn.NetStreamContext;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.hz.utils.BillInfoQueryUtil;
import nc.bs.hz.utils.HzJson2ObjectUtil;
import nc.bs.hz.utils.SafeObject;
import nc.bs.hz.utils.SendUtil;
import nc.bs.logging.Logger;
import nc.itf.fa.byzlog.IbyzLogRcord;
import nc.itf.fa.prv.IDeployOut;
import nc.itf.uap.pf.IPFBusiAction;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.fa.asset.AssetVO;
import nc.vo.fa.assetcard.CardVO;
import nc.vo.fa.assetcard.CardhistoryVO;
import nc.vo.fa.byzLogVO.ByzLogRcordVO;
import nc.vo.fa.deployout.DeployOutBodyVO;
import nc.vo.fa.deployout.DeployOutHeadVO;
import nc.vo.fa.deployout.DeployOutVO;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.uif2.LoginContext;
import nccloud.framework.service.ServiceLocator;
import nccloud.pubitf.fa.deploy.deployout.IDeployOut4Cloud;
import uap.json.JSONArray;
import uap.json.JSONObject;

public class ByzSysAmCallOutServlet implements IHttpServletAdaptor {
	private HzJson2ObjectUtil json2Object;
	private BaseDAO baseDAO;
	private UFDate business_date;
	private String org;

	
	public HzJson2ObjectUtil getJson2Object() {
		if (json2Object == null) {
			json2Object = new HzJson2ObjectUtil();
		}
		return json2Object;
	}

	@Override
	public void doAction(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 后台模拟用户登录
		ISecurityTokenCallback tc = NCLocator.getInstance().lookup(ISecurityTokenCallback.class);
		  byte[] tokens = tc.token("__system".getBytes(), "NC".getBytes());
		  NetStreamContext.setToken(tokens);
//		NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(), "pfxx".getBytes());
		Logger.info("调用资产调出新增！！");

		JSONObject resultjson = new JSONObject();
		String pk_deployout = "";
		JSONObject pk_deployout_b = new JSONObject();

		String bill_code = "";
		String guid = "";
		Map<String, Object> jsonMap = null;
		String reqJson = null;
		try {

			reqJson = requestJson(request);
			JSONObject json = new JSONObject(reqJson);
			jsonMap = json.getHashMap();
			String appid = (String) jsonMap.get("appid");
			String time = (String) jsonMap.get("time");
			String token = (String) jsonMap.get("token");

			JSONObject head = (JSONObject) ((JSONObject) jsonMap.get("data")).get("head");
			JSONArray body = (JSONArray) ((JSONObject) jsonMap.get("data")).get("bodys");
			guid = (String) head.get("def2");			
			BillInfoQueryUtil.initEnvironment("0001H810000000000HS2", new UFDate(head.getString("business_date")));
			BillInfoQueryUtil.initSysBilltypeCache(new String[] { "HG", "HF", "HC", "HC-01", "HD", "HD-01" });
			selectByUID(guid);
			DeployOutVO aggvo = new DeployOutVO();
			DeployOutHeadVO processHeadData = processingHeaderData(head);
			aggvo.setParent(processHeadData);
			DeployOutBodyVO[] processBodyDatas = processingBodyData(body);
			aggvo.setChildrenVO(processBodyDatas);


			InvocationInfoProxy.getInstance().setGroupId("0001H810000000000HS2");

			LoginContext context = new LoginContext();
			context.setPk_group(InvocationInfoProxy.getInstance().getGroupId());
			context.setPk_loginUser(InvocationInfoProxy.getInstance().getUserId());
			NCLocator.getInstance().lookup(IDeployOut.class).insert(null, aggvo);
			
//			IDeployOut4Cloud service2 = (IDeployOut4Cloud)ServiceLocator.find(IDeployOut4Cloud.class);
//			DeployOutVO[] insertVo= service2.insert(new DeployOutVO[]{aggvo});
			
			IPFBusiAction baService = (IPFBusiAction) NCLocator.getInstance().lookup(IPFBusiAction.class.getName());

			//DeployOutVO ss = (DeployOutVO)baService.processAction("SAVE", "HC", null, aggvo, context, null);
		
			DeployOutVO aggv =  null;
			String pk = aggvo.getPrimaryKey();
			DeployOutVO[] deployOutVO = NCLocator.getInstance().lookup(IDeployOut.class).queryDeployOutVOByPKs(pk);
			boolean approvalProcess = nccloud.bs.pub.pf.CloudPfUtil.hasApproveflowDef("HC-01",
					deployOutVO[0]);
			if (!approvalProcess) {// 如果没有审批流
				baService.processAction("APPROVE", "HC", null, aggvo, context, null);
			} else 
			{
				aggv = (DeployOutVO)baService.processAction("SAVE", "HC", null, aggvo, context, null);
			}

			/**
			 * 此处Json串无单据状态会报空指针异常,建议先执行前就添加成自由态0,之后进行正常的保存提交流程
			 */

			pk_deployout = aggvo.getParentVO().getPrimaryKey();
			DeployOutBodyVO[] deployOutBody  = (DeployOutBodyVO[]) aggvo.getChildrenVO();
			for(int i=0;i<deployOutBody.length;i++) {
				pk_deployout_b.put("bodypk"+i, deployOutBody[i].getPk_deployout_b());
			}
			bill_code = ((DeployOutHeadVO) aggvo.getParentVO()).getBill_code();
			resultjson.put("guid", guid);
			resultjson.put("billpk", pk_deployout);
			resultjson.put("billno", bill_code);			
			resultjson.put("billBodyPk", pk_deployout_b);
			resultjson.put("status", 1);
			resultjson.put("message", "资产调出新增成功。");
		} catch (Exception e) {
			Logger.error(e.getMessage(), e);
			resultjson.put("guid", guid);
			resultjson.put("billpk", pk_deployout);
			resultjson.put("billBodyPk", pk_deployout_b);
			resultjson.put("billno", bill_code);
			resultjson.put("status", 0);
			resultjson.put("message", e.getMessage());
		} finally {
			responseWriter(response, resultjson.toString());
			IbyzLogRcord ibyzLogRcord = (IbyzLogRcord) NCLocator.getInstance().lookup(IbyzLogRcord.class);
			ByzLogRcordVO byzLogRcordVO = new ByzLogRcordVO();
			byzLogRcordVO.setVbillcode(bill_code);
			byzLogRcordVO.setItf_type("资产调出新增");
			byzLogRcordVO.setItfclass("nc.itf.fa.servlet.ByzSysAmCallOutServlet");
			byzLogRcordVO.setByztonccparam(SendUtil.unicodeToString(reqJson));
			String resjson = SendUtil.unicodeToString(resultjson.toString());
			byzLogRcordVO.setNcctobyzresult(resjson);
			try {
				ibyzLogRcord.RcordLogBYZ__RequiresNew(byzLogRcordVO);
			} catch (BusinessException e) {
				Logger.error(e.getMessage(), e);
				Logger.error("日志生成失败！！nc.itf.fa.byzlog.IbyzLogRcord");

			}

		}
	}

	public String requestJson(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		try {
			request.setCharacterEncoding("utf-8");
			BufferedReader reader = request.getReader();
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public void responseWriter(HttpServletResponse response, String returnJson) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "application/json; charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.write(returnJson);
		writer.close();
	}

	/**
	 * 处理表头信息
	 * 
	 * @param head
	 * @return
	 * @throws Exception
	 */
	private DeployOutHeadVO processingHeaderData(JSONObject head) throws Exception {
		DeployOutHeadVO headVO = getJson2Object().json2Object(head, DeployOutHeadVO.class);
		headVO.setStatus(VOStatus.NEW);
		headVO.setBill_type("HC");
		headVO.setTransi_type("HC-01");
		headVO.setPk_transitype("0001H81000000000DN9L");
		headVO.setPk_group("0001H810000000000HS2");
		
		headVO.setDef10(headVO.getDef1());
		headVO.setDef11(headVO.getDef2());
		
		headVO.setDef1(null);
		headVO.setDef2(null);
		
		
		OrgVO pk_org = BillInfoQueryUtil.selectOrgByPK((String) head.get("pk_org"));
		if (pk_org != null) {
			headVO.setPk_org_v(pk_org.getPk_vid());
		}

		OrgVO pk_org_in = BillInfoQueryUtil.selectOrgByPK((String) head.get("pk_org_in"));
		if (pk_org_in != null) {
			headVO.setPk_org_in_v(pk_org_in.getPk_vid());
		}
		headVO.setBillmaketime(new UFDateTime());
		headVO.setBill_status(0);// 单据状态
		headVO.setBillmaker(BillInfoQueryUtil.getPK_syscreater());//制单人

		if ("是".equals(head.getString("confirm_flag")))// 是否本月确认调入
			headVO.setConfirm_flag(new UFBoolean("Y"));
		
		if(BillInfoQueryUtil.isSameDef51(headVO.getPk_org(),headVO.getPk_org_in()))
			headVO.setDef12("Y");
		//add by djy 20220319
		else
			headVO.setDef12("N");
		
		headVO.setAccount_currency(BillInfoQueryUtil.getBdcurrtypenameByName(head.getString("account_currency")));// 币种
		business_date=headVO.getBusiness_date();
		org=headVO.getPk_org();
		return headVO;
	}
	private DeployOutVO[] getInsertVos(Object[] vos) {
		List<DeployOutVO> res = new ArrayList();
		 Object[] var3 = vos;      int var4 = vos.length;
		for(int var5 = 0; var5 < var4; ++var5) {         Object vo = var3[var5];
		if (vo instanceof DeployOutVO) {
		DeployOutVO tvo = (DeployOutVO)vo;
		  res.add(tvo);
		     }
		  }
	
		     return (DeployOutVO[])res.toArray(new DeployOutVO[0]);
	 }
	/**
	 * 处理表体信息
	 * 
	 * @param body
	 * @return
	 * @throws NoSuchElementException
	 * @throws Exception
	 */
	private DeployOutBodyVO[] processingBodyData(JSONArray body) throws NoSuchElementException, Exception {
		DeployOutBodyVO[] bodyVolist = new DeployOutBodyVO[body.length()];
		for (int i = 0; i < body.length(); i++) {
			DeployOutBodyVO bodyVO = getJson2Object().json2Object(body.getJSONObject(i), DeployOutBodyVO.class);
			//add by dxr
			CardhistoryVO cardhistoryVO = BillInfoQueryUtil.getFaCardHistory(bodyVO.getPk_card());
			//add by djy20220402 算实际的累计折旧
			Map<String, Object> mapdep=new HashMap<String, Object>();
			String[] pks=new String[] {bodyVO.getPk_card()};
			String accbook=BillInfoQueryUtil.getAccountingbook(org);
			mapdep=BillInfoQueryUtil.handlerDep(pks,"0001H810000000000HS2",
					org,accbook,business_date,UFBoolean.FALSE);
			if(mapdep.get("simulateAccudep")==null||
					((HashMap)mapdep.get("simulateAccudep")).get(bodyVO.getPk_card())==null)
				throw new Exception("计算累计折旧有误，请联系管理员");			
			cardhistoryVO.setAccudep((UFDouble) ((HashMap)mapdep.get("simulateAccudep")).get(bodyVO.getPk_card()));
			
			
			AssetVO cardVO = BillInfoQueryUtil.getFaCard(bodyVO.getPk_card());
			if (cardhistoryVO != null) {
				bodyVO.setDeploy_price(cardhistoryVO.getOriginvalue());
				bodyVO.setDeploy_accudep(cardhistoryVO.getAccudep());
				bodyVO.setDeploy_pdaluate(cardhistoryVO.getPredevaluate());
				//净值
				UFDouble jz = cardhistoryVO.getLocaloriginvalue() == null ? new UFDouble("0.00")
						: cardhistoryVO.getLocaloriginvalue()
								.sub(cardhistoryVO.getAccudep() == null ? new UFDouble("0.00")
										: cardhistoryVO.getAccudep());
				//净额
				UFDouble je = jz.sub(cardhistoryVO.getPredevaluate() == null ? new UFDouble("0.00")
						: cardhistoryVO.getPredevaluate());
				bodyVO.setNetvalue(jz);
				bodyVO.setNetrating(je);
//				bodyVO.setSimulatedep(cardhistoryVO.getAccudep());
				bodyVO.setAccudep(cardhistoryVO.getAccudep());
				bodyVO.setUsemonth(cardhistoryVO.getUsedmonth());
				bodyVO.setRed_accudep(cardhistoryVO.getAccudep());
			}
			bodyVO.setPk_addreducestyle(
					BillInfoQueryUtil.getFaAddOrReduceStyle(bodyVO.getPk_addreducestyle()));
			bodyVolist[i] = bodyVO;
		}
		return bodyVolist;
	}
	private void selectByUID(String src_id) throws BusinessException {
		String sql = "select count(pk_deployout) from fa_deployout where def11 = '"+src_id+"' and dr = 0";
		Integer number = (Integer)getBaseDAO().executeQuery(sql, new ColumnProcessor());
		if(number != 0) {
			 throw new BusinessException("该来源单据号NCC已存在：" + src_id);
		}
	}
	private BaseDAO getBaseDAO() {
		if (baseDAO == null) {
			baseDAO = new BaseDAO();
		}
		return baseDAO;
	}
}
