package nc.bs.arap.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.uap.pf.IPFBusiAction;
import nc.log.NcLog;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.arap.pay.PayBillItemVO;
import nc.vo.arap.pay.PayBillVO;
import nc.vo.org.FinanceOrgVO;
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.pub.workflownote.WorkflownoteVO;

/**
 * 预付单 2024-10-30
 */
public class PrepayBillImpl extends BaseServlet implements IHttpServletAdaptor{

	@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());
			billno = json.getString("billno");
//			InvocationInfoProxy.getInstance().setUserDataSource("NC6337");
			GetDataUtil.getPayBillno(billno);
			checkJson(json);
			AggPayBillVO aggPayBillVO = new AggPayBillVO ();
			PayBillVO payBillVO = new PayBillVO();
			String userPK = GetDataUtil.getUserPK(json.getString("billmaker"));
			String pk_group = GetDataUtil.getGroupPK(json.getString("pk_group"));
			
			InvocationInfoProxy.getInstance().setUserId(userPK);//用户主键
			InvocationInfoProxy.getInstance().setGroupId(pk_group);//指定集团pk
			//集团
			payBillVO.setPk_group(pk_group);
			String pk_tradetype = json.getString("pk_tradetype");
			//付款单类型编码
			payBillVO.setPk_tradetype(pk_tradetype);
			String pk_billtypeid = GetDataUtil.getBilltypePK(pk_tradetype,pk_group);
			//付款类型
			payBillVO.setPk_tradetypeid(pk_billtypeid);
			FinanceOrgVO financeOrgVO = GetDataUtil.getFinanceOrgVO(json.getString("pk_org"));
			//财务组织
			payBillVO.setPk_fiorg(financeOrgVO.getPk_financeorg());
			//废弃财务组织版本 
//			payBillVO.setPk_fiorg_v(financeOrgVO.getPk_vid());
			//付款财务组织
			payBillVO.setPk_org(financeOrgVO.getPk_financeorg());
			//付款财务组织版本
			payBillVO.setPk_org_v(financeOrgVO.getPk_vid());
			//结算财务组织
			payBillVO.setSett_org(financeOrgVO.getPk_financeorg());
			//结算财务组织版本
			payBillVO.setSett_org_v(financeOrgVO.getPk_vid());
			//业务组织
			payBillVO.setPu_org(financeOrgVO.getPk_financeorg());
			//业务组织版本
			payBillVO.setPu_org_v(financeOrgVO.getPk_vid());
			//单据编号
			payBillVO.setBillno(json.getString("billno"));
			//单据日期
			payBillVO.setBilldate(new UFDate(json.getString("billdate")));
			if("F3-Cxx-04".equals(pk_tradetype)) {//对外预付款(非项目)
				//起算日期
				payBillVO.setBusidate(new UFDate(json.getString("busidate")));	
			}else {//对外预付款(项目)
				//起算日期
				payBillVO.setBusidate(new UFDate(json.getString("billdate")));	
			}	
			//员工编号
			payBillVO.setDef13(json.getString("def13"));
			//建议付款日期
			payBillVO.setDef13(json.getString("def3"));
			//合计金额
			payBillVO.setLocal_money(new UFDouble(json.getString("local_money")));
			//费用承担部门
			payBillVO.setDef5(GetDataUtil.getDeptPK(json.getString("def5")));
			//预算所在部门
			payBillVO.setDef20(GetDataUtil.getDeptPK(json.getString("def20")));
			//组长审批
			payBillVO.setDef4(GetDataUtil.getPsndocPK(json.getString("def4")));
			//是否打印备注
			payBillVO.setDef1(GetDataUtil.getDefdocPK(json.getString("def1"), "19", "是否打印备注"));
			//制单人
			payBillVO.setBillmaker(userPK);
			//创建人
			payBillVO.setCreator(userPK);
			//创建时间
			payBillVO.setCreationtime(new UFDateTime(json.getString("billdate")));
			String pk_dept = GetDataUtil.getDeptPK(json.getString("pk_deptid"));
			//业务部门
			payBillVO.setPu_deptid(pk_dept);	
			String pk_vid = GetDataUtil.getDeptVPK(json.getString("pk_deptid_v"));
			if(pk_vid == null) {
				pk_vid = GetDataUtil.getDeptVPK(json.getString("pk_deptid"));
			}
			//部门版本信息
