package nccloud.api.so.so.saleorder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import nc.bs.framework.common.NCLocator;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.JdbcSession;
import nc.jdbc.framework.PersistenceManager;
import nc.jdbc.framework.exception.DbException;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.pub.BusinessException;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.ws.rest.resource.AbstractNCCRestResource;
import org.json.JSONString;
import nc.bs.dao.BaseDAO;

@Path("so/so/saleorder")
public class saleUpdateLJfh extends AbstractNCCRestResource {

	@Override
	public String getModule() {
		return "so";
	}

	// 用于存储手工维护的必填字段和字段说明
	private Map<String, String> requiredFields;

	// 构造方法，初始化必填字段及其说明
	public saleUpdateLJfh() {
		// 初始化必填字段列表及字段说明
		requiredFields = new HashMap<>();
		requiredFields.put("pk_org", "业务单元");
		requiredFields.put("array.vbillcode", "单据编号");
		requiredFields.put("array.crowno", "行号");
		requiredFields.put("array.sendQty", "发货数量");
	}

	@POST
	@Path("/saleUpdateLJfh")
	@Consumes({"application/json"})
	@Produces({"application/json"})
	public JSONString saleUpdateLJfh(JSONString json) {
		try {

			JSONObject object = JSON.parseObject(json.toJSONString());
			if (object == null) {
				return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
			}
			// 校验必填字段
			String tipsStr = checkRequiredFields(object);
			if (!tipsStr.equals("")) {
				return ResultMessageUtil.exceptionToJSON(new NullPointerException(tipsStr));
			}
			String pk_org = (String) object.getOrDefault("pk_org", "");
			Object obj = object.getOrDefault("array", "");
			ArrayList<?> arrayList = new ArrayList<>();
			if (obj instanceof JSONArray) {
				JSONArray jsonArray = (JSONArray) obj;
				arrayList = new ArrayList<>(jsonArray.toJavaList(Object.class));
			}
//            StringBuilder sqlStr = new StringBuilder();
			List sqlStr = new ArrayList();
			for (int i = 0; i < arrayList.size(); i++) {
				Map dataMap = (Map) arrayList.get(i);
				sqlStr.add("UPDATE so_saleorder_b b "
						+ "SET b.vbdef2 = '" + dataMap.get("sendQty") + "'"
						+ "WHERE b.csaleorderid IN ("
						+ "    SELECT h.csaleorderid"
						+ "    FROM so_saleorder h"
						+ "    LEFT JOIN org_salesorg o ON h.pk_org = o.pk_salesorg"
						+ "    WHERE h.vbillcode = '" + dataMap.get("vbillcode") + "' "
						+ "      AND o.code = '" + pk_org + "' "
						+ "      AND b.crowno = '" + dataMap.get("crowno") + "'"
						+ ");");
			}
//            int succState = updateSaleBSQty(sqlStr.toString());
			int succState = executeUpdate(sqlStr);

			JSONObject returnJson = new JSONObject();
			returnJson.put("state", '1');
 //
 			if (succState == 0) {
				returnJson.put("msg", "失败");
			}else {
				returnJson.put("msg", "成功,已修改"+succState+"行");
			}
 			return ResultMessageUtil.toJSON(returnJson);
		} catch (DbException e) {
			throw new RuntimeException(e);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * updateSqls为要执行的sql语句。返回影响行数量
	 */
	public int executeUpdate(List<String> updateSqls) throws DbException {
		if (updateSqls == null) {
			return 0;
		}

		int ret = 0;
		PersistenceManager manager = null;
		JdbcSession session = null;
		Connection connection = null;

		try {
			manager = PersistenceManager.getInstance();
			session = manager.getJdbcSession();
			connection = session.getConnection();  // 获取实际的数据库连接

			// 开始事务
			connection.setAutoCommit(false);  // 禁用自动提交，手动管理事务

			// 执行批量操作
			for (String sql : updateSqls) {
				session.addBatch(sql);
			}

			// 执行批处理
			ret = session.executeBatch();

			// 提交事务
			connection.commit();  // 批处理成功后提交事务

		} catch (DbException e) {
			if (connection != null) {
				try {
					// 如果发生异常，回滚事务
					connection.rollback();
				} catch (SQLException rollbackEx) {
					// 记录回滚异常的详细信息
					throw new DbException("Error during transaction rollback", rollbackEx) {
						@Override
						public boolean isDataIntegrityViolation() {
							return false;
						}

						@Override
						public boolean isBadSQLGrammar() {
							return false;
						}
					};
				}
			}
			throw e;  // 将原始异常抛出
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (connection != null) {
				try {
					// 恢复自动提交模式，确保不会影响其他操作
					connection.setAutoCommit(true);
				} catch (SQLException e) {
					// 忽略恢复自动提交时的异常
				}
			}
			if (manager != null) {
				manager.release();
			}
		}

		return ret;
	}

	// 方法：检查必填项并返回转化后的Map
	public static String checkRequiredFields(JSONObject data) throws Exception {
		String returnStr = "";
		// 2. 检查必填字段 pk_org
		String pkOrg = (String) data.getOrDefault("pk_org", "");
		if (pkOrg.isEmpty()) {
			return "字段pk_org缺失或为空!";
		}
		// 3. 获取并检查 array 字段
		Object array = data.getOrDefault("array", null);
		if (array == null || !(array instanceof JSONArray) || ((JSONArray) array).isEmpty()) {
			return "array对象为空或不存在!";
		}
		ArrayList<?> arrayList = new ArrayList<>();
		if (array instanceof JSONArray) {
			JSONArray jsonArray = (JSONArray) array;
			arrayList = new ArrayList<>(jsonArray.toJavaList(Object.class));
		}
		// 5. 遍历每个对象，检查必填字段
		for (int i = 0; i < arrayList.size(); i++) {
			Map item = (Map) arrayList.get(i);
			// 检查必填字段 'crowno'
			if (item.getOrDefault("crowno", "").toString().isEmpty()) {
				return "第 " + (i + 1) + " 项缺少必填字段crowno!";
			}
			// 检查必填字段 'vbillcode'
			if (item.getOrDefault("vbillcode", "").toString().isEmpty()) {
				return "第 " + (i + 1) + " 项缺少必填字段vbillcode!";
			}
			// 检查必填字段 'sendQty'
			if (item.getOrDefault("sendQty", "").toString().isEmpty()) {
				return "第 " + (i + 1) + " 项缺少必填字段sendQty!";
			}
		}
		return returnStr;
	}


	/*
	 *创建时间：2024-11-28
	 *作用：查询
	 *传值：无
	 *返回值：必填项map对象
	 */
	private String getSaleorderBPK(String pk_org, String vbillcode, String crowno) throws BusinessException {
		String sql = " select b.csaleorderbid from so_saleorder h \n"
				+ "left join so_saleorder_b b on h.csaleorderid=b.csaleorderid\n"
				+ "left join org_salesorg o on h.pk_org=o.pk_salesorg\n"
				+ "where h.vbillcode='" + vbillcode + "' and o.code='" + pk_org + "' and b.crowno='" + crowno + "' ";
		String saleorderBPK = (String) getQueryService().executeQuery(sql, new ColumnProcessor());
		return saleorderBPK;
	}

	/*
	 *创建时间：2024-11-28
	 *作用：查询
	 *传值：无
	 *返回值：必填项map对象
	 */
	private int updateSaleBSQty(String sql) throws BusinessException {
		BaseDAO baseDAO = new BaseDAO();
		int succInt = baseDAO.executeUpdate(sql);
		return succInt;
	}

	public IUAPQueryBS getQueryService() {
		return NCLocator.getInstance().lookup(IUAPQueryBS.class);
	}

}