package nc.impl.th;

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.HashMap;
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.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.pu.plugin.DataUtils.QueryDataUtil;
import nc.bs.scmpub.pf.PfParameterUtil;
import nc.bs.servlet.service.BaseServlet;
import nc.itf.pu.m21.IOrderApprove;
import nc.itf.pu.m21.IOrderMaintain;
import nc.itf.uap.pf.IPFBusiAction;
import nc.itf.uap.pf.IWorkflowMachine;
import nc.log.NcLog;
import nc.vo.bd.material.MaterialVO;
import nc.vo.ct.purdaily.entity.CtPuBVO;
import nc.vo.org.PurchaseOrgVO;
import nc.vo.pu.m21.entity.OrderHeaderVO;
import nc.vo.pu.m21.entity.OrderItemVO;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pub.workflownote.WorkflownoteVO;
import nc.vo.util.CloneUtil;

/**
 * 采购订单
 * @author Yaoyu
 *
 */
public class OrderAddImpl extends BaseServlet implements IHttpServletAdaptor {

	@Override
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String vbillcode = "";
		try {
			NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());
			String createStr = buildJson(req, resp, this.getClass().getName());
			NcLog.info("采购订单："+ createStr);
			JSONObject json = JSON.parseObject(createStr);
			vbillcode = json.getString("vbillcode");
			InvocationInfoProxy.getInstance().setUserDataSource("NC6337");
			QueryDataUtil.getBillno(vbillcode);
			checkJson(json);
			OrderVO orderVO = new OrderVO();
			OrderHeaderVO orderHeaderVO = new OrderHeaderVO();
			String userPK = QueryDataUtil.getUserPK(json.getString("billmaker"));
			String pk_group = QueryDataUtil.getGroupPK(json.getString("pk_group"));

