package nc.impl.mmbd.bchange.bchangemaster;

import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.UUID;
import java.lang.String;
import java.util.stream.Stream;
import nc.vo.pub.lang.UFDateTime;
import nc.uap.utils.InSQLCreator;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.beanutils.PropertyUtils;
import nc.vo.bd.meta.BDObjectAdpaterFactory;
import nc.vo.bd.meta.IBDObject;
import nc.vo.bd.meta.IBDObjectAdapterFactory;

import nc.vo.pub.BusinessException;
import nc.vo.pub.BusinessRuntimeException;
import nc.vo.pub.SuperVO;
import nc.vo.pub.VOStatus;
import nc.codeplatform.framework.service.ServiceSupport;


import nc.vo.bchange.bchange.BchangeMasterVO;
import nc.itf.mmbd.bchange.bchangemaster.IBchangeMasterVOService;


import nc.bs.framework.common.InvocationInfoProxy;
import nccloud.framework.core.exception.ExceptionUtils;

public class  BchangeMasterVOServiceImpl extends ServiceSupport implements IBchangeMasterVOService {

	public BchangeMasterVOServiceImpl() {
		super("3b2de27c-86f9-42bc-acc5-5c9a4bb48ba5");
	}


	@Override
	public BchangeMasterVO[] listBchangeMasterVOByPk(String[] pks,  boolean blazyLoad) throws BusinessException{
		return dao.listByPk(BchangeMasterVO.class, pks, blazyLoad);
	}

	@Override
	public  BchangeMasterVO findBchangeMasterVOByPk(String pk, boolean blazyLoad) throws BusinessException{
		return dao.findByPk(BchangeMasterVO.class, pk, blazyLoad);
	}

	@Override
	public  BchangeMasterVO[] listBchangeMasterVOByPk(String condition, boolean blazyLoad) throws BusinessException{
		return dao.listByCondition(BchangeMasterVO.class, condition, blazyLoad);
	}
	@Override
	public String[] listBchangeMasterVOPkByCond(String condition) throws BusinessException{
		return listBchangeMasterVOPkByCond(condition,new String[]{"pk_bchangemaster"});
	}
	@Override
	public String[] listBchangeMasterVOPkByCond(String condition,String[] orderPath) throws BusinessException{
		if(StringUtils.isEmpty(condition)) {
			condition = " 1 = 1 ";
		}
		StringBuilder sql = new StringBuilder();
		sql.append(" select pk_bchangemaster from ").append(BchangeMasterVO.getDefaultTableName());
		sql.append(" where ").append(condition);
		if (ArrayUtils.isNotEmpty(orderPath)) {
			sql.append(" order by ").append(StringUtils.join(orderPath, ", "));
		}
		return (String[]) dao.getBaseDAO().executeQuery(sql.toString(), (rs) -> {
			List<String> pks = new ArrayList<>();
			while (rs.next()) {
				pks.add(rs.getString(1));
			}
			return pks.toArray(new String[0]);
		});
	}
	@Override
	public void initDefaultData(BchangeMasterVO vo){
		if(vo.getAttributeValue("pk_group") == null){
			vo.setAttributeValue("pk_group",InvocationInfoProxy.getInstance().getGroupId());
		}
	}
	@Override
	public BchangeMasterVO preAddBchangeMasterVO(BchangeMasterVO vo,Map<String,Object> userJson) throws BusinessException{

		getMainVO(vo).setStatus(VOStatus.NEW);
		initDefaultData((BchangeMasterVO)getMainVO(vo));
		String pk_org = InvocationInfoProxy.getInstance().getGroupId();

		//下面这段要判断是否是树表界面插件
		Map<String,String> data = userJson!=null && userJson.get("data") != null?(Map<String,String>)userJson.get("data"):null;
		if(data!=null && data.size()>0){
			String parentKey = data.get("parentKey");
			String parentPk = data.get("parentPk");
			getMainVO(vo).setAttributeValue(parentKey,parentPk);
		}


		return vo;
	}
	@Override
	public BchangeMasterVO preAddBchangeMasterVO(Map<String,Object> userJson) throws BusinessException{
		BchangeMasterVO result = null;

		BchangeMasterVO mainvo = new BchangeMasterVO();
		//设置默认值
		initDefaultData(mainvo);

		result = mainvo;
		return preAddBchangeMasterVO(result,userJson);
	}

	@Override
	public BchangeMasterVO preEditBchangeMasterVO(String pk) throws BusinessException{
		return dao.findByPkWithDr(BchangeMasterVO.class, pk, true);
	}
	@Override
	public BchangeMasterVO copyBchangeMasterVO(String pk) throws BusinessException{

		BchangeMasterVO vo = dao.findByPkWithDr(BchangeMasterVO.class, pk, false);

		if (vo == null) {
			throw new BusinessException("没有查到对应的数据，请重试");
		}

		getMainVO(vo).setPrimaryKey(null);
		getMainVO(vo).setStatus(VOStatus.NEW);

		getMainVO(vo).setAttributeValue("srcbilltype",null);
		getMainVO(vo).setAttributeValue("srcbillid",null);

		getMainVO(vo).setAttributeValue("code",null);
		getMainVO(vo).setAttributeValue("",null);
		getMainVO(vo).setAttributeValue("name",null);
		String defaultGroup = InvocationInfoProxy.getInstance().getGroupId();
		getMainVO(vo).setAttributeValue("pk_group",defaultGroup);
		getMainVO(vo).setAttributeValue("", new UFDateTime(InvocationInfoProxy.getInstance().getBizDateTime()));
		getMainVO(vo).setAttributeValue("", null);

		return vo;
	}

	public BchangeMasterVO[] saveBchangeMasterVO(BchangeMasterVO vo ) throws BusinessException{
		return this.saveBchangeMasterVO(vo, null);
	}

	public BchangeMasterVO[] saveBchangeMasterVO(BchangeMasterVO vo , String nodetype ) throws BusinessException{
        lockUtils.lock(vo);
		String pk = getVOPrimaryKey(vo);
		setDefaultVal(vo);
		if(StringUtils.isEmpty(pk)){
			return insert(vo); //插入
		}else{
			return update(vo); //更新
		}
	}

	/**
	 * 保存前处理一些默认值
	 * @param vos
	 */
	private void setDefaultVal(BchangeMasterVO... vos) throws BusinessException {
		//其他默认值处理
	}

	// 给单表（行编辑表）单独适配
	@Override
	public BchangeMasterVO[] saveBchangeMasterVO(BchangeMasterVO[] vos) throws BusinessException {
		return this.saveBchangeMasterVO(vos, null);
	}

	public BchangeMasterVO[] saveBchangeMasterVO(BchangeMasterVO[] vos , String nodetype ) throws BusinessException {
		if (ArrayUtils.isEmpty(vos)) {
			return new BchangeMasterVO[0];
		}
        lockUtils.lock(vos);
		setDefaultVal(vos); // 设置默认值
		return save(vos,true);
	}

	@Override
	public BchangeMasterVO[] deleteBchangeMasterVOs(Map<String,String> tsMap) throws BusinessException{
		 return deleteBchangeMasterVOs(tsMap, null);
	}
	@Override
	public BchangeMasterVO[] deleteBchangeMasterVOs(Map<String,String> tsMap, String nodetype) throws BusinessException{
		BchangeMasterVO[] vos = dao.listByPk(BchangeMasterVO.class,tsMap.keySet().toArray(new String[0]));
		if (vos == null || vos.length == 0) {
			throw new BusinessException("没有查到对应的数据，请重试");
		}

		lockUtils.lock(vos);
		validate(vos,tsMap);
		
		delete(vos,true);
        
		return vos;
	}

	//校验  包括ts校验  已提交校验
	private void validate(BchangeMasterVO[] vos,Map<String,String> tsMap) throws BusinessException{

		Boolean isPass = true;
		String error = "";    //错误信息
		if(ArrayUtils.isEmpty(vos)){
			isPass = false;
		}

		for(int i = 0 ; i < vos.length ; i++){
			SuperVO mainvo = vos[i];
			UFDateTime ts = (UFDateTime)mainvo.getAttributeValue("ts");
			if(!StringUtils.equals(tsMap.get(mainvo.getPrimaryKey()),ts.toString())){
				isPass = false;
				break;
			}
		}
		if(!isPass) {
			throw new BusinessException("您操作的数据已被他人修改或删除，请刷新后重试！");
		}
		if(!"".equals(error)){
			throw new BusinessException(error);
		}
	}

	@Override
	public <T> T[] loadTreeData(Class<T> clazz,Map<String,Object> userJson) throws BusinessException{
		String condition = "dr = 0 ";

		return dao.listByCondition(clazz, condition, false);
	}



}
