package nc.bs.tbb.servlet;

import java.io.IOException;

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.server.ISecurityTokenCallback;
import nc.bs.servlet.service.BaseServlet;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDouble;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ModifyBudgetServlet extends BaseServlet implements IHttpServletAdaptor{

	BaseDAO basedao = new BaseDAO();
	IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	String kyye = "CORPYS0000";//可用余额编码
	String ysze = "CORPYS0003";//预算总额编码
	String sjsy = "Actual";//实际使用数编码
	String yzs = "PreActual";//预占数编码
	String yss = "Budget";//预算数编码
	
	@Override
	public void doAction(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO 自动生成的方法存根
		NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());
		
		try {
			String createStr = buildJson(req, resp, this.getClass().getName());
			JSONObject json = JSONObject.fromObject(createStr);
			String checkresult = checkJson(json);
			if(checkresult != null){
				resp.getWriter().write(formatRSJsonData("失败",
						checkresult,"").toString());
				return;
			}
			JSONArray bodyArray = json.getJSONArray("result");
			JSONArray result = new JSONArray();
			for (Object Object : bodyArray) {
				JSONObject bodyObject = JSONObject.fromObject(Object);
				String objcode = QueryModelCode(bodyObject.getString("objname"));//应用模型编码
				String code_entity = bodyObject.getString("code_entity");//责任主体
				String pk_year = bodyObject.getString("pk_year");//会计年度
				String code_measure = QueryMeasureCode(bodyObject.getString("code_measure"));//预算编码
				String code_version = QueryVersionCode(bodyObject.getString("code_version"));//预算版本
				UFDouble value = new UFDouble(bodyObject.getString("value"));//预算总额
				UFDouble actualUse = new UFDouble(QueryNmny(objcode,code_entity,pk_year,code_measure,code_version,sjsy));//本年度实际使用数
				UFDouble pupremny = new UFDouble(QueryNmny(objcode,code_entity,pk_year,code_measure,code_version,yzs));//预占数
				//预算总额-本年度实际使用数-预占数<0抛异常
				if(value.sub(actualUse).sub(pupremny).compareTo(UFDouble.ZERO_DBL)<0){
					result.add(formatRSJsonData("失败",
							bodyObject.getString("objname")+pk_year+"年"+bodyObject.getString("code_measure")+"可用额度不足，请检查","").toString());
				}
				else{
					Object ndyspk = QueryPk(objcode,code_entity,pk_year,code_measure,code_version,yss);//预算数pk
					if(ndyspk != null){
						//修改本年度预算数
						UpdateSql(objcode,value.toString(),ndyspk.toString());
					}
					Object yszepk = QueryPk(objcode,code_entity,pk_year,code_measure,code_version,ysze);//预算总额pk
					if(yszepk != null){
						//修改预算总额
						UpdateSql(objcode,value.toString(),yszepk.toString());
					}
					Object kyyepk = QueryPk(objcode,code_entity,pk_year,code_measure,code_version,kyye);//可用余额pk
					if(kyyepk != null){
						//修改可用余额
						UpdateSql(objcode,value.sub(actualUse).sub(pupremny).toString(),kyyepk.toString());
					}
					result.add(formatRSJsonData("成功",
						     "",bodyObject.getString("objname")+pk_year+"年"+bodyObject.getString("code_measure")+"预算修改成功").toString());
				}
			}
			resp.getWriter().write(result.toString());
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}//非空判断
	}

	/*
	 * 非空判断
	 */
	private String checkJson(JSONObject json) throws Exception {
		
		StringBuffer mags = new StringBuffer();
		Boolean empty = true;
		
		String body = "result";//表体
		
		if (json.getJSONArray(body)==null) {
			empty = false;
			mags.append("表体不存在！ ");
		}
		
		JSONArray oprepObjectBs = json.getJSONArray("result");
		
		if (oprepObjectBs == null || oprepObjectBs.size() == 0) {
			return "表体内容不可为空！";
		}
		
		String objname = "objname";//应用模型
		String code_entity = "code_entity";//责任主体
		String pk_year = "pk_year";//会计年份
		String code_measure = "code_measure";//预算编码
		String code_version = "code_version";//预算版本

		String value = "value";//预算额度
		
		for(int i = 0; i < oprepObjectBs.size(); i++) {
			
			JSONObject oprepJsonObjectB = oprepObjectBs.getJSONObject(i);
			String[] BodyKey = {objname,code_entity,pk_year,code_measure,code_version,value};
			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) {
			return "以下字段不可为空："+mags;
		}
		return null;
	}

	/**
	 * 修改预算额度
	 * @param objcode
	 * @param value
	 * @param pk
	 * @throws DAOException
	 */
	public void UpdateSql(String objcode,String value,String pk) throws DAOException{
		String sql = "update tb_cube_"+objcode+" set value = '"+value+"' where pk_obj = '"+pk+"'";
		basedao.executeUpdate(sql);
		
	}
	
	/**
	 * 查询pk
	 * @param objcode
	 * @param code_entity
	 * @param pk_year
	 * @param code_measure
	 * @param code_version
	 * @param code_mvtype
	 * @return
	 */
	public String QueryPk(String objcode,String code_entity,String pk_year,String code_measure,String code_version,String code_mvtype){
		String qrysql = "select pk_obj from tb_cube_"+objcode+" where code_entity = '"+code_entity+"' and pk_year = '"+pk_year+"' and code_measure = '"+code_measure+"'  and code_version = '"+code_version+"' and code_mvtype = '"+code_mvtype+"'";
		Object object = "";
		try {
			object = iuap.executeQuery(qrysql, new ColumnProcessor());
		} catch (BusinessException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		if (object==null) {
			return null;
		}else {
			return object.toString();
		}
	}
	
	/**
	 * 查询金额
	 * @param objcode
	 * @param code_entity
	 * @param pk_year
	 * @param code_measure
	 * @param code_version
	 * @param code_mvtype
	 * @return
	 */
	public String QueryNmny(String objcode,String code_entity,String pk_year,String code_measure,String code_version,String code_mvtype){
		String qrysql = "select value from tb_cube_"+objcode+" where code_entity = '"+code_entity+"' and pk_year = '"+pk_year+"' and code_measure = '"+code_measure+"'  and code_version = '"+code_version+"' and code_mvtype = '"+code_mvtype+"'";
		Object object = "";
		try {
			object = iuap.executeQuery(qrysql, new ColumnProcessor());
		} catch (BusinessException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		if (object==null) {
			return "0";
		}else {
			return object.toString();
		}
	}
	
	
	
	/**
	 * 查询应用模型编码
	 * @param objname
	 * @return
	 * @throws BusinessException
	 */
	public String QueryModelCode(String objname) throws BusinessException{
		String qrysql = "select objcode from tb_cubedef where objname = '"+objname+"' and nvl(dr,0) = 0";
		Object object;
		object = iuap.executeQuery(qrysql, new ColumnProcessor());
		if (object==null) {
			return null;
		}else {
			return object.toString();
		}
	}
	
	
	/**
	 * 查询预算编码
	 * @param code_measure
	 * @return
	 * @throws BusinessException
	 */
	public String QueryMeasureCode(String code_measure) throws BusinessException{
		String qrysql = "select code from bd_inoutbusiclass where name = '"+code_measure+"' and nvl(dr,0) = 0";
		Object object;
		object = iuap.executeQuery(qrysql, new ColumnProcessor());
		if (object==null) {
			return null;
		}else {
			return object.toString();
		}
	}
	
	
	/**
	 * 查询版本编码
	 * @param code_version
	 * @return
	 * @throws BusinessException
	 */
	public String QueryVersionCode(String code_version) throws BusinessException{
		String qrysql = "select objcode from tb_version where objname = '"+code_version+"' and nvl(dr,0) = 0";
		Object object;
		object = iuap.executeQuery(qrysql, new ColumnProcessor());
		if (object==null) {
			return null;
		}else {
			return object.toString();
		}
	}
}
