package nccloud.openapi.so.m30;

import nc.bd.itf.tools.BFPubTools;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.itf.bd.defdoc.IDefdocService;
import nc.itf.pim.project.prv.IProject;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.pim.project.ProjectHeadVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pubapp.AppContext;
import nc.vo.so.m30.entity.SaleOrderBVO;
import nc.vo.so.m30.entity.SaleOrderHVO;
import nc.vo.so.m30.entity.SaleOrderVO;
import nc.ws.opm.pub.utils.result.APIErrCodeEnum;
import nccloud.api.rest.utils.NCCRestUtils;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.api.so.m30.IAPISaleOrderMaitain;
import nccloud.api.so.m30.IAPISaleOrderQuery;
import nccloud.commons.lang.StringUtils;
import nccloud.openapi.scmpub.pub.NCCPubRestResource;
import nccloud.openapi.scmpub.pub.TransferCodeToPKTool;
import nccloud.openapi.scmpub.pub.TransferMapToVOTool;
import nccloud.openapi.scmpub.util.CallReturnBuildUtil;
import org.json.JSONString;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.*;


/**
 * 销售订单接口适配2005代码
 * zhangxinah
 */

@Path("so/saleorder")
public class SaleOrderResource extends NCCPubRestResource {
    private static Log log = Log.getInstance("biptonccsaleorder");
    private static String BODYTABLE = "so_saleorder_b";
    private static String HEADTABLE = "so_saleorder";
    public BaseDAO dao;

    public BaseDAO getDao() {
        if (dao == null) {
            dao = new BaseDAO();
        }
        return dao;
    }

    @POST
    @Path("operation/save")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString save(Map<String, Object> paramMap) {
        List<Map<String, Object>> paramList = (List) paramMap.get("array");
        return saveold(paramList);
    }

    public JSONString saveold(List<Map<String, Object>> paramList) {
        try {
            for (Map<String, Object> map : paramList) {
                if (!map.containsKey(HEADTABLE) || !map.containsKey(BODYTABLE)) {
                    return ResultMessageUtil.exceptionToJSON("传入参数不能为空", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
                }
            }

            IAPISaleOrderMaitain service = (IAPISaleOrderMaitain) NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class);
            SaleOrderVO[] results = service.save(paramList);

            return ResultMessageUtil.toJSON(results, "销售订单新增保存成功");
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    /**
     * @Description: 在2312基础上适配2005代码
     * @date: 2025年3月19日 18点11分
     * @version NCC2312
     */
    @SuppressWarnings("unchecked")
    @POST
    @Path("save")
    @Consumes("application/json")
    @Produces("application/json")
    public JSONString save(List<Map<String, Object>> paramList) {
        InvocationInfoProxy.getInstance().setGroupId("0001A110000000000677");
        try {
            for (Map<String, Object> map : paramList) {
                if (!map.containsKey(HEADTABLE) || !map.containsKey(BODYTABLE)) {
                    return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildHeadBodyResult());
                }
                // 设置集团
                Map<String, Object> headdata = (Map<String, Object>) map.get(HEADTABLE);
                headdata.put("pk_org", headdata.get("pk_org_v"));
                headdata.put("cdeptid", headdata.get("cdeptvid"));
                headdata.put("fstatusflag", 1);
                headdata.put("dmakedate", headdata.get("dbilldate"));
                headdata.put("dmakedate", headdata.get("dbilldate"));
                headdata.put("cinvoicecustid", headdata.get("ccustomerid"));
                headdata.put("ccustomervid", headdata.get("ccustomerid"));
                String pk_group = AppContext.getInstance().getPkGroup();
                headdata.put("pk_group", pk_group);
                List<Object> bodyArr = (List<Object>) map.get(BODYTABLE);
                for (Object body : bodyArr) {
                    Map<String, Object> bodydata = (Map<String, Object>) body;
                    bodydata.put("pk_group", pk_group);
                    bodydata.put("cprojectid", headdata.get("vdef6"));
                    // bodydata.put("ctrafficorgvid", headdata.get("pk_org_v"));
                    bodydata.put("csendstockorgvid", headdata.get("pk_org_v"));
                    // bodydata.put("csendstordocid", headdata.get("pk_org_v"));
                    bodydata.put("csendstockorgid", headdata.get("pk_org_v"));
                    bodydata.put("carorgid", headdata.get("pk_org_v"));
                    bodydata.put("carorgvid", headdata.get("pk_org_v"));
                    bodydata.put("csettleorgid", headdata.get("pk_org_v"));
                    bodydata.put("csettleorgvid", headdata.get("pk_org_v"));
                    bodydata.put("ctaxcountryid", "CN");
                    bodydata.put("crececountryid", "CN");
                    bodydata.put("csendcountryid", "CN");
                    bodydata.put("fbuysellflag", 1);
                    // 根据物料编码查询物料信息
                    setMaterl(bodydata);
                }
            }
            // 新增自定义档案
            SaleOrderVO[] salevos = OpenAPIParaUtil.changeVO(paramList, HEADTABLE, BODYTABLE);
            log.error("销售订单根据自定义项创建档案开始-----------------------");
            List<DefdocVO> defdocVOS = genDef(salevos);

            for (Map<String, Object> map : paramList) {
                BaseDAO baseDAO = new BaseDAO();
                Map<String, Object> headdata = (Map<String, Object>) map.get(HEADTABLE);
                List<Object> bodyArr = (List<Object>) map.get(BODYTABLE);
                for (Object body : bodyArr) {
                    Map<String, Object> bodydata = (Map<String, Object>) body;
                    String sql = " select pk_project from  bd_project  where project_code='" + headdata.get("vdef6") + "'  and nvl(dr,0)=0  ";
                    String o_pk_project = (String) baseDAO.executeQuery(sql, new ColumnProcessor());
                    bodydata.put("cprojectid", o_pk_project);
                }
            }

            // 参数形式转换为vo并翻译
            List<SaleOrderVO> vosList = TransferMapToVOTool.transferMapToAggVO(paramList, SaleOrderVO.class);
            //根据返回的defdocVOS先行翻译
            if(defdocVOS!=null && defdocVOS.size()>0){
                Map<String,Map<String,String>> deflist_map = new HashMap<>();
                for(DefdocVO defdocVO : defdocVOS){
                    String pkDefdoclist = defdocVO.getPk_defdoclist();
                    String code = defdocVO.getCode();
                    String pkDefdoc = defdocVO.getPk_defdoc();
                    log.error("销售订单保存接口：档案列表编号【"+pkDefdoclist+"】，档案编号【"+code+"】，档案主键【"+pkDefdoc+"】");
                    if(deflist_map.containsKey(pkDefdoclist)){
                        Map<String, String> stringStringMap = deflist_map.get(pkDefdoclist);
                        if(!stringStringMap.containsKey(code)){
                            stringStringMap.put(code, pkDefdoc);
                        }
                    }else{
                        Map<String, String> code_DefdocMap = new HashMap<>();
                        code_DefdocMap.put(code, pkDefdoc);
                        deflist_map.put(pkDefdoclist, code_DefdocMap);
                    }
                }
                for(SaleOrderVO saleOrderVO : vosList){
                    SaleOrderHVO parentVO = saleOrderVO.getParentVO();
                    String vdef6 = BFPubTools.getString_TrimAsNull(parentVO.getVdef6());
                    String vdef2 = BFPubTools.getString_TrimAsNull(parentVO.getVdef2());
                    String vdef13 = BFPubTools.getString_TrimAsNull(parentVO.getVdef13());
                    if (vdef6 != "") {
                        Map<String, String> stringStringMap = deflist_map.get("zdy-001");
                        if(stringStringMap!=null&&stringStringMap.size()>0){
                            String defpk = stringStringMap.get(vdef6);
                            if(defpk!=null){
                                parentVO.setVdef6(defpk);
                            }
                        }
                    }
                    if (vdef2 != "") {
                        Map<String, String> stringStringMap = deflist_map.get("BQxmh");
                        if(stringStringMap!=null&&stringStringMap.size()>0){
                            String defpk = stringStringMap.get(vdef2);
                            if(defpk!=null){
                                parentVO.setVdef2(defpk);
                            }
                        }
                    }
                    if (vdef13 != "") {
                        Map<String, String> stringStringMap = deflist_map.get("BIP-ddh");
                        if(stringStringMap!=null&&stringStringMap.size()>0){
                            String defpk = stringStringMap.get(vdef13);
                            if(defpk!=null){
                                parentVO.setVdef13(defpk);
                            }
                        }
                    }
                    //表体自定义项翻译--vbdef1值与vdef6相同，vbdef5与vdef13相同
                    SaleOrderBVO[] childrenVO = saleOrderVO.getChildrenVO();
                    for(SaleOrderBVO saleOrderBVO : saleOrderVO.getChildrenVO()){
                        String vbdef1 = saleOrderBVO.getVbdef1();
                        Map<String, String> zdy_001 = deflist_map.get("zdy-001");
                        if(zdy_001!=null&&zdy_001.size()>0){
                            String defpk = zdy_001.get(vbdef1);
                            if(defpk!=null){
                                saleOrderBVO.setVbdef1(defpk);
                            }
                        }
                        String vbdef5 = saleOrderBVO.getVbdef5();
                        Map<String, String> bip_ddh = deflist_map.get("BIP-ddh");
                        if(bip_ddh!=null&&bip_ddh.size()>0){
                            String defpk = bip_ddh.get(vbdef5);
                            if(defpk!=null){
                                saleOrderBVO.setVbdef5(defpk);
                            }
                        }
                    }
                }
            }else{
                log.error("销售订单保存接口：新增/已存在的档案没有，可能json自定义项无值");
            }
            //翻译前打印各个档案值
            for (SaleOrderVO saleOrderVO : vosList) {
                SaleOrderHVO parentVO = saleOrderVO.getParentVO();
                log.error("销售订单保存接口：vdef6【"+parentVO.getVdef6()+"】，vdef2【"+parentVO.getVdef2()+"】，vdef13【"+parentVO.getVdef13()+"】");
            }
            vosList = TransferCodeToPKTool.transferAggVO(vosList);
            SaleOrderVO[] vos = vosList.toArray(new SaleOrderVO[vosList.size()]);

            // 调用接口保存
            IAPISaleOrderMaitain service = NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class);
            SaleOrderVO[] results = service.save(vos);
            log.error("销售订单根据自定义项创建档案结束-----------------------");
            // 包装返回信息
            return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildSuccessResult(results, "销售订单保存成功"));
        } catch (Exception e) {
            log.error("销售订单根据自定义项创建档案结束-----------------------");
            return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildFailResult(null, "销售单保存异常:" + e.getMessage()));
        }
    }

    private List<DefdocVO> genDef(SaleOrderVO[] salevos) throws BusinessException {
        BaseDAO baseDAO = new BaseDAO();
        List<DefdocVO> allDefDoc = new ArrayList<DefdocVO>();
        ArrayList<String> arrhth = new ArrayList<String>();
        ArrayList<String> arrxmh = new ArrayList<String>();
        ArrayList<String> arrxsddh = new ArrayList<String>();
        String sql = " select pk_org,pk_vid from org_orgs where org_orgs.code='" + salevos[0].getParentVO().getPk_org() + "' and nvl(dr,0)=0 and isbusinessunit='Y' ";

        Map map = (Map) baseDAO.executeQuery(sql, new MapProcessor());
        if (map == null) {
            throw new BusinessException("采购组织档案未查到");
        }
        String o = (String) map.get("pk_org");

        String cprocode = salevos[0].getChildrenVO()[0].getCprojectid();
        String cproname = salevos[0].getChildrenVO()[0].getVbdef10();
        if (!BFPubTools.getString_TrimAsNull(cprocode).equals("")) {
            sql = " select pk_project from  bd_project  where project_code='" + cprocode + "'  and  pk_duty_org='" + o + "' and nvl(dr,0)=0  ";
            String o_pk_project = (String) baseDAO.executeQuery(sql, new ColumnProcessor());
            if (o_pk_project == null) {
                // 新增项目档案
                createPro(cprocode, cproname, map);
            }
        }

        for (int i = 0; i < salevos.length; i++) {
            String vdef6 = BFPubTools.getString_TrimAsNull(salevos[i].getParentVO().getVdef6());
            if (vdef6 != "" && !arrhth.contains(vdef6)) {
                arrhth.add(vdef6);
            }

            String vdef2 = BFPubTools.getString_TrimAsNull(salevos[i].getParentVO().getVdef2());
            if (vdef2 != "" && !arrxmh.contains(vdef2)) {
                arrxmh.add(vdef2);
            }

            String vdef13 = BFPubTools.getString_TrimAsNull(salevos[i].getParentVO().getVdef13());
            if (vdef13 != "" && !arrxsddh.contains(vdef13)) {
                arrxsddh.add(vdef13);
            }

        }
        if (arrhth.size() > 0) {
            sql = " pk_defdoclist in(select pk_defdoclist from bd_defdoclist  where code='zdy-001') and pk_org='" + o + "' and  ";
            sql += BFPubTools.getInSqlWithOutAnd("code", arrhth, 0, arrhth.size());
//            ArrayList<String> obj_arrhth = (ArrayList<String>) baseDAO.executeQuery(sql, new ColumnListProcessor());
            List<DefdocVO> obj_arrhth = (List<DefdocVO>) dao.retrieveByClause(DefdocVO.class, sql);
            if (obj_arrhth != null && obj_arrhth.size() > 0) {
                List<String> defCode=new ArrayList<>();
                obj_arrhth.stream().forEach(defdoc -> {defdoc.setPk_defdoclist("zdy-001");defCode.add(defdoc.getCode());});
                arrhth.removeAll(defCode);
                allDefDoc.addAll(obj_arrhth);
            }
        }

        // 组装销售订单数据
        if (arrhth.size() > 0) {
            DefdocVO[] defdocVOS = NCLocator.getInstance().lookup(IDefdocService.class).insertDefdocs(o, createDefVO(arrhth, "zdy-001", o.toString()));
            Arrays.stream(defdocVOS).forEach(defdoc -> defdoc.setPk_defdoclist("zdy-001"));
            allDefDoc.addAll(Arrays.asList(defdocVOS));
        }

        if (arrxmh.size() > 0) {
            sql = " pk_defdoclist in(select pk_defdoclist from bd_defdoclist  where code='BQxmh') and pk_org='" + o + "' and ";
            sql += BFPubTools.getInSqlWithOutAnd("code", arrxmh, 0, arrxmh.size());
//            ArrayList<String> obj_arrhth = (ArrayList<String>) baseDAO.executeQuery(sql, new ColumnListProcessor());
            List<DefdocVO> obj_arrhth = (List<DefdocVO>) dao.retrieveByClause(DefdocVO.class, sql);
            if (obj_arrhth != null && obj_arrhth.size() > 0) {
                List<String> defCode=new ArrayList<>();
                obj_arrhth.stream().forEach(defdoc -> {defdoc.setPk_defdoclist("BQxmh");defCode.add(defdoc.getCode());});
                arrxmh.removeAll(defCode);
                allDefDoc.addAll(obj_arrhth);
            }

        }
        if (arrxmh.size() > 0) {
            DefdocVO[] defdocVOS = NCLocator.getInstance().lookup(IDefdocService.class).insertDefdocs(o, createDefVO(arrxmh, "BQxmh", o.toString()));
            Arrays.stream(defdocVOS).forEach(defdoc -> defdoc.setPk_defdoclist("BQxmh"));
            allDefDoc.addAll(Arrays.asList(defdocVOS));
        }

        if (arrxsddh.size() > 0) {
            sql = " pk_defdoclist in( select pk_defdoclist from bd_defdoclist  where code='BIP-ddh') and pk_org='" + o + "' and  ";
            sql += BFPubTools.getInSqlWithOutAnd("code", arrxsddh, 0, arrxsddh.size());
//            ArrayList<String> obj_arrhth = (ArrayList<String>) baseDAO.executeQuery(sql, new ColumnListProcessor());
            List<DefdocVO> obj_arrhth = (List<DefdocVO>) dao.retrieveByClause(DefdocVO.class, sql);
            if (obj_arrhth != null && obj_arrhth.size() > 0) {
                List<String> defCode=new ArrayList<>();
                obj_arrhth.stream().forEach(defdoc -> {defdoc.setPk_defdoclist("BIP-ddh");defCode.add(defdoc.getCode());});
                arrxsddh.removeAll(defCode);
                allDefDoc.addAll(obj_arrhth);
            }
        }
        if (arrxsddh.size() > 0) {
            DefdocVO[] defdocVOS = NCLocator.getInstance().lookup(IDefdocService.class).insertDefdocs(o, createDefVO(arrxsddh, "BIP-ddh", o.toString()));
            Arrays.stream(defdocVOS).forEach(defdoc -> defdoc.setPk_defdoclist("BIP-ddh"));
            allDefDoc.addAll(Arrays.asList(defdocVOS));
        }
        return allDefDoc;
    }

    private void createPro(String cprocode, String cproname, Map map) throws BusinessException {
        String pk_org = (String) map.get("pk_org");
        String pk_org_v = (String) map.get("pk_vid");

        ProjectHeadVO hvo = new ProjectHeadVO();
        hvo.setProject_code(cprocode);
        hvo.setProject_name(cproname);
        hvo.setPk_org(pk_org);
        hvo.setPk_org_v(pk_org_v);

        hvo.setBill_type("4D10");
        hvo.setCreationtime(new UFDateTime());
        hvo.setCreator(InvocationInfoProxy.getInstance().getUserId());
        hvo.setPk_group(InvocationInfoProxy.getInstance().getGroupId());
        hvo.setDr(0);
        hvo.setPk_duty_org(pk_org);
        hvo.setTransi_type("4D10-01");
        hvo.setPk_eps("1001A110000000004K64");
        hvo.setPk_duty_dept_v(pk_org_v);
        hvo.setEnablestate(2);
        NCLocator.getInstance().lookup(IProject.class).insertProject(hvo);
    }

    private DefdocVO[] createDefVO(List<String> newhth, String defdoclistcode, String pk_org) throws BusinessException {
        String sql = " select pk_defdoclist from bd_defdoclist  where code='" + defdoclistcode + "' ";
        String o = (String) getDao().executeQuery(sql, new ColumnProcessor());

        ArrayList<DefdocVO> arrvo = new ArrayList<DefdocVO>();
        for (int i = 0; i < newhth.size(); i++) {
            DefdocVO vo = new DefdocVO();
            vo.setEnablestate(2);
            vo.setPk_defdoclist(o);
            vo.setPk_org(pk_org);
            vo.setCode(newhth.get(i));
            vo.setName(newhth.get(i));
            vo.setDataoriginflag(0);
            vo.setDr(0);
            vo.setPk_group(InvocationInfoProxy.getInstance().getGroupId());
            vo.setCreator(InvocationInfoProxy.getInstance().getUserId());
            vo.setCreationtime(new UFDateTime());

            arrvo.add(vo);
        }

        return arrvo.toArray(new DefdocVO[arrvo.size()]);

    }

    private void setMaterl(Map<String, Object> bodydata) throws BusinessException {
        String sql = " select a.pk_material,a.pk_source, a.pk_measdoc cunitid,nvl(b.pk_measdoc,a.pk_measdoc) castunitid,nvl(b.measrate,'1/1') measrate from bd_material a left join bd_materialconvert  b on a.pk_material=b.pk_material where a.code='" + bodydata.get("cmaterialvid") + "'  ";
        Map map = (Map) getDao().executeQuery(sql, new MapProcessor());
        if (map == null) {
            throw new BusinessException(bodydata.get("cmaterialvid") + "物料未查到");
        }
        bodydata.put("castunitid", map.get("castunitid"));
        bodydata.put("vchangerate", map.get("measrate"));
        // 重新计算金额
        bodydata.put("cqtunitid", map.get("castunitid"));
        bodydata.put("cunitid", map.get("cunitid"));

        bodydata.put("cmaterialid", map.get("pk_material"));
        bodydata.put("cmaterialvid", map.get("pk_source"));

        bodydata.put("nqtunitnum", BFPubTools.getUFDouble_NullAsZero(bodydata.get("nnum")).div(BFPubTools.getUFDouble_NullAsZero(map.get("measrate").toString().split("/")[0])));

        bodydata.put("nastnum", BFPubTools.getUFDouble_NullAsZero(bodydata.get("nnum")).div(BFPubTools.getUFDouble_NullAsZero(map.get("measrate").toString().split("/")[0])));
        sql = "select sl.pk_taxcode from bd_taxrate sl inner join bd_taxcode sm on sl.pk_taxcode=sm.pk_taxcode  where sl.taxrate=" + bodydata.get("ntaxrate") + " and sm.pk_group<>'~' " + "";

        String o_pk_project = (String) getDao().executeQuery(sql, new ColumnProcessor());
        bodydata.put("ctaxcodeid", o_pk_project);

    }

    @POST
    @Path("update")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString update(Map<String, Object> paramMap) {
        try {
            if (paramMap == null || !paramMap.containsKey(HEADTABLE) || !paramMap.containsKey(BODYTABLE)) {
                return ResultMessageUtil.exceptionToJSON("传入参数不能为空", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
            }
            List<Map<String, Object>> paramList = new ArrayList<Map<String, Object>>();

            paramList.add(paramMap);

            IAPISaleOrderMaitain service = (IAPISaleOrderMaitain) NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class);
            SaleOrderVO[] results = service.update(paramList);

            // return ResultMessageUtil.toJSON(results, "销售订单修改成功");
            // 包装返回信息
            return NCCRestUtils.toJSONString(CallReturnBuildUtil.buildSuccessResult(results, "销售订单修改成功"));
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    @POST
    @Path("operation/delete")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString delete(Map<String, Object> paramMap) {
        ArrayList<String> paramArray = (ArrayList) paramMap.get("csaleorderid");
        String[] hids = (String[]) paramArray.toArray(new String[0]);
        return delete(hids);
    }

    @POST
    @Path("delete")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString delete(String[] hids) {
        if (hids == null || hids.length == 0) {
            return ResultMessageUtil.exceptionToJSON("传入参数为空,请检查", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
        }

        try {
            ((IAPISaleOrderMaitain) NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class)).delete(hids);
            String[] arr = new String[0];
            return ResultMessageUtil.toJSON(arr, "销售订单删除成功");
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(new BusinessException("删除销售订单出现异常", e));
        }
    }

    @POST
    @Path("querybyscheme")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString queryByScheme(Map<String, Object> paramMap) {
        SaleOrderVO[] resultVOs = null;

        try {
            resultVOs = ((IAPISaleOrderQuery) NCLocator.getInstance().lookup(IAPISaleOrderQuery.class)).queryByScheme(paramMap);

            return ResultMessageUtil.toJSON(resultVOs, "查询销售订单成功");
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    @POST
    @Path("sendapprove")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString sendApprove(Map<String, Object> paramMap) {
        SaleOrderVO[] sendApprove = null;
        ArrayList<String> paramArray = (ArrayList) paramMap.get("csaleorderid");
        String[] hids = (String[]) paramArray.toArray(new String[0]);
        if (hids == null || hids.length == 0) {
            return ResultMessageUtil.exceptionToJSON("传入参数为空,请检查", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
        }

        try {
            sendApprove = ((IAPISaleOrderMaitain) NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class)).sendApprove(hids);
            return ResultMessageUtil.toJSON(sendApprove, "销售订单提交成功");
        } catch (BusinessException e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    @POST
    @Path("unsend")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString unSendApprove(Map<String, Object> paramMap) {
        SaleOrderVO[] unSend = null;
        ArrayList<String> paramArray = (ArrayList) paramMap.get("csaleorderid");
        String[] hids = (String[]) paramArray.toArray(new String[0]);
        if (hids == null || hids.length == 0) {
            return ResultMessageUtil.exceptionToJSON("传入参数为空,请检查", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
        }

        try {
            unSend = ((IAPISaleOrderMaitain) NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class)).unSendApprove(hids);
            return ResultMessageUtil.toJSON(unSend, "销售订单收回成功");
        } catch (BusinessException e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    @POST
    @Path("approve")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString approve(Map<String, Object> paramMap) {
        SaleOrderVO[] aprove = null;
        ArrayList<String> paramArray = (ArrayList) paramMap.get("csaleorderid");
        String[] hids = (String[]) paramArray.toArray(new String[0]);
        if (hids == null || hids.length == 0) {
            return ResultMessageUtil.exceptionToJSON("传入参数为空,请检查", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
        }
        try {
            aprove = ((IAPISaleOrderMaitain) NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class)).approve(hids);
            return ResultMessageUtil.toJSON(aprove, "销售订单审批成功");
        } catch (BusinessException e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    @POST
    @Path("unapprove")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString unApprove(Map<String, Object> paramMap) {
        SaleOrderVO[] unaprove = null;
        ArrayList<String> paramArray = (ArrayList) paramMap.get("csaleorderid");
        String[] hids = (String[]) paramArray.toArray(new String[0]);
        if (hids == null || hids.length == 0) {
            return ResultMessageUtil.exceptionToJSON("传入参数为空,请检查", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
        }
        try {
            unaprove = ((IAPISaleOrderMaitain) NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class)).unApprove(hids);
            return ResultMessageUtil.toJSON(unaprove, "销售订单取消审批成功");
        } catch (BusinessException e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    /**
     * 金思维Mes修改BIP销售订单明细
     *
     * @author mzr
     * @date 2025/05/14
     */
    @POST
    @Path("updateDef")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString updateDef(Map<String, Object> paramMap) {
        String csaleorderbid = (String) paramMap.get("csaleorderbid");
        if (StringUtils.isEmpty(csaleorderbid)) {
            return ResultMessageUtil.exceptionToJSON("传入参数为空,请检查", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
        }
        try {
            StringBuilder sql = new StringBuilder("update so_saleorder_b set ");
            SQLParameter parameter = new SQLParameter();
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                if ("csaleorderbid".equals(entry.getKey()) ||
                        "csaleorderid".equals(entry.getKey()) ||
                        entry.getKey().startsWith("vdef")
                ) {
                    continue;
                }
                sql.append(entry.getKey()).append(" = ?, ");
                parameter.addParam(entry.getValue());
            }
            if (parameter.getCountParams() <= 0) {
                return ResultMessageUtil.toJSON("传入参数为空,请检查", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
            }
            // 删除最后的", "
            sql.delete(sql.length() - 2, sql.length());
            sql.append(" where csaleorderbid = ?");
            // NCCForUAPLogger.debug("updateDef-sql:" + sql);
            parameter.addParam(csaleorderbid);
            BaseDAO baseDAO = new BaseDAO();
            // 修改销售订单子表
            int num = baseDAO.executeUpdate(sql.toString(), parameter);
            if (num > 0) {
                // 回写合同平台的对应字段
                NCLocator.getInstance().lookup(IAPISaleOrderMaitain.class).updateBipFlagSo(paramMap);
            }
            return ResultMessageUtil.toJSON(num, "销售订单修改成功,共修改" + num + "行");
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    /**
     * 合同管理系统修改ERP销售订单明细
     *
     * @author mzr
     * @date 2025/05/28
     */
    @POST
    @Path("updateDefs")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString updateDefs(List<Map<String, Object>> paramList) {
        int num = 0;
        try {
            for (Map<String, Object> paramMap : paramList) {
                String csaleorderbid = (String) paramMap.get("csaleorderbid");
                if (StringUtils.isEmpty(csaleorderbid)) {
                    return ResultMessageUtil.exceptionToJSON("传入参数为空,请检查", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
                }
                StringBuilder sql = new StringBuilder("update so_saleorder_b set ");
                SQLParameter parameter = new SQLParameter();
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    if (!"csaleorderbid".equals(entry.getKey())) {
                        sql.append(entry.getKey()).append(" = ?, ");
                        parameter.addParam(entry.getValue());
                    }
                }
                if (parameter.getCountParams() <= 0) {
                    return ResultMessageUtil.toJSON("传入参数为空,请检查", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
                }
                // 删除最后的", "
                sql.delete(sql.length() - 2, sql.length());
                sql.append(" where csaleorderbid = ?");
                parameter.addParam(csaleorderbid);
                BaseDAO baseDAO = new BaseDAO();
                num += baseDAO.executeUpdate(sql.toString(), parameter);
            }
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
        return ResultMessageUtil.toJSON(num, "销售订单修改成功,共修改" + num + "行");

    }

}
