package nccloud.api.uapbd.materialmanage.material;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.core.util.ObjectCreator;
import nc.impl.pubapp.pattern.database.SqlBuilderUtil;
import nc.itf.bd.material.assign.IMaterialAssignService;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.material.prod.MaterialProdVO;
import nc.vo.bd.material.sale.MaterialSaleVO;
import nc.vo.bd.material.stock.MaterialStockVO;
import nc.ws.opm.pub.utils.result.APIErrCodeEnum;
import nccloud.api.baseapp.exchange.convert.IOpenApiJsonConvertToExChangeXmlService;
import nccloud.api.baseapp.exchange.convert.OpenApiConvertDataObject;
import nccloud.api.baseapp.exchange.convert.OpenApiConvertDataResult;
import nccloud.api.rest.utils.ApiResourceParamUtils;
import nccloud.api.rest.utils.IParamTranslator;
import nccloud.api.rest.utils.OpenApiPageInfo;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.api.uapbd.common.utils.OpenApiPagenationUtils;
import nccloud.commons.lang.StringUtils;
import nccloud.ws.rest.resource.AbstractNCCRestResource;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物料接口适配2312
 */

@Path("uapbd/material/material")
public class MaterialManageMaterial extends AbstractNCCRestResource {
	private static final String defbilltype = "material";

	@POST
	@Path("add")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString addMaterial(JSONString json) {
		return process(json);
	}

	/**
	 * 
	 * @param json {"code":"COM24111300019","version":"1","pk_org":"PLM"}
	 * @return
	 */
	@POST
	@Path("queryMaterialIsExist")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })

	public JSONString queryMaterialIsExist(JSONString json) {

		boolean bool = false;// false 不存在 true 存在

		JSONObject jObject = JSONObject.parseObject(json.toJSONString());
		if (jObject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
		}

		if (StringUtils.isEmpty(jObject.getString("code"))) {
			return ResultMessageUtil.exceptionToJSON("code 不能为空", APIErrCodeEnum.UNKNOWEXCCODE.getCode());
		}
		String code = jObject.getString("code");
		String version = jObject.getString("version");
		String pk_org = jObject.getString("pk_org");// 所属组织编码

		String sql = "select  bd_material.code,bd_material.version,org_orgs.code From bd_material , org_orgs where  bd_material.pk_org=org_orgs.pk_org and  bd_material.code='"
				+ code + "'";

		if (!StringUtils.isEmpty(version)) {
			sql += " and bd_material.version ='" + jObject.get("version") + "'";
		}

		if (!StringUtils.isEmpty(pk_org)) {
			sql += " and org_orgs.code ='" + jObject.get("pk_org") + "'";
		}

		try {
			ArrayList<HashMap<String, String>> lists = (ArrayList<HashMap<String, String>>) new BaseDAO()
					.executeQuery(sql, new MapListProcessor());
			if (lists != null && lists.size() > 0) {
				bool = true;
				return ResultMessageUtil.toJSONUnTranslate(bool);
			} else {
				bool = false;
				return ResultMessageUtil.toJSONUnTranslate(bool, "没有符合条件的数据");
			}
		} catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ResultMessageUtil.toJSONUnTranslate(bool);

	}

	@POST
	@Path("update")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString updateMaterial(JSONString json) {
		return process(json);
	}

	@POST
	@Path("queryMaterial")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString queryMaterial(JSONString json) {
		JSONObject jObject = JSON.parseObject(json.toJSONString());
		if (jObject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
		}
		JSONObject bject = jObject.getJSONObject("ufinterface");
		if (bject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("ufinterface:null"));
		}

		JSONObject data = bject.getJSONObject("data");
		String pk_group = data.getString("pk_group");
		JSONArray pk_orgs = data.getJSONArray("pk_org");
		JSONArray code = data.getJSONArray("code");
		JSONArray name = data.getJSONArray("name");
		JSONArray marbaseclass = data.getJSONArray("marbaseclass");
		String enablestate = data.getString("enablestate");
		String ts = data.getString("ts");
		JSONObject pageInfo = data.getJSONObject("pageInfo");
		Map<String, Object> param = new HashMap<String, Object>();

		if (StringUtils.isNotBlank(pk_group)) {
			param.put("pk_group", pk_group);
		}
		if (StringUtils.isNotBlank(enablestate)) {
			param.put("enablestate", enablestate);
		}
		if (StringUtils.isNotBlank(ts)) {
			param.put("ts", ts);
		}
		if (pk_orgs != null && pk_orgs.size() > 0) {
			param.put("pk_org", pk_orgs.toArray(new String[0]));
		}
		if (code != null && code.size() > 0) {
			param.put("code", code.toArray(new String[0]));
		}
		if (name != null && name.size() > 0) {
			param.put("name", name.toArray(new String[0]));
		}
		if (marbaseclass != null && marbaseclass.size() > 0) {
//			param.put("marbaseclass", marbaseclass.toArray(new String[0]));
			//数据库无此字段，修改成
			param.put("pk_marbasclass", marbaseclass.toArray(new String[0]));
		}
		try {
			ApiResourceParamUtils ApiResourceParamUtils = new ApiResourceParamUtils();
			IParamTranslator IParamTranslator = (IParamTranslator) ObjectCreator.newInstance("uapbd",
					nccloud.api.uapbd.translator.OrgParamTranslator.class.getName());
			ApiResourceParamUtils.addTranslatorMap("pk_org", IParamTranslator);
			String condition = ApiResourceParamUtils.parseParmToSqlByCode(new MaterialVO(), param);

			if (condition.isBlank()) {
				condition = "1=1";// 没有条件就拼接个1=1,防止sql报错
			}

			String sql = "select pk_material from bd_material where " + condition;
			List<String> allPks = (List) (new BaseDAO()).executeQuery(sql, new ColumnListProcessor());
			OpenApiPageInfo openApiPageInfo = new OpenApiPageInfo();
			String[] currPks = OpenApiPagenationUtils.getCurrentPagePksAndPageInfo(allPks, pageInfo, openApiPageInfo);
			if (currPks == null || currPks.length == 0) {
				return ResultMessageUtil.toJSON(null);
			}

			SqlBuilderUtil SqlBuilderUtil = new SqlBuilderUtil();
			String wherepart = SqlBuilderUtil.buildSQL("pk_material", currPks, null);

			MaterialVO[] vos = (MaterialVO[]) (new BaseDAO()).retrieveByClause(MaterialVO.class, wherepart)
					.toArray(new MaterialVO[0]);
			ResultMessageUtil.toJSONByPage(vos, openApiPageInfo, false);
			return ResultMessageUtil.toJSONByPage(vos, openApiPageInfo, false);
		} catch (Exception e) {
			return ResultMessageUtil.exceptionToJSON(e);
		}
	}

	@POST
	@Path("assignMaterial")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString assignMaterial(JSONString json) {
		JSONObject jObject = JSON.parseObject(json.toJSONString());
		if (jObject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
		}
		JSONObject bject = jObject.getJSONObject("ufinterface");
		if (bject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("ufinterface:null"));
		}

		JSONObject data = bject.getJSONObject("data");
		String pk_org = data.getString("pk_org");
		String code = data.getString("code");
		String version = data.getString("version");
		JSONArray assignorgs = data.getJSONArray("assignorgs");

		JSONObject pageInfo = data.getJSONObject("pageInfo");
		Map<String, Object> param = new HashMap<String, Object>();

		if (StringUtils.isBlank(pk_org) && StringUtils.isBlank(code) && StringUtils.isBlank(version)) {
			return ResultMessageUtil.exceptionToJSON(new Exception("所属组织、物料编码、版本号,不能同时为空"));
		}
		if (assignorgs == null || (assignorgs != null && assignorgs.size() <= 0)) {
			return ResultMessageUtil.exceptionToJSON(new Exception("分配组织不能为空"));
		}
		if (StringUtils.isNotBlank(pk_org)) {
			param.put("pk_org", pk_org);
		}
		if (StringUtils.isNotBlank(code)) {
			param.put("code", code);
		}
		if (StringUtils.isNotBlank(version)) {
			param.put("version", version);
		}
		try {
			ApiResourceParamUtils ApiResourceParamUtils = new ApiResourceParamUtils();
			IParamTranslator IParamTranslator = (IParamTranslator) ObjectCreator.newInstance("uapbd",
					nccloud.api.uapbd.translator.OrgParamTranslator.class.getName());
			ApiResourceParamUtils.addTranslatorMap("pk_org", IParamTranslator);
			String condition = ApiResourceParamUtils.parseParmToSqlByCode(new MaterialVO(), param);

			MaterialVO[] vos = (MaterialVO[]) (new BaseDAO()).retrieveByClause(MaterialVO.class, condition)
					.toArray(new MaterialVO[0]);
			if (vos == null || (vos != null && vos.length <= 0)) {
				return ResultMessageUtil.exceptionToJSON(new Exception("未查询到物料信息"));
			}
			IMaterialAssignService IMaterialAssignService = (IMaterialAssignService) NCLocator.getInstance()
					.lookup(IMaterialAssignService.class);
			if (vos != null && vos.length > 0) {
				List<String> pk_materials = new ArrayList<String>();
				for (MaterialVO vo : vos) {
					pk_materials.add(vo.getPk_material());
				}
				if (assignorgs != null && assignorgs.size() > 0) {
					List<String> pk_orgs = IParamTranslator.translateByCode(null,
							(String[]) assignorgs.toArray(new String[0]));
					IMaterialAssignService.assignMaterialByPks((String[]) pk_materials.toArray(new String[0]),
							(String[]) pk_orgs.toArray(new String[0]), null);
				}
			}
			return ResultMessageUtil.toJSON(null, "分配成功！");
		} catch (Exception e) {
			return ResultMessageUtil.exceptionToJSON(e);
		}
	}

	@POST
	@Path("queryMaterialsale")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString queryMaterialsale(JSONString json) {
		JSONObject jObject = JSON.parseObject(json.toJSONString());
		if (jObject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
		}
		JSONObject bject = jObject.getJSONObject("ufinterface");
		if (bject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("ufinterface:null"));
		}

		JSONObject data = bject.getJSONObject("data");
		String pk_org = data.getString("pk_org");
		String code = data.getString("code");
		String version = data.getString("version");
		JSONArray saleorgs = data.getJSONArray("saleorgs");
		JSONObject pageInfo = data.getJSONObject("pageInfo");
		Map<String, Object> param = new HashMap<String, Object>();

		if (StringUtils.isNotBlank(pk_org)) {
			param.put("pk_org", pk_org);
		}
		if (StringUtils.isNotBlank(code)) {
			param.put("code", code);
		}
		if (StringUtils.isNotBlank(version)) {
			param.put("version", version);
		}

		if (StringUtils.isBlank(pk_org) && StringUtils.isBlank(code)) {
			return ResultMessageUtil.exceptionToJSON(new Exception("所属组织和编码 pk_org、code不能同时为空"));
		}

		if (saleorgs == null || saleorgs.size() == 0) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("saleorgs:" + saleorgs + "，不能为空"));
		}
		try {
			ApiResourceParamUtils ApiResourceParamUtils = new ApiResourceParamUtils();
			IParamTranslator IParamTranslator = (IParamTranslator) ObjectCreator.newInstance("uapbd",
					nccloud.api.uapbd.translator.OrgParamTranslator.class.getName());
			ApiResourceParamUtils.addTranslatorMap("pk_org", IParamTranslator);
			String condition = ApiResourceParamUtils.parseParmToSqlByCode(new MaterialVO(), param);
			MaterialVO[] vos = (MaterialVO[]) (new BaseDAO()).retrieveByClause(MaterialVO.class, condition)
					.toArray(new MaterialVO[0]);

			if (vos != null && vos.length > 0) {
				List<String> materialpks = new ArrayList<String>();
				for (MaterialVO vo : vos) {
					materialpks.add(vo.getPk_material());
				}
				param.clear();
				param.put("pk_material", materialpks.toArray(new String[0]));
				if (saleorgs != null && saleorgs.size() > 0) {
					param.put("pk_org", saleorgs.toArray(new String[0]));
				}
				String condition1 = ApiResourceParamUtils.parseParmToSqlByCode(new MaterialVO(), param);

				String sql = "select pk_materialsale from bd_materialsale where " + condition1;
				List<String> allPks = (List) (new BaseDAO()).executeQuery(sql, new ColumnListProcessor());
				OpenApiPageInfo openApiPageInfo = new OpenApiPageInfo();
				String[] currPks = OpenApiPagenationUtils.getCurrentPagePksAndPageInfo(allPks, pageInfo,
						openApiPageInfo);
				if (currPks == null || currPks.length == 0) {
					return ResultMessageUtil.toJSON(null);
				}

				SqlBuilderUtil SqlBuilderUtil = new SqlBuilderUtil();
				String wherepart = SqlBuilderUtil.buildSQL("pk_materialsale", currPks, null);

				MaterialSaleVO[] salevos = (MaterialSaleVO[]) (new BaseDAO())
						.retrieveByClause(MaterialSaleVO.class, wherepart).toArray(new MaterialSaleVO[0]);
				return ResultMessageUtil.toJSONByPage(salevos, openApiPageInfo, false);
			}
		} catch (Exception e) {
			return ResultMessageUtil.exceptionToJSON(e);
		}
		return null;
	}

	@POST
	@Path("queryMaterialprod")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString queryMaterialprod(JSONString json) {
		JSONObject jObject = JSON.parseObject(json.toJSONString());
		if (jObject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
		}
		JSONObject bject = jObject.getJSONObject("ufinterface");
		if (bject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("ufinterface:null"));
		}

		JSONObject data = bject.getJSONObject("data");
		String pk_org = data.getString("pk_org");
		String code = data.getString("code");
		String version = data.getString("version");
		JSONArray prodorgs = data.getJSONArray("prodorgs");
		JSONObject pageInfo = data.getJSONObject("pageInfo");
		Map<String, Object> param = new HashMap<String, Object>();

		if (StringUtils.isNotBlank(pk_org)) {
			param.put("pk_org", pk_org);
		}
		if (StringUtils.isNotBlank(code)) {
			param.put("code", code);
		}
		if (StringUtils.isNotBlank(version)) {
			param.put("version", version);
		}
		if (StringUtils.isBlank(pk_org) && StringUtils.isBlank(code)) {
			return ResultMessageUtil.exceptionToJSON(new Exception("所属组织和编码 pk_org、code不能同时为空"));
		}
		if (prodorgs == null || prodorgs.size() == 0) {
			return ResultMessageUtil.exceptionToJSON(new Exception("prodorgs:" + prodorgs + "，不能为空"));
		}
		try {
			ApiResourceParamUtils ApiResourceParamUtils = new ApiResourceParamUtils();
			IParamTranslator IParamTranslator = (IParamTranslator) ObjectCreator.newInstance("uapbd",
					nccloud.api.uapbd.translator.OrgParamTranslator.class.getName());
			ApiResourceParamUtils.addTranslatorMap("pk_org", IParamTranslator);
			String condition = ApiResourceParamUtils.parseParmToSqlByCode(new MaterialVO(), param);
			MaterialVO[] vos = (MaterialVO[]) (new BaseDAO()).retrieveByClause(MaterialVO.class, condition)
					.toArray(new MaterialVO[0]);

			if (vos != null && vos.length > 0) {
				List<String> materialpks = new ArrayList<String>();
				for (MaterialVO vo : vos) {
					materialpks.add(vo.getPk_material());
				}
				param.clear();
				param.put("pk_material", materialpks.toArray(new String[0]));
				if (prodorgs != null && prodorgs.size() > 0) {
					param.put("pk_org", prodorgs.toArray(new String[0]));
				}
				String condition1 = ApiResourceParamUtils.parseParmToSqlByCode(new MaterialVO(), param);

				String sql = "select pk_materialprod from bd_materialprod where " + condition1;
				List<String> allPks = (List) (new BaseDAO()).executeQuery(sql, new ColumnListProcessor());
				OpenApiPageInfo openApiPageInfo = new OpenApiPageInfo();
				String[] currPks = OpenApiPagenationUtils.getCurrentPagePksAndPageInfo(allPks, pageInfo,
						openApiPageInfo);
				if (currPks == null || currPks.length == 0) {
					return ResultMessageUtil.toJSON(null);
				}

				SqlBuilderUtil SqlBuilderUtil = new SqlBuilderUtil();
				String wherepart = SqlBuilderUtil.buildSQL("pk_materialprod", currPks, null);
				MaterialProdVO[] prodvos = (MaterialProdVO[]) (new BaseDAO())
						.retrieveByClause(MaterialProdVO.class, wherepart).toArray(new MaterialProdVO[0]);
				return ResultMessageUtil.toJSONByPage(prodvos, openApiPageInfo, false);
			}
		} catch (Exception e) {
			return ResultMessageUtil.exceptionToJSON(e);
		}
		return null;
	}

	@POST
	@Path("queryMaterialstock")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString queryMaterialstock(JSONString json) {
		JSONObject jObject = JSON.parseObject(json.toJSONString());
		if (jObject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
		}
		JSONObject bject = jObject.getJSONObject("ufinterface");
		if (bject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("ufinterface:null"));
		}

		JSONObject data = bject.getJSONObject("data");
		String pk_org = data.getString("pk_org");
		String code = data.getString("code");
		String version = data.getString("version");
		JSONArray stockorgs = data.getJSONArray("stockorgs");
		JSONObject pageInfo = data.getJSONObject("pageInfo");
		Map<String, Object> param = new HashMap<String, Object>();

		if (StringUtils.isNotBlank(pk_org)) {
			param.put("pk_org", pk_org);
		}
		if (StringUtils.isNotBlank(code)) {
			param.put("code", code);
		}
		if (StringUtils.isNotBlank(version)) {
			param.put("version", version);
		}

		if (StringUtils.isBlank(pk_org) && StringUtils.isBlank(code)) {
			return ResultMessageUtil.exceptionToJSON(new Exception("所属组织和编码 pk_org、code不能同时为空"));
		}

		if (stockorgs == null || stockorgs.size() == 0) {
			return ResultMessageUtil.exceptionToJSON(new Exception("stockorgs:" + stockorgs + "，不能为空"));
		}
		try {
			ApiResourceParamUtils ApiResourceParamUtils = new ApiResourceParamUtils();
			IParamTranslator IParamTranslator = (IParamTranslator) ObjectCreator.newInstance("uapbd",
					nccloud.api.uapbd.translator.OrgParamTranslator.class.getName());
			ApiResourceParamUtils.addTranslatorMap("pk_org", IParamTranslator);
			String condition = ApiResourceParamUtils.parseParmToSqlByCode(new MaterialVO(), param);
			MaterialVO[] vos = (MaterialVO[]) (new BaseDAO()).retrieveByClause(MaterialVO.class, condition)
					.toArray(new MaterialVO[0]);

			if (vos != null && vos.length > 0) {
				List<String> materialpks = new ArrayList<String>();
				for (MaterialVO vo : vos) {
					materialpks.add(vo.getPk_material());
				}
				param.clear();
				param.put("pk_material", materialpks.toArray(new String[0]));
				if (stockorgs != null && stockorgs.size() > 0) {
					param.put("pk_org", stockorgs.toArray(new String[0]));
				}
				String condition1 = ApiResourceParamUtils.parseParmToSqlByCode(new MaterialVO(), param);

				String sql = "select pk_materialstock from bd_materialstock where " + condition1;
				List<String> allPks = (List) (new BaseDAO()).executeQuery(sql, new ColumnListProcessor());
				OpenApiPageInfo openApiPageInfo = new OpenApiPageInfo();
				String[] currPks = OpenApiPagenationUtils.getCurrentPagePksAndPageInfo(allPks, pageInfo,
						openApiPageInfo);
				if (currPks == null || currPks.length == 0) {
					return ResultMessageUtil.toJSON(null);
				}

				SqlBuilderUtil SqlBuilderUtil = new SqlBuilderUtil();
				String wherepart = SqlBuilderUtil.buildSQL("pk_materialstock", currPks, null);
				MaterialStockVO[] stockvos = (MaterialStockVO[]) (new BaseDAO())
						.retrieveByClause(MaterialStockVO.class, wherepart).toArray(new MaterialStockVO[0]);
				return ResultMessageUtil.toJSONByPage(stockvos, openApiPageInfo, false);
			}
		} catch (Exception e) {
			return ResultMessageUtil.exceptionToJSON(e);
		}
		return null;
	}

	private JSONString process(JSONString json) {
		JSONObject jObject = JSON.parseObject(json.toJSONString());
		if (jObject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
		}
		JSONObject bject = jObject.getJSONObject("ufinterface");
		if (bject == null) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException("ufinterface:null"));
		}
		String billtype = bject.getString("billtype");
		String account = bject.getString("account");
		String groupcode = bject.getString("groupcode");
		if (!"material".equals(billtype)) {
			return ResultMessageUtil.exceptionToJSON(new NullPointerException(
					"billtype:" + billtype + ",account:" + account + ",groupcode:" + groupcode));
		}

		OpenApiConvertDataObject openApiConvertDataObject = new OpenApiConvertDataObject();
		openApiConvertDataObject.setAccount(account);
		openApiConvertDataObject.setBilltype(billtype);
		openApiConvertDataObject.setGroupcode(groupcode);
		openApiConvertDataObject.setOpenApiJsonData(jObject);

		try {
			OpenApiConvertDataResult r = getIOpenApiJsonConvertToExChangeXmlService()
					.changeToExchangeData(openApiConvertDataObject);
			if (r != null) {
				return ResultMessageUtil.toJSON(r.getDesc());
			}
		} catch (Exception e) {
			return ResultMessageUtil.exceptionToJSON(e);
		}
		return ResultMessageUtil.exceptionToJSON(new Exception("未知异常"));
	}

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

	private IOpenApiJsonConvertToExChangeXmlService getIOpenApiJsonConvertToExChangeXmlService() {
		return (IOpenApiJsonConvertToExChangeXmlService) NCLocator.getInstance()
				.lookup(IOpenApiJsonConvertToExChangeXmlService.class);
	}
}
