package nccloud.openapi.ic.subcontractReceipt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import nc.bs.dao.BaseDAO;
import nc.bs.logging.Log;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.BusinessException;
import nccloud.api.rest.utils.OpenApiPageInfo;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.ws.rest.resource.AbstractNCCRestResource;
import org.json.JSONString;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nccloud.api.rest.utils.ApiResourceParamUtils;
import nc.impl.pubapp.pattern.database.SqlBuilderUtil;
import nc.vo.ic.m47.entity.SubcontInHeadVO;

@Path("ic/subcontractReceipt")
public class SubcontractReceiptResource extends AbstractNCCRestResource {

    private Log log = Log.getInstance("hlcsalog");
    private volatile BaseDAO baseDAO = null;

    /**
     * 委外加工入库查询，校验必填参数并按条件查询数据库
     * 第一次查询,为空查询,返回分页条件对应的数据,第一次查询返回code,name,pk
     * 第二次查询可以按照主键查询 也可以按照code查询
     * 1. 第一次查询 无限制条件 根据分页条件查询
     * 2. 第二次查询 写一个视图
     *
     * @param json 请求JSON
     * @return 查询结果
     */
    @POST
    @Path("querySubcontractReceipt")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString querySubcontractReceipt(JSONString json) {
        try {
            // 解析JSON请求体
            JSONObject jObject = JSON.parseObject(json.toJSONString());
            if (jObject == null) {
                return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
            }
            JSONObject ufinterface = jObject.getJSONObject("ufinterface");
            if (ufinterface == null) {
                return ResultMessageUtil.exceptionToJSON(new NullPointerException("ufinterface:null"));
            }

            // 处理分页参数，设为必传
            JSONObject pageInfo = ufinterface.getJSONObject("pageInfo");
            if (pageInfo == null) {
                return ResultMessageUtil.exceptionToJSON(new BusinessException("分页信息(pageInfo)为必填项"));
            }

            OpenApiPageInfo openApiPageInfo = new OpenApiPageInfo();
            int pageIndex = pageInfo.getIntValue("pageIndex") > 0 ? pageInfo.getIntValue("pageIndex") : 1;
            int pageSize = pageInfo.getIntValue("pageSize") > 0 ? pageInfo.getIntValue("pageSize") : 20;
            openApiPageInfo.setPageIndex(pageIndex);
            openApiPageInfo.setPageSize(pageSize);

            // 提取查询参数（不再强制验证必填）
            Map<String, Object> param = new HashMap<>();
            boolean hasConditions = extractParams(ufinterface, param);

            // 查询条件：若无条件则查询全部
            String condition = "1=1";
            if (hasConditions) {
                // 使用ApiResourceParamUtils生成查询条件
                ApiResourceParamUtils apiUtils = new ApiResourceParamUtils();
                condition = apiUtils.parseParmToSql(new SubcontInHeadVO(), param, ApiResourceParamUtils.BYCODE);
                if (condition.endsWith("and ")) {
                    condition = condition.substring(0, condition.length() - 4);
                }
                if (condition.trim().isEmpty()) {
                    condition = "1=1";
                }
            }

            // 查询所有符合条件的主键
            if (baseDAO == null) {
                baseDAO = new BaseDAO();
            }
            String sql = "SELECT cgeneralhid FROM ic_subcontin_h WHERE " + condition;
            List<String> allPks = (List<String>) baseDAO.executeQuery(sql,
                    new SQLParameter(),
                    new ColumnListProcessor());

            // 处理分页
            int total = allPks.size();
            if (total == 0) {
                openApiPageInfo.setTotal(0);
                return ResultMessageUtil.toJSONByPage(null, openApiPageInfo, false);
            }

            // 计算当前页的记录
            int fromIndex = (pageIndex - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, total);
            if (fromIndex >= total) {
                openApiPageInfo.setTotal(total);
                return ResultMessageUtil.toJSONByPage(null, openApiPageInfo, false);
            }
            List<String> currPks = allPks.subList(fromIndex, toIndex);

            // 使用SqlBuilderUtil生成IN子句处理批量查询
            List<Map<String, Object>> resultList = new ArrayList<>();
            if (!currPks.isEmpty()) {
                SqlBuilderUtil sqlBuilderUtil = new SqlBuilderUtil();
                String wherepart = sqlBuilderUtil.buildSQL("cgeneralhid", currPks.toArray(new String[0]), null);
                String detailSql = "SELECT * FROM ic_subcontin_h WHERE " + wherepart;
                resultList = (List<Map<String, Object>>) baseDAO.executeQuery(detailSql,
                        new SQLParameter(),
                        new MapListProcessor());
            }

            // 返回结果
            openApiPageInfo.setTotal(total);
            return ResultMessageUtil.toJSONByPage(resultList, openApiPageInfo, false);

        } catch (Exception e) {
            // 统一异常处理
            return ResultMessageUtil.exceptionToJSON(new BusinessException("查询委外加工入库单据失败: " + e.getMessage(), e));
        }
    }

    /**
     * 提取请求参数，不强制验证必填
     *
     * @param ufinterface JSON请求对象
     * @param param       要填充的参数Map
     * @return 是否有查询条件
     */
    private boolean extractParams(JSONObject ufinterface, Map<String, Object> param) {
        boolean hasConditions = false;

        // 获取参数
        String pk_group = ufinterface.getString("pk_group");
        String name = ufinterface.getString("name");
        String code = ufinterface.getString("code");
        String createdate = ufinterface.getString("createdate");
        String ncindustry = ufinterface.getString("ncindustry");
        String pk_currtype = ufinterface.getString("pk_currtype");
        String pk_exratescheme = ufinterface.getString("pk_exratescheme");
        String vbillcode = ufinterface.getString("vbillcode");
        String pk_org = ufinterface.getString("pk_org");
        String dbilldate = ufinterface.getString("dbilldate");

        // 添加到参数Map - 只添加非空参数
        if (pk_group != null && !pk_group.trim().isEmpty()) {
            param.put("pk_group", pk_group);
            hasConditions = true;
        }
        if (name != null && !name.trim().isEmpty()) {
            param.put("name", name);
            hasConditions = true;
        }
        if (code != null && !code.trim().isEmpty()) {
            param.put("code", code);
            hasConditions = true;
        }
        if (createdate != null && !createdate.trim().isEmpty()) {
            param.put("createdate", createdate);
            hasConditions = true;
        }
        if (ncindustry != null && !ncindustry.trim().isEmpty()) {
            param.put("ncindustry", ncindustry);
            hasConditions = true;
        }
        if (pk_currtype != null && !pk_currtype.trim().isEmpty()) {
            param.put("pk_currtype", pk_currtype);
            hasConditions = true;
        }
        if (pk_exratescheme != null && !pk_exratescheme.trim().isEmpty()) {
            param.put("pk_exratescheme", pk_exratescheme);
            hasConditions = true;
        }
        if (vbillcode != null && !vbillcode.trim().isEmpty()) {
            param.put("vbillcode", vbillcode);
            hasConditions = true;
        }
        if (pk_org != null && !pk_org.trim().isEmpty()) {
            param.put("pk_org", pk_org);
            hasConditions = true;
        }
        if (dbilldate != null && !dbilldate.trim().isEmpty()) {
            param.put("dbilldate", dbilldate);
            hasConditions = true;
        }

        return hasConditions;
    }

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