package nc.bs.pu.wgpt.process;

import java.util.List;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.impl.pubapp.env.BSContext;
import nc.itf.pu.m21.IOrderClose;
import nc.itf.pubapp.pub.smart.IBillQueryService;
import nc.itf.uap.pf.IPFWorkflowQry;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.net.servlet.IReturnStatus;
import nc.pubitf.arap.pay.IArapPayBillPubQueryService;
import nc.pubitf.arap.pay.IArapPayBillPubService;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.uap.wgpt.WuYeWgptUtil;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultVO;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pubapp.pattern.data.ValueUtils;
import nc.vo.wgpt.log.WuYeWgptLogVO;
import nccloud.commons.collections.CollectionUtils;

import uap.json.JSONObject;

/**
 * @Description: 【网购平台->NC】整单关闭采购订单
 * 
 * @author 谢文如 【碧桂园-物业板块-网购平台接口】
 * @date 2019-3-6
 * @version with NCC
 */
public class CloseOrderProcess {

	@SuppressWarnings("unchecked")
	public String closeOrder(JSONObject jsonobj) throws BusinessException {
		String rsdata = null;
		String nc_id = null;
		Object orderno = null;
		ResultEsbVO<ResultVO> esb = new ResultEsbVO<ResultVO>();
		ResultVO result = new ResultVO();
		com.alibaba.fastjson.JSONObject resultJsonObject=new com.alibaba.fastjson.JSONObject();
		resultJsonObject.put("state", "0");
		result.setResult(resultJsonObject);
		esb.setResultInfo(result);
		try {
			if (jsonobj == null || "".equals(jsonobj)) {// 无Post提交值
				result.setCode(IReturnStatus.FAILING);// 失败
				result.setMessage("Post所提交请求Json格式错误或者无值!");
				WuYeWgptUtil.createResultEsbVO(esb);
				esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_FAILING);
				esb.getEsbInfo().setReturnMsg("失败");
				esb.setResultInfo(result);
			} else {
				orderno = jsonobj.getJSONObject("requestInfo").get("orderno");
				BaseDAO baseDAO = new BaseDAO();
				String sql = "select pk_order from po_order where nvl(dr,0)=0 and vdef15='"+ orderno +"'";
				List<String> pkOrders = (List<String>) baseDAO.executeQuery(sql, new ColumnListProcessor());
				if (CollectionUtils.isEmpty(pkOrders)) {
					throw new BusinessException("没有该采购订单【" + orderno + "】");
				}
				if (pkOrders.size() > 1) {
					throw new BusinessException("NC有" + pkOrders.size() + "张订单【" + orderno + "】");
				}
				nc_id = pkOrders.get(0);
				IBillQueryService billQuery = NCLocator.getInstance().lookup(IBillQueryService.class);
				OrderVO orderVO = billQuery.querySingleBillByPk(OrderVO.class, nc_id);
				orderVO.getHVO().setVdef31(UFBoolean.TRUE.toString());
				IOrderClose closeService = NCLocator.getInstance().lookup(IOrderClose.class);
				IPFWorkflowQry workflowQry=NCLocator.getInstance().lookup(IPFWorkflowQry.class);
				IArapPayBillPubQueryService payBillPubQueryService=NCLocator.getInstance().lookup(IArapPayBillPubQueryService.class);
				IArapPayBillPubService payBillPubService=NCLocator.getInstance().lookup(IArapPayBillPubService.class);
				AggPayBillVO[] aggPayBillVOs=payBillPubQueryService.queryVOsByWhere("pk_paybill in (select pi.pk_paybill from ap_payitem pi where pi.top_billid ='"+nc_id+"' and nvl(dr,0)=0)  and  money>0  and  nvl(dr,0)=0");
				InvocationInfoProxy.getInstance().setProperty("iswgptsend", "Y");
				BSContext.getInstance().setSession("iswgptsend", "Y");
				if(MMValueCheck.isEmpty(aggPayBillVOs)) {
					closeService.close(new OrderVO[] { orderVO }, 0, true);
					resultJsonObject.put("state","3");
					result.setCode(IReturnStatus.SUCCEED);// 成功
					result.setMessage("采购订单【" + orderno + "】关闭成功");
				}else {
					boolean  isApproveFlowStartup=workflowQry.isApproveFlowStartup(aggPayBillVOs[0].getHeadVO().getPk_paybill(), aggPayBillVOs[0].getHeadVO().getPk_tradetype());
					//预付款单状态为自由态，删除预付款单，关闭订单
					if(!isApproveFlowStartup && (aggPayBillVOs[0].getHeadVO().getBillstatus()==-1 || aggPayBillVOs[0].getHeadVO().getBillstatus()==-99)) {
						InvocationInfoProxy.getInstance().setProperty("iswgptsend", "Y");
						BSContext.getInstance().setSession("iswgptsend", "Y");
						
						payBillPubService.delete(aggPayBillVOs);
						orderVO = billQuery.querySingleBillByPk(OrderVO.class, nc_id);
						closeService.close(new OrderVO[] { orderVO }, 0, true);
						resultJsonObject.put("state","4");
						result.setCode(IReturnStatus.SUCCEED);// 成功
						result.setMessage("采购订单【" + orderno + "】关闭成功");
					}else {
						int settleflag=ValueUtils.getInt(aggPayBillVOs[0].getHeadVO().getSettleflag(), 0);
						if(settleflag==1) {
							resultJsonObject.put("state","2");
							result.setCode(IReturnStatus.FAILING);// 成功
							result.setMessage("订单【"+orderno+"】已支付预付款，订单暂未关闭。待财务确认收到退款后订单将自动关闭");
						}else {
							resultJsonObject.put("state","1");
							result.setCode(IReturnStatus.FAILING);// 成功
							result.setMessage("该订单下游预付款单（"+aggPayBillVOs[0].getHeadVO().getBillno()+"）已生成但未支付，订单暂未关闭。待财务删除预付款单后订单将自动关闭");
						}
					}
				}
				orderVO.getHVO().setVdef31(UFBoolean.TRUE.toString());
				new BaseDAO().updateVO(orderVO.getHVO(), new String[] {"vdef31"});
				WuYeWgptUtil.createResultEsbVO(esb);
				result.setResult(resultJsonObject);
				esb.setResultInfo(result);
			}
		} catch (Exception e) {
			result.setCode(IReturnStatus.ERROR);// 异常
			result.setError(WuYeWgptUtil.getExceptionDetail(e));
			result.setMessage(result.getError());
			WuYeWgptUtil.createResultEsbVO(esb);// 初始化响应对象
			esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_ERROR);
			esb.getEsbInfo().setReturnMsg("异常");
			esb.setResultInfo(result);// 设置响应内容
		} finally {
			rsdata = com.alibaba.fastjson.JSONObject.toJSONString(esb);

			WuYeWgptLogVO logVO = new WuYeWgptLogVO();
			logVO.setNc_id(nc_id);
			logVO.setOther_id(orderno + "");
			logVO.setBillno("");
			logVO.setTranstypecode("21");
			logVO.setItfcode("WGPT-NC-002");
			logVO.setItfname("【网购平台->NC】整单关闭采购订单");
			logVO.setBilldata(jsonobj == null ? "" : jsonobj.toString());
			logVO.setRsdata(rsdata);
			logVO.setMsg(null);
			logVO.setIssuccess(IReturnStatus.SUCCEED.equals(result.getCode()) ? "Y" : "N");

			WuYeWgptUtil.getIWuYeWgptLogService().insertLog_RequiresNew(logVO);
		}
		return rsdata;
	}

}