			InvocationInfoProxy.getInstance().setUserId(userPK);//用户主键
			InvocationInfoProxy.getInstance().setGroupId(pk_group);//指定集团pk
			//制单人
			orderHeaderVO.setBillmaker(userPK);
			//审批人即制单人
			orderHeaderVO.setApprover(userPK);
			//币种
			orderHeaderVO.setCorigcurrencyid(QueryDataUtil.getCurrtypePK(json.getString("corigcurrencyid")));
			//订单类型
			orderHeaderVO.setCtrantypeid(QueryDataUtil.getBilltypePK(json.getString("vtrantypecode")));
			//订单日期
			orderHeaderVO.setDbilldate(new UFDate(json.getString("dbilldate")));
			//制单日期
			orderHeaderVO.setDmakedate(new UFDate(json.getString("dmakedate")));
			//审批日期即制单时间
			orderHeaderVO.setTaudittime(orderHeaderVO.getDmakedate());
			//整单扣税类别
			orderHeaderVO.setFhtaxtypeflag(Integer.parseInt(json.getString("fhtaxtypeflag")));
			//总数量
			orderHeaderVO.setNtotalastnum(new UFDouble(json.getString("ntotalastnum")));
			//价税合计
			orderHeaderVO.setNtotalorigmny(new UFDouble(json.getString("ntotalorigmny")));
			//业务流程
			orderHeaderVO.setPk_busitype(QueryDataUtil.getBusitypePK(json.getString("pk_busitype")));
			//采购员-计划员
			orderHeaderVO.setCemployeeid(QueryDataUtil.getPsndocPK(json.getString("cemployeeid")));
			//采购部门最新版本-计划部门
			orderHeaderVO.setPk_dept(QueryDataUtil.getDeptVPK(json.getString("pk_dept")));
			//采购部门-计划部门
			orderHeaderVO.setPk_dept_v(orderHeaderVO.getPk_dept());
			//集团
			orderHeaderVO.setPk_group(pk_group);
			//开票供应商
			orderHeaderVO.setPk_invcsupllier(QueryDataUtil.getSupplierPK(json.getString("pk_invcsupllier")));
			//供应商
			orderHeaderVO.setPk_supplier(orderHeaderVO.getPk_invcsupllier());
			//开户银行
			orderHeaderVO.setPk_bankdoc(QueryDataUtil.getBankaccsubPK(json.getString("payaccount"),orderHeaderVO.getPk_invcsupllier()));
			PurchaseOrgVO purchaseOrgVO = QueryDataUtil.getFinanceOrgVO(json.getString("pk_org"));
			//采购组织版本
			orderHeaderVO.setPk_org(purchaseOrgVO.getPk_purchaseorg());
			//采购组织
			orderHeaderVO.setPk_org_v(purchaseOrgVO.getPk_vid());
			//订单号
			orderHeaderVO.setVbillcode(vbillcode);
			//备注
			orderHeaderVO.setVmemo(json.getString("vmemo"));
			//订单类型
			orderHeaderVO.setVtrantypecode(json.getString("vtrantypecode"));
			//是否需要投标
			orderHeaderVO.setVdef2(QueryDataUtil.getDefdocPK(json.getString("vdef2"), "11", "是否需要投标"));
			//有无框架协议
			orderHeaderVO.setVdef3(QueryDataUtil.getDefdocPK(json.getString("vdef3"), "12", "有无框架协议"));
			//预算名称
			orderHeaderVO.setVdef5(QueryDataUtil.getInoutbusiclassPK(json.getString("vdef5")));
			//预算编码
			orderHeaderVO.setVdef9(json.getString("vdef5"));
			//付款计划简述
			orderHeaderVO.setVdef6(json.getString("vdef6"));
			//预算所在部门
			orderHeaderVO.setVdef7(QueryDataUtil.getDeptPK(json.getString("vdef7")));
			//供应商开户行
			orderHeaderVO.setVdef8(QueryDataUtil.getBankdocName(json.getString("payaccount"),orderHeaderVO.getPk_invcsupllier()));
			//是否有附件
			orderHeaderVO.setVdef10(QueryDataUtil.getDefdocPK(json.getString("vdef10"), "18", "是否有附件"));
			//收货人
			orderHeaderVO.setVdef15(QueryDataUtil.getPsndocPK(json.getString("vdef15")));
			//收货人联系电话
			orderHeaderVO.setVdef16(json.getString("vdef16"));
			//收货地址
			orderHeaderVO.setVdef17(QueryDataUtil.getDefdocPK(json.getString("vdef17"), "shdz", "收货地址"));
			//采购员
			orderHeaderVO.setVdef18(QueryDataUtil.getPsndocPK(json.getString("vdef18")));
			//采购部门
			orderHeaderVO.setVdef19(QueryDataUtil.getDeptPK(json.getString("vdef19")));
			orderHeaderVO.setStatus(2);
			orderHeaderVO.setForderstatus(3);
			orderVO.setParent(orderHeaderVO);
			JSONArray josns = json.getJSONArray("childrenVO");
			List<OrderItemVO> listOrderItemVO = new ArrayList<OrderItemVO>();
			for (int i = 0; i < josns.size(); i++) {
				JSONObject item = josns.getJSONObject(i);
				OrderItemVO orderItemVO = new OrderItemVO();
				
				//行号
				orderItemVO.setCrowno(item.getString("crowno"));
				String vcontractcode = item.getString("vcontractcode");
				Map<String,String> map = new HashMap<String,String>();
				if(!"".equals(vcontractcode)) {
					
					map = QueryDataUtil.getDataMap("Z2", vcontractcode, item.getString("vcontractcrowno"));
					//合同号
					orderItemVO.setVcontractcode(vcontractcode);
					//合同主键
					orderItemVO.setCcontractid(map.get("pk_id"));
					//合同表体主键
					orderItemVO.setCcontractrowid(map.get("pk_id_b"));
				}
				//本币币种
				orderItemVO.setCcurrencyid(QueryDataUtil.getCurrtypePK(item.getString("ccurrencyid")));
				//币种
				orderItemVO.setCorigcurrencyid(orderItemVO.getCcurrencyid());
				
				String vfirstcode = item.getString("vfirstcode");
				if(!"".equals(vfirstcode)) {
					String cfirsttypecode = item.getString("cfirsttypecode");
					String vfirstrowno = item.getString("vfirstrowno");
					map = QueryDataUtil.getDataMap(cfirsttypecode, vfirstcode, vfirstrowno);
					//源头单据号
					orderItemVO.setVfirstcode(vfirstcode);
					//源头单据
					orderItemVO.setCfirstid(map.get("pk_id"));
					//源头单据明细
					orderItemVO.setCfirstbid(map.get("pk_id_b"));
					//源头单据行号
					orderItemVO.setVfirstrowno(vfirstrowno);
					//源头交易类型
					orderItemVO.setVfirsttrantype(QueryDataUtil.getBilltypePK(item.getString("vfirsttrantype")));
					//源头单据类型
					orderItemVO.setCfirsttypecode(QueryDataUtil.getBilltypePK(cfirsttypecode));
				}
				
				String vsourcecode = item.getString("vsourcecode");
				if(!"".equals(vsourcecode)) {
					String vsourcerowno = item.getString("vsourcerowno");
					String csourcetypecode = item.getString("csourcetypecode");
					map = QueryDataUtil.getDataMap(csourcetypecode, vsourcecode, vsourcerowno);
					//来源单据号 
					orderItemVO.setVsourcecode(vsourcecode);
					//来源单据行号
					orderItemVO.setVsourcerowno(vsourcerowno);
					//来源交易类型
					orderItemVO.setVsourcetrantype(QueryDataUtil.getBilltypePK(item.getString("vsourcetrantype")));
					//来源单据
					orderItemVO.setCsourceid(map.get("pk_id"));
					//来源单据明细
					orderItemVO.setCsourcebid(map.get("pk_id_b"));
					//来源单据类型
					orderItemVO.setCsourcetypecode(QueryDataUtil.getBilltypePK(csourcetypecode));
				}
				//税码
				orderItemVO.setCtaxcodeid(QueryDataUtil.getTaxcodePK(item.getString("ctaxcodeid")));
				//税率
				orderItemVO.setNtaxrate(new UFDouble(item.getString("ntaxrate")));
				//主单位
				orderItemVO.setCunitid(QueryDataUtil.getMeasdocPK(item.getString("cunitid")));
				//单位
				orderItemVO.setCastunitid(orderItemVO.getCunitid());
				//报价单位
				orderItemVO.setCqtunitid(orderItemVO.getCunitid());
				//订单日期
				orderItemVO.setDbilldate(orderHeaderVO.getDbilldate());
				//计划到货日期
				orderItemVO.setDplanarrvdate(orderHeaderVO.getDbilldate());
				//购销类型
				orderItemVO.setFbuysellflag(Integer.parseInt(item.getString("fbuysellflag")));
				//扣税类别
				orderItemVO.setFtaxtypeflag(orderHeaderVO.getFhtaxtypeflag());
				//计税金额
				orderItemVO.setNcaltaxmny(new UFDouble(item.getString("ncaltaxmny")));
				//计成本金额
				orderItemVO.setNcalcostmny(orderItemVO.getNcaltaxmny());
				//折本汇率
				orderItemVO.setNexchangerate(new UFDouble(1));
				//折扣
				orderItemVO.setNitemdiscountrate(new UFDouble(100));
				
				//主数量
				orderItemVO.setNnum(new UFDouble(item.getString("nnum")));
				//数量
				orderItemVO.setNastnum(orderItemVO.getNnum());
				//报价数量
				orderItemVO.setNqtunitnum(orderItemVO.getNnum());
				
				//无税单价
				orderItemVO.setNqtorigprice(new UFDouble(item.getString("nqtorigprice")));
				//无税净价 
				orderItemVO.setNqtorignetprice(orderItemVO.getNqtorigprice());
				//主无税单价
				orderItemVO.setNorigprice(orderItemVO.getNqtorigprice());
				//主无税净价
				orderItemVO.setNorignetprice(orderItemVO.getNqtorigprice());
				//本币无税单价
				orderItemVO.setNqtprice(orderItemVO.getNqtorigprice());
				//本币无税净价
				orderItemVO.setNqtnetprice(orderItemVO.getNqtorigprice());
				//主本币无税单价
				orderItemVO.setNprice(orderItemVO.getNqtorigprice());
				//主本币无税净价
				orderItemVO.setNnetprice(orderItemVO.getNqtorigprice());
				//含税单价 
				orderItemVO.setNqtorigtaxprice(new UFDouble(item.getString("nqtorigtaxprice")));
				//含税净价
				orderItemVO.setNqtorigtaxnetprc(orderItemVO.getNqtorigtaxprice());
				//主含税单价
				orderItemVO.setNorigtaxprice(orderItemVO.getNqtorigtaxprice());
				//主含税净价
				orderItemVO.setNorigtaxnetprice(orderItemVO.getNqtorigtaxprice());
				//本币含税单价 
				orderItemVO.setNqttaxprice(orderItemVO.getNqtorigtaxprice());
				//本币含税净价
				orderItemVO.setNqttaxnetprice(orderItemVO.getNqtorigtaxprice());
				//主本币含税单价
				orderItemVO.setNtaxprice(orderItemVO.getNqtorigtaxprice());
				//主本币含税净价
				orderItemVO.setNtaxnetprice(orderItemVO.getNqtorigtaxprice());
				//税额
				orderItemVO.setNtax(new UFDouble(item.getString("ntax")));
				//无税金额
				orderItemVO.setNorigmny(new UFDouble(item.getString("norigmny")));
				//本币无税金额
				orderItemVO.setNmny(orderItemVO.getNorigmny());
				//价税合计
				orderItemVO.setNorigtaxmny(new UFDouble(item.getString("norigtaxmny")));
				//本币价税合计
				orderItemVO.setNtaxmny(orderItemVO.getNorigtaxmny());
				//应付组织最新版本 
				orderItemVO.setPk_apfinanceorg(orderHeaderVO.getPk_org());
				//应付组织
				orderItemVO.setPk_apfinanceorg_v(orderHeaderVO.getPk_org_v());
				//结算利润中心最新版本 
				orderItemVO.setPk_apliabcenter(orderHeaderVO.getPk_org());
				//结算利润中心
				orderItemVO.setPk_apliabcenter_v(orderHeaderVO.getPk_org_v());
				//收货库存组织最新版本
				orderItemVO.setPk_arrvstoorg(orderHeaderVO.getPk_org());
				//收货库存组织
				orderItemVO.setPk_arrvstoorg_v(orderHeaderVO.getPk_org_v());
				//采购组织版本信息
				orderItemVO.setPk_org(orderHeaderVO.getPk_org());
				//采购组织
				orderItemVO.setPk_org_v(orderHeaderVO.getPk_org_v());
				//结算财务组织最新版本
				orderItemVO.setPk_psfinanceorg(orderHeaderVO.getPk_org());
				//结算财务组织
				orderItemVO.setPk_psfinanceorg_v(orderHeaderVO.getPk_org_v());
				//需求公司 
				orderItemVO.setPk_reqcorp(orderHeaderVO.getPk_org());
				//需求库存组织最新版本
				orderItemVO.setPk_reqstoorg(orderHeaderVO.getPk_org());
				//需求库存组织
				orderItemVO.setPk_reqstoorg_v(orderHeaderVO.getPk_org_v());
				//需求部门最新版本
				orderItemVO.setPk_reqdept(QueryDataUtil.getDeptPK(item.getString("pk_reqdept")));
				//需求部门
				orderItemVO.setPk_reqdept_v(QueryDataUtil.getDeptVPK(item.getString("pk_reqdept")));
				
				//所属集团
				orderItemVO.setPk_group(orderHeaderVO.getPk_group());
				MaterialVO materialVO = QueryDataUtil.getMaterialPK(item.getString("pk_material"));
				//物料版本信息
				orderItemVO.setPk_material(materialVO.getPk_material());
				//物料信息
				orderItemVO.setPk_srcmaterial(materialVO.getPk_source());
				//供应商
				orderItemVO.setPk_supplier(orderHeaderVO.getPk_supplier());
				//备注
				orderItemVO.setVbmemo(item.getString("vbmemo"));
				//换算率
				orderItemVO.setVchangerate(item.getString("vchangerate"));
				//报价换算率
				orderItemVO.setVqtunitrate(orderItemVO.getVchangerate());
				//发货国家/地区
				orderItemVO.setCsendcountryid(QueryDataUtil.getCountryzonePK("CN"));
				//收货国家/地区
				orderItemVO.setCrececountryid(orderItemVO.getCsendcountryid());
				//报税国家/地区
				orderItemVO.setCtaxcountryid(orderItemVO.getCsendcountryid());
				//领用单号
				orderItemVO.setVbdef4(item.getString("vbdef4"));
				//采购含税预估单价
				orderItemVO.setVbdef5(item.getString("vbdef5"));
				//员工承担金额
				orderItemVO.setVbdef7(item.getString("vbdef7"));
				//使用人
				orderItemVO.setVbdef13(QueryDataUtil.getPsndocPK(item.getString("vbdef13")));
				orderItemVO.setStatus(2);
				listOrderItemVO.add(orderItemVO);
			}
			orderVO.setChildrenVO(listOrderItemVO.toArray(new OrderItemVO[listOrderItemVO.size()]));
			//设置线程时间
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Object dateTimeString  = orderHeaderVO.getDbilldate();
			if(dateTimeString != null) {
			    Date date = format.parse(dateTimeString.toString());
			    long timestamp = date.getTime();
			    InvocationInfoProxy.getInstance().setBizDateTime(timestamp);
			 }
			IPFBusiAction ipf = NCLocator.getInstance().lookup(IPFBusiAction.class);
			OrderVO[] orderVOs = (OrderVO[]) ipf.processAction("SAVEBASE", "21", null, orderVO, null, null);
			
//			HashMap hmPfExParams = new HashMap();
//			WorkflownoteVO workflownoteVO = NCLocator.getInstance().lookup(IWorkflowMachine.class).checkWorkFlow("SAVE", "21", orderVOs[0], hmPfExParams);
//			if(workflownoteVO == null) { 
//				//没有审批流
//				ipf.processAction("APPROVE", "21", workflownoteVO, orderVOs[0], null, null);
//			}else {
//				ipf.processAction("SAVE", "21", workflownoteVO, orderVOs[0], null, null);
//			}
			
			resp.getWriter().write(formatRSJsonData("成功", "", vbillcode).toString());
			NcLog.info("采购订单结束！");
		} catch (Exception e) {
			resp.getWriter().write(formatRSJsonData("失败",e.getMessage() == null ? "" : e.getMessage(),vbillcode).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_org = "pk_org";
		String vbillcode = "vbillcode";
		String billmaker  = "billmaker";
		String cemployeeid = "cemployeeid";
		String corigcurrencyid = "corigcurrencyid";
		String dbilldate = "dbilldate";
		String dmakedate = "dmakedate";
		String fhtaxtypeflag = "fhtaxtypeflag";
		String ntotalastnum = "ntotalastnum";
		String ntotalorigmny = "ntotalorigmny";
		String pk_busitype = "pk_busitype";
		String pk_invcsupllier = "pk_invcsupllier";
		String vtrantypecode = "vtrantypecode";
		String vdef5 = "vdef5";
		String vdef7 = "vdef7";
		String vdef18 = "vdef18";
		String vdef19 = "vdef19";
		String body = "childrenVO";//表体
		String[] HeadKey = {pk_group,pk_org,vbillcode,billmaker,cemployeeid,corigcurrencyid,dbilldate,dmakedate,dmakedate,
				fhtaxtypeflag,ntotalastnum,ntotalorigmny,pk_busitype,pk_invcsupllier,vtrantypecode,vdef5,vdef7,vdef18,vdef19};
		
		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 rowno = "crowno";
		String ccurrencyid = "ccurrencyid";
		String ctaxcodeid = "ctaxcodeid";
		String ntaxrate = "ntaxrate";
		String cunitid = "cunitid";
		String fbuysellflag = "fbuysellflag";
		String ncaltaxmny = "ncaltaxmny";
		String nnum = "nnum";
		String nqtorigprice = "nqtorigprice";
		String nqtorigtaxprice = "nqtorigtaxprice";
		String ntax = "ntax";
		String norigmny = "norigmny";
		String norigtaxmny = "norigtaxmny";
		String pk_material = "pk_material";
		String vchangerate = "vchangerate";
		String vbdef7 = "vbdef7";

		for(int i = 0; i < childrenVO.size(); i++) {
			
			JSONObject oprepJsonObjectB = childrenVO.getJSONObject(i);
			String[] BodyKey = {rowno,ccurrencyid,ctaxcodeid,ntaxrate,cunitid,fbuysellflag,ncaltaxmny,nnum,nqtorigprice,
					nqtorigtaxprice,ntax,norigmny,norigtaxmny,pk_material,vchangerate,vbdef7};
			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);
		}
	}
}
