package nccloud.openapi.mmpac.pmo;

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.itf.mmpac.pmo.pac0002.IPMOBusinessService;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.util.mmf.framework.base.MMCollectionUtil;
import nc.vo.mmpac.pmo.pac0002.entity.PMOAggVO;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;
import nc.ws.opm.pub.utils.result.APIErrCodeEnum;
import nccloud.api.mmpac.pmo.IAPIPmoMaintainService;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.pubift.commen.itf.utils.IHttpPostOtherSys;
import nccloud.ws.rest.resource.AbstractNCCRestResource;
import org.json.JSONString;

@Path("mmpac/pmo")
public class PmoResource extends AbstractNCCRestResource {
    private static String HEADTABLE = "mm_pmo";
    private static String BODYTABLE = "mm_mo";
    private static String GRANDTABLE = "mm_pmo_procedure";
    private static final BaseDAO BASE_DAO = new BaseDAO();
    IHttpPostOtherSys httpPostOtherSys = NCLocator.getInstance().lookup(IHttpPostOtherSys.class);
    private static final Log logger = Log.getInstance("pmoresoucelogger");

    public PmoResource() {
    }

    // 找投放 调哪个接口 拿到接口 根据审批状态和组织判断 自动投放
    @POST
    @Path("save")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString save(Map<String, Object> paramMap) {
        logger.debug("=================开始进行流程生产订单的保存操作,交易类型为 保存即审批 审批后自动设置整单投放================");
        List<Map<String, Object>> paramList = (List) paramMap.get("data");
        PMOAggVO[] insertBills = null;

        try {
            if (MMCollectionUtil.isEmpty(paramList)) {
                return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含data", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
            } else {
                for (Map<String, Object> map : paramList) {
                    if (!map.containsKey(HEADTABLE) || !map.containsKey(BODYTABLE)) {
                        return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
                    }
                }
                IAPIPmoMaintainService serv = (IAPIPmoMaintainService) NCLocator.getInstance().lookup(IAPIPmoMaintainService.class);
                insertBills = serv.save(paramList);
                // 遍历paramList，判断组织是否需要自动投放
                for (Map<String, Object> map : paramList) {
                    Map<String, Object> head = (Map<String, Object>) map.get(HEADTABLE);
                    if (head == null) continue;
                    String pk_org = (String) head.get("pk_org");
                    String orgCode = pk_org;
                    // 如果传递的是主键
                    if (pk_org.length() >= 20) {
                        throw new BusinessException("传入数据异常'pk_org'，参数应该为编码而非主键");
                    }
                    logger.debug("传递的组织非主键,为code[" + pk_org + "]");
                    boolean isIncludeOrg = httpPostOtherSys.checkIfIncludeOrg(orgCode);
                    logger.debug("检查是否为电缆[" + orgCode + "]返回：" + isIncludeOrg);
                    if (isIncludeOrg) {
                        logger.debug("当前检查组织为电缆,进行投放操作");
                        IPMOBusinessService putService = (IPMOBusinessService) NCLocator.getInstance().lookup(IPMOBusinessService.class);
                        try {
                            putService.rowput(insertBills);
                            logger.info("==================自动投放完成，orgCode=" + orgCode);
                        } catch (Exception e) {
                            logger.error("==================自动投放失败，orgCode=" + orgCode, e);
                        }
                    }
                }

                return ResultMessageUtil.toJSON(insertBills, "流程生产订单保存成功");
            }
        } catch (Exception e) {
            logger.error("===========================流程生产订单保存异常", e);
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    @POST
    @Path("update")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString update(Map<String, Object> paramMap) {
        List<Map<String, Object>> paramList = (List) paramMap.get("data");
        PMOAggVO[] updateBills = null;

        try {
            if (MMCollectionUtil.isEmpty(paramList)) {
                return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含data", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
            } else {
                for (Map<String, Object> map : paramList) {
                    if (!map.containsKey(HEADTABLE) || !map.containsKey(BODYTABLE)) {
                        return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
                    }
                }

                updateBills = ((IAPIPmoMaintainService) NCLocator.getInstance().lookup(IAPIPmoMaintainService.class)).update(paramList);
                return ResultMessageUtil.toJSON(updateBills, "流程生产订单修改成功");
            }
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    @POST
    @Path("delete")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString delete(Map<String, Object> paramMap) {
        List<String> hidList = (List) paramMap.get("ids");
        if (MMCollectionUtil.isEmpty(hidList)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含ids信息", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
        } else {
            try {
                String[] hids = (String[]) hidList.toArray(new String[0]);
                ((IAPIPmoMaintainService) NCLocator.getInstance().lookup(IAPIPmoMaintainService.class)).delete(hids);
                return ResultMessageUtil.toJSON(new String[0], "流程生产订单删除成功");
            } catch (BusinessException e) {
                return ResultMessageUtil.exceptionToJSON(e);
            }
        }
    }

    @POST
    @Path("queryPmos")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString queryByPurcahseOrderId(Map<String, Object> paramMap) {
        try {
            if (paramMap == null || !paramMap.containsKey("vdef8")) {
                return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含vdef8信息", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
            }
            List<String> vdef8List = (List<String>) paramMap.get("vdef8");
            Integer limit = null;
            if (paramMap.containsKey("limit")) {
                Object limitObj = paramMap.get("limit");
                if (limitObj instanceof Number) {
                    limit = ((Number) limitObj).intValue();
                }
            }
            String baseSql;
            if (MMCollectionUtil.isEmpty(vdef8List)) {
                // 如果vdef8List为空，查询所有数据
                baseSql = "SELECT * FROM GET_PRODUCTION_ORDER";
            } else {
                // 构建IN条件的SQL查询
                StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM GET_PRODUCTION_ORDER WHERE vdef8 IN (");
                for (int i = 0; i < vdef8List.size(); i++) {
                    if (i > 0) {
                        sqlBuilder.append(",");
                    }
                    sqlBuilder.append("'").append(vdef8List.get(i)).append("'");
                }
                sqlBuilder.append(")");
                baseSql = sqlBuilder.toString();
            }

            // 如果有limit参数，使用ROWNUM限制返回条数
            String sql;
            if (limit != null && limit > 0) {
                sql = "SELECT * FROM (" + baseSql + ") WHERE ROWNUM <= " + limit;
            } else {
                sql = baseSql;
            }
            List<Map<String, Object>> rows = (List<Map<String, Object>>) BASE_DAO.executeQuery(sql, new MapListProcessor());
            return ResultMessageUtil.toJSON(rows, "查询生产订单信息成功");

        } catch (DAOException e) {
            return ResultMessageUtil.exceptionToJSON("数据库查询异常: ", e.getMessage());
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    public String getModule() {
        return "mmpac";
    }
}