//			payBillVO.setPk_deptid_v(pk_vid);
			//业务部门版本
//			payBillVO.setPu_deptid_v(pk_vid);	
			//业务流程
			payBillVO.setPk_busitype(GetDataUtil.getBusitypePK(json.getString("pk_busitype")));
			//付款部门
			payBillVO.setPk_deptid(GetDataUtil.getDeptPK(json.getString("pk_deptid")));
			//对方单位名称
			payBillVO.setSupplier(GetDataUtil.getSupplierPK(json.getString("supplier")));
			//组织本币金额
			payBillVO.setLocal_money(new UFDouble(json.getString("local_money")));
			//原币金额
			payBillVO.setMoney(new UFDouble(json.getString("local_money")));
			String recaccount = GetDataUtil.getBankaccsubPK(json.getString("recaccount"));
			//对方单位银行账户
			payBillVO.setRecaccount(recaccount);
			//对方单位开户行
			payBillVO.setDef25(json.getString("def25"));
			//附件张数
			payBillVO.setAccessorynum(Integer.parseInt(json.getString("accessorynum")));
			//单据会计年度
			payBillVO.setBillyear(json.getString("billyear"));
			//单据会计期间
			payBillVO.setBillperiod(json.getString("billperiod"));
			String payaccount = GetDataUtil.getBankaccsubPK(json.getString("payaccount"));
			//付款银行账户
			payBillVO.setPayaccount(payaccount);   
			String pk_currtype = GetDataUtil.getCurrtypePK(json.getString("pk_currtype"));
			//币种
			payBillVO.setPk_currtype(pk_currtype);
			String pk_psndoc = GetDataUtil.getPsndocPK(json.getString("pk_psndoc"));
			//业务员
//			payBillVO.setPk_psndoc(pk_psndoc); //数据库没存
			//业务人员
//			payBillVO.setPu_psndoc(pk_psndoc); //数据库没存
			//单据确认人
//			payBillVO.setConfirmuser(pk_psndoc); //数据库不赋值
			//审批状态
			payBillVO.setApprovestatus(-1);
			//单据来源系统 默认来源采购系统
			payBillVO.setSrc_syscode(Integer.parseInt(json.getString("src_syscode")));	
			//是否打印备注
			payBillVO.setDef1(GetDataUtil.getDefdocPK(json.getString("def1"), "19", "是否打印备注"));
			//建议付款日期
			payBillVO.setDef3(json.getString("def3"));	
			//组长审批
			payBillVO.setDef4(GetDataUtil.getPsndocPK(json.getString("def4")));
			//费用承担部门
			payBillVO.setDef5(GetDataUtil.getDeptPK(json.getString("def5")));
			//来源单号
			payBillVO.setDef15(json.getString("def15"));
			//预算所在部门
			payBillVO.setDef20(GetDataUtil.getDeptPK(json.getString("def20")));		
			//单据类型编码
			payBillVO.setPk_billtype("F3");
			//单据大类
			payBillVO.setBillclass("fk");
			//国家地区 默认CN
			String pk_country = GetDataUtil.getCountryzonePK("CN");
			payBillVO.setRececountryid(pk_country);
			//报税国 默认CN
			payBillVO.setTaxcountryid(pk_country);
			//单据所属系统 默认所属付款系统
			payBillVO.setSyscode(1);			
			//结算方式 取表体第一行赋给表头
			payBillVO.setPk_balatype(GetDataUtil.getBalatypePK(json.getJSONArray("childrenVO").getJSONObject(0).getString("pk_balatype")));
			payBillVO.setBillstatus(-1);
//			payBillVO.setStatus(2);		
			//是否红冲过
			payBillVO.setIsreded(UFBoolean.FALSE);
			//是否流程单据
			payBillVO.setIsflowbill(UFBoolean.FALSE);
			aggPayBillVO.setParentVO(payBillVO);
			List<PayBillItemVO> listPayBillItemVO = new ArrayList<PayBillItemVO>();
			JSONArray josns = json.getJSONArray("childrenVO");
			for (int i = 0; i < josns.size(); i++) {
				PayBillItemVO payBillItemVO = new PayBillItemVO();
				JSONObject item = josns.getJSONObject(i);
				//所属集团
				payBillItemVO.setPk_group(pk_group);
				//结算财务组织
				payBillItemVO.setSett_org(financeOrgVO.getPk_financeorg());
				//结算财务组织版本 
				payBillItemVO.setSett_org_v(financeOrgVO.getPk_vid());
				//付款财务组织
				payBillItemVO.setPk_org(financeOrgVO.getPk_financeorg());
				//付款财务组织版本
				payBillItemVO.setPk_org_v(financeOrgVO.getPk_vid());
				//废弃财务组织
				payBillItemVO.setPk_fiorg(financeOrgVO.getPk_financeorg());
				//废弃财务组织版本 
//				payBillItemVO.setPk_fiorg_v(financeOrgVO.getPk_vid());
				//业务员
				payBillItemVO.setPk_psndoc(pk_psndoc);
				//业务人员
//				payBillItemVO.setPu_psndoc(pk_psndoc);
				//业务部门
//				payBillItemVO.setPu_deptid(pk_dept);
				//业务部门版本
//				payBillItemVO.setPu_deptid_v(pk_vid);
				//业务组织
				payBillItemVO.setPu_org(financeOrgVO.getPk_financeorg());
				//业务组织版本
				payBillItemVO.setPu_org_v(financeOrgVO.getPk_vid());
				//付款性质--1预付款
				payBillItemVO.setPrepay(1);
				//物料
				payBillItemVO.setMaterial(GetDataUtil.getMaterialPK(item.getString("material")));
				//供应商--对方单位名称
				payBillItemVO.setSupplier(GetDataUtil.getSupplierPK(item.getString("supplier")));
				//票据方向checkdirection
//				payBillItemVO.setCheckdirection("ap");
				//单据日期
				payBillItemVO.setBilldate(new UFDate(json.getString("billdate")));
				//单据类型编码
				payBillItemVO.setPk_billtype("F3");
				//单据大类
				payBillItemVO.setBillclass("fk");
				//付款类型code
//				payBillItemVO.setPk_tradetype(pk_tradetype);
				//付款类型
//				payBillItemVO.setPk_tradetypeid(pk_billtypeid);
				//起算日期
				if("F3-Cxx-04".equals(pk_tradetype)) {
					//起算日期
					payBillItemVO.setBusidate(new UFDate(json.getString("busidate")));	
				}else {
					//起算日期
					payBillItemVO.setBusidate(new UFDate(json.getString("billdate")));	
				}
				//预算编号
				payBillItemVO.setDef1(item.getString("pk_subjcode"));
				//预算名称
				payBillItemVO.setPk_subjcode(GetDataUtil.getInoutbusiclassPK(item.getString("pk_subjcode")));
				//单据号
				payBillItemVO.setBillno(json.getString("billno"));
				//往来对象
				payBillItemVO.setObjtype(Integer.parseInt(item.getString("objtype")));
				//单据分录号--行号
				payBillItemVO.setRowno(Integer.parseInt(item.getString("rowno")));
				//行类型
				payBillItemVO.setRowtype(0);
				//方向 默认贷方
				payBillItemVO.setDirection(-1);
				//摘要
				payBillItemVO.setDef25(GetDataUtil.getDefdocPK(item.getString("def25"), "999", "摘要"));
				//币种
				payBillItemVO.setPk_currtype(pk_currtype);
				//税率
				payBillItemVO.setTaxrate(new UFDouble(item.getString("taxrate")));
				//付款部门
				payBillItemVO.setPk_deptid("".equals(item.getString("pk_deptid")) ? pk_dept : GetDataUtil.getDeptPK(item.getString("pk_deptid")));
				//部门版本
				payBillItemVO.setPk_deptid_v(pk_vid);
				//组织本币余额
				payBillItemVO.setLocal_money_bal(new UFDouble(item.getString("local_money_bal")));
				//组织本币金额(借方)
				payBillItemVO.setLocal_money_de(new UFDouble(item.getString("local_money_de")));
				//组织本币无税金额(借方)
				payBillItemVO.setLocal_notax_de(new UFDouble(item.getString("local_notax_de")));
				//税额
				payBillItemVO.setLocal_tax_de(new UFDouble(item.getString("local_tax_de")));
				//原币余额
				payBillItemVO.setMoney_bal(new UFDouble(item.getString("local_mony_bal")));
				//借方原币金额
				payBillItemVO.setMoney_de(new UFDouble(item.getString("local_money_de")));
				//借方原币无税金额
				payBillItemVO.setNotax_de(new UFDouble(item.getString("local_notax_de")));
				//结算方式
				payBillItemVO.setPk_balatype(GetDataUtil.getBalatypePK(item.getString("pk_balatype")));
				//项目名称
				payBillItemVO.setProject(GetDataUtil.getprojectPK(item.getString("project")));
				//项目编码
				payBillItemVO.setDef18(item.getString("project"));
				//备注
				payBillItemVO.setDef2(item.getString("def2"));
				//票据/保理/售出编号
				payBillItemVO.setDef5(item.getString("def5"));
				//专业
				payBillItemVO.setDef6(GetDataUtil.getDefdocPK(item.getString("def6"), "HR016", "专业"));
				//费用事项
				payBillItemVO.setDef7(GetDataUtil.getDefdocPK(item.getString("def7"), "88", "费用事项"));
				//汇款附言
				payBillItemVO.setDef21(item.getString("def21"));
				//预算所在部门
				payBillItemVO.setDef29(GetDataUtil.getDeptPK(item.getString("def29")));
									
				//上层单据号
				String vsourcecode = item.getString("vsourcecode");
				if(!"".equals(vsourcecode)) {
					//上层单据类型
					String  top_billtype = item.getString("top_billtype");
					//上层单据行号
					String vsourcerowno = item.getString("vsourcerowno");
					Map<String,String> map = GetDataUtil.getDataMap(top_billtype, vsourcecode, vsourcerowno);
					//上层单据主键
					payBillItemVO.setTop_billid(map.get("pk_id"));
					//上层单据行主键
					payBillItemVO.setTop_itemid(map.get("pk_id_b"));
					//上层单据类型
					payBillItemVO.setTop_billtype(top_billtype);
					//上层交易类型
					payBillItemVO.setTop_tradetype(GetDataUtil.getBilltypePK(item.getString("top_tradetype"), pk_group));
				}
				
				//源头单据号
				String vfirstcode = item.getString("vfirstcode");
				if(!"".equals(vfirstcode)) {
					//源头单据类型
					String  src_billtype = item.getString("src_billtype");
					//源头单据行号
					String vfirstrowno = item.getString("vfirstrowno");
					Map<String,String> map = GetDataUtil.getDataMap(src_billtype, vfirstcode, vfirstrowno);
					//源头单据主键
					payBillItemVO.setSrc_billid(map.get("pk_id"));
					//源头单据行主键
					payBillItemVO.setSrc_itemid(map.get("pk_id_b"));
					//源头单据类型
					payBillItemVO.setSrc_billtype(src_billtype);
					//源头交易类型
					payBillItemVO.setSrc_tradetype(GetDataUtil.getBilltypePK(item.getString("src_tradetype"), pk_group));
				}
				//rate组织本币汇率 
				payBillItemVO.setRate(new UFDouble(1));
				//收款银行账户
				payBillItemVO.setRecaccount(recaccount);
				//付款银行账户
				payBillItemVO.setPayaccount(payaccount);
				//订单号
				payBillItemVO.setPurchaseorder(item.getString("purchaseorder"));
				//费用归属
				payBillItemVO.setDef30(GetDataUtil.getDefdocPK(item.getString("def30"), "05", "费用归属"));
				//是否逆向征税
				payBillItemVO.setOpptaxflag(UFBoolean.FALSE);
				payBillItemVO.setStatus(2);
				listPayBillItemVO.add(payBillItemVO);
			}
			aggPayBillVO.setChildrenVO(listPayBillItemVO.toArray(new PayBillItemVO[listPayBillItemVO.size()]));
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Object dateTimeString  = payBillVO.getBilldate();
			if(dateTimeString != null) {
			    Date date = format.parse(dateTimeString.toString());
			    long timestamp = date.getTime();
			    InvocationInfoProxy.getInstance().setBizDateTime(timestamp);
			 }
			
			WorkflownoteVO Workflownote = new WorkflownoteVO();
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			ipf.processAction("SAVE", "F3", Workflownote, aggPayBillVO, null, null);
			resp.getWriter().write(formatRSJsonData("成功", "", 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);
		}
		
	}
	
	private void checkJson(JSONObject json) throws Exception {
		
		StringBuffer mags = new StringBuffer();
		Boolean empty = true;
		
		String pk_group = "pk_group";
		String pk_tradetype = "pk_tradetype";
		String pk_org = "pk_org";
		String billno = "billno";
		String billdate = "billdate";
		String billmaker = "billmaker";
		String local_money = "local_money";
		String accessorynum = "accessorynum";
		String pk_busitype = "pk_busitype";
		String billyear = "billyear";
		String billperiod = "billperiod";
		String pk_currtype = "pk_currtype";
		String src_syscode = "src_syscode";
		String supplier = "supplier";
		String recaccount = "recaccount";
	
		String body = "childrenVO";//表体
		String[] HeadKey = {pk_group,pk_tradetype,pk_org,billno,billdate,billmaker,local_money,accessorynum,
				pk_busitype,billyear,billperiod,pk_currtype,src_syscode,supplier,recaccount};
		
		for (String as : HeadKey) {

			if (json.getString(as).isEmpty()) {
				empty = false;
				mags.append("'" + as + "'");
			}
		}
		if (json.getJSONArray(body)==null) {
			empty = false;
			mags.append("表体不存在！ ");
		}
		
		JSONArray childrenVO = json.getJSONArray("childrenVO");
		
		if (childrenVO == null || childrenVO.size() == 0) {
			throw new Exception("表体内容不可为空！");
		}
		
		String local_money_bal = "local_money_bal";
		String local_money_de = "local_money_de";
		String local_notax_de = "local_notax_de";
		String local_tax_de = "local_tax_de";
		String taxrate = "taxrate";
		String objtype = "objtype";
		String rowno = "rowno";
		for(int i = 0; i < childrenVO.size(); i++) {
			
			JSONObject oprepJsonObjectB = childrenVO.getJSONObject(i);
			String[] BodyKey = {local_money_bal,local_money_de,local_notax_de,local_tax_de,taxrate,objtype,rowno};
			int num = i+1;
			
			mags.append("第"+num+"块表体：{");
			for (String as : BodyKey) {
				if (oprepJsonObjectB.getString(as).isEmpty()) {
					empty = false;
					mags.append("'" + as + "' ");
				}
			}
			mags.append("}");
		}
		if (!empty) {
			throw new Exception("以下字段不可为空："+mags);
		}
	}
	

}
