package nccloud.api.so.so.saleorder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ufida.web.html.S;
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;
import nccloud.web.so.saleorder.action.SaleOrderBillCloseAction;

@Path("so/so/SendQty")
public class saleUpdateSQty extends AbstractNCCRestResource {

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

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

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

    @POST
    @Path("/updateSendQty")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString updateSendQty(JSONString json) {
        try {
            JSONObject returnJson = new JSONObject();
            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);
                String csaleorderid = (String) dataMap.get("crowno");
                if (csaleorderid != null) {
                    sqlStr.add(
                            "UPDATE so_saleorder_b SET vbdef2 = '" + dataMap.get("sendQty") + "' WHERE csaleorderbid='"
                                    + csaleorderid + "'");
                } else {
                    returnJson.put("state", "N");
                    returnJson.put("msg",
                            "修改失败,单号：" + dataMap.get("vbillcode") + "行号：" + dataMap.get(
                                    "crowno") + "无法关联NCC销售订单。");
                    return ResultMessageUtil.toJSON(returnJson);
                }

            }
            int succState = executeUpdate(sqlStr);

            if (succState == arrayList.size()) {
                returnJson.put("state", 'Y');
                returnJson.put("msg", "成功,已修改" + succState + "行");

            } else {
                returnJson.put("state", 'N');
                returnJson.put("msg", "失败,已修改" + succState + "行");
            }
            return ResultMessageUtil.toJSON(returnJson);
        } catch (DbException e) {
            JSONObject returnJson = new JSONObject();
            returnJson.put("state", 'N');
            returnJson.put("msg", "修改失败" + e.getMessage());
            return ResultMessageUtil.toJSON(returnJson);
        } catch (Exception e) {
            JSONObject returnJson = new JSONObject();
            returnJson.put("state", 'N');
            returnJson.put("msg", "修改失败" + e.getMessage());
            return ResultMessageUtil.toJSON(returnJson);
        }
    }

    public int executeUpdate(List<String> updateSqls) throws DbException {
        if (updateSqls == null) {
            return 0;
        }

        int ret = 0;
        PersistenceManager manager = null;
        JdbcSession session = new JdbcSession();
        Connection connection = null;
        try {
            manager = PersistenceManager.getInstance();
            session = manager.getJdbcSession();
            connection = session.getConnection();  // 获取实际的数据库连接
            // 禁用自动提交，确保事务控制
            connection.setAutoCommit(false);

            try {
                // 执行批处理
                // 执行批量操作
                for (String sql : updateSqls) {
                    session.addBatch(sql);
                }
                ret = session.executeBatch();

                // 确保在所有操作成功之后提交事务
                connection.commit();  // 批处理成功后提交事务
                connection.getAutoCommit();
            } catch (SQLException batchEx) {
                // 如果批处理执行时发生异常，回滚事务
                connection.rollback();
            }

        } catch (DbException e) {
            // 捕获 DbException，执行回滚操作
            if (connection != null) {
                try {
                    connection.rollback();  // 回滚事务
                } catch (SQLException rollbackEx) {
                    // 记录回滚异常的详细信息
                    e.printStackTrace();
                }
            }
            e.printStackTrace();  // 或者记录日志
        } catch (SQLException e) {
            // 针对其他 SQLException 异常的处理
            if (connection != null) {
                try {
                    connection.rollback();  // 回滚事务
                } catch (SQLException rollbackEx) {
                    // 记录回滚异常的详细信息
                    e.printStackTrace();  // 或者记录日志
                }
            }
            e.printStackTrace();  // 或者记录日志
        } finally {
            if (connection != null) {
                try {
                    // 恢复自动提交模式
                    connection.setAutoCommit(true);
                } catch (SQLException e) {
                    // 忽略恢复自动提交时的异常
                    e.printStackTrace();
                }
            }
            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;
    }


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

}