/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-06-26
 * 描述            ：成本对象基础表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;
import java.util.Date;
import java.util.List;

import market.Cm.mapper.BaseCostItemMapper;
import market.Cm.mapper.BaseCostObjectMapper;
import market.Cm.mapper.BaseObjectCmpMapper;
import market.Cm.service.BaseCostObjectService;
import market.Cm.vo.BaseCostItem;
import market.Cm.vo.BaseCostObject;
import market.Cm.vo.BaseObjectCmp;
import market.Com.pb.TreeNodeHelper;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Com.vo.TreeNode;

import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path="BaseCostObjectService")
public class BaseCostObjectServiceImpl extends BaseServiceImpl<BaseCostObject,Object> implements BaseCostObjectService {

	/**
	 * 查询成本对象
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryBaseCostObject(CommonPage<BaseCostObject> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		BaseCostObject bco = cp.getObject();
		try {
			String swhere = "";
			if (bco.getObject_name()!=null && !"".equals(bco.getObject_name())) {
				swhere+=" and t.object_name like  '%"+bco.getObject_name()+"%'";//对象名称
			}
			if (bco.getObject_code()!=null && !"".equals(bco.getObject_code())) {
				swhere+=" and t.object_code = '"+bco.getObject_code()+"'";//对象代码
			}
			if (bco.getParent_object_name()!=null && !"".equals(bco.getParent_object_name())) {
				swhere+=" and t.parent_object_name like  '%"+bco.getParent_object_name()+"%'";//父类名称
			}
			if (bco.getParent_object_code()!=null && !"".equals(bco.getParent_object_code())) {
				swhere+=" and t.parent_object_code = '"+bco.getParent_object_code()+"'";//父类代码
			}
			if (bco.getValid_flg()!=null && !"".equals(bco.getValid_flg())) {
				swhere+=" and t.valid_flg = '"+bco.getValid_flg()+"'"; //是否有效
			}
			if (bco.getObject_type()!=null && !"".equals(bco.getObject_type())) {
				swhere+=" and t.object_type = '"+bco.getObject_type()+"'"; //对象类型(A汇总项 B明细项)
			}
			if (bco.getObject_grade()!=null && !"".equals(bco.getObject_grade())) {
				swhere+=" and t.object_grade = "+bco.getObject_grade().longValue(); //对象级别
			}
			List<BaseCostObject> lists = this.getMapper(BaseCostObjectMapper.class).doQueryBaseCostObject(swhere);
			rm.setData(lists);
			rm.setState("200");
			rm.setMsgInfo("查询成功");
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}	
	
	/**
	 * 成本基础数据树查询
	 * @param sum
	 * memo1 为 父节点值
	 * memo2 为 valid_flag值 1为有效 0无效
	 * @return
	 */
	public ResultModel findBaseObjectTreeNode(CommonPage<TreeNode> cp){
		ResultModel rm=new ResultModel();
		try{
			String parent_code = cp.getMemo1();
			List<TreeNode> ltn=this.getMapper(BaseCostObjectMapper.class).findBaseObjectTreeNode(parent_code,cp.getMemo2());
			TreeNodeHelper th=new TreeNodeHelper();
			List<TreeNode> lt = th.GetTreeJsonByList(ltn, parent_code);
			rm.setData(lt);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("服务端异常，获取数据失败!");
		}
		return rm;
	}
	
	/**
	 * 新增成本对象
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertBaseCostObject(CommonPage<BaseCostObject> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		List<BaseCostObject> bcoList = cp.getObjectList();
		if (bcoList==null || bcoList.size()<=0) {
			throw new Exception("请传入参数");
		}
		Date now = new Date();
		for (BaseCostObject bco : bcoList) {
			//必填项验证
			this.doCheckBaseCostObject(bco);
			
			//验证[相同父类下]是否存在重复的成本对象名称
			BaseCostObject BCO = new BaseCostObject();
			//BCO.setParent_object_code(bco.getParent_object_code());//第一级的父类编码默认为0
			BCO.setObject_name(bco.getObject_name());
			int count = this.getMapper(BaseCostObjectMapper.class).count(BCO);
			if (count > 0) {
				throw new Exception("已经存在相同的成本对象名称【"+bco.getObject_name()+"】");
			}
			
			//生成项目的等级
			if ("".equals(bco.getParent_object_code())) {//第一级树结构
				bco.setObject_grade(1L);
			}else {//不是第一级目录（第二，第三级树结构）
				//查询上级项目的信息
				BaseCostObject b = this.getMapper(BaseCostObjectMapper.class).findById(bco.getParent_object_code());
				if (b==null) {
					throw new Exception("上级成本对象不存在");
				}
				if (b.getObject_grade().longValue() == 3) {
					throw new Exception("成本对象等级最多到3级");//上层成本对象到第3级了,则不允许继续加子对象
				}
				bco.setObject_grade(b.getObject_grade()+1);					
			}
			
			//生成项目代码(ID)
			BCO = new BaseCostObject();
			BCO.setParent_object_code(bco.getParent_object_code());
			BCO.setParent_object_name(bco.getParent_object_name());
			List<BaseCostObject> list = this.getMapper(BaseCostObjectMapper.class).findWithCondition(BCO, null, "object_code desc", 0, 0);
			if (list==null || list.size()<=0) {
				//如果当前父类项目下不存在子项目
				if (bco.getObject_grade().longValue() == 1) {//第一级编码
					bco.setObject_code("CP001");						
				}else {
					bco.setObject_code(bco.getParent_object_code()+"001");
				}
			}else {
				//如果当前父类项目下存在子项目，则流水号+1
				String maxCode = list.get(0).getObject_code();
				String seq = maxCode.substring(maxCode.length()-3);
				int iseq = Integer.parseInt(seq) + 1;						
				if (bco.getObject_grade().longValue() == 1) {//第一层
					bco.setObject_code("CP" + String.format("%03d", iseq));
				}else {//其它层			
					bco.setObject_code(bco.getParent_object_code() + String.format("%03d", iseq));
				}			
			}							
			bco.setCreate_man(userName);
			bco.setCreate_time(now);
			this.getMapper(BaseCostObjectMapper.class).insert(bco);
			
			//2.生成项目对照关系 //第3层生成成本对象对照关系
			if (bco.getObject_grade().longValue() == 3 && bco.getCmp_code()!=null && !"".equals(bco.getCmp_code())) {
				BaseObjectCmp bic = new BaseObjectCmp();
				bic.setObject_code(bco.getObject_code());
				bic.setObject_name(bco.getObject_name());
				bic.setCmp_code(bco.getCmp_code());
				bic.setCmp_name(bco.getCmp_name());
				bic.setMdl_code(bco.getMdl_code());
				bic.setMdl_name(bco.getMdl_name());
				bic.setValid_flg("1");
				bic.setCreate_man(userName);
				bic.setCreate_time(now);
				this.getMapper(BaseObjectCmpMapper.class).insert(bic);
			}			
		}
		rm.setState("200");
		rm.setMsgInfo("新增成功");
		return rm;
	}
	
	/**
	 * 修改成本对象
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doUpdateBaseCostObject(CommonPage<BaseCostObject> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		BaseCostObject bco = cp.getObject();
		if (bco==null) {
			throw new Exception("请传入参数");
		}
		//必填项验证
		this.doCheckBaseCostObject(bco);
				 
		BaseCostObject BCO = this.getMapper(BaseCostObjectMapper.class).findById(bco.getObject_code());
		if (BCO==null) {
			throw new Exception("当前选择的成本对象不存在，请重新查询");
		}
		if ("0".equals(BCO.getValid_flg())) {
			throw new Exception("成本对象【"+BCO.getObject_name()+"】已经禁用，无法修改");
		}
		//判断相同父类下的子类项目名称是否重复
		/*String condition = "object_code <> '"+bco.getObject_code()+"' and org_name = '"+bco.getObject_name()+"' "
				+ "and parent_object_code = '"+bco.getParent_object_code()+"'";*/
		//判断项目名称是否重复
		String condition = "object_code <> '"+bco.getObject_code()+"' and object_name = '"+bco.getObject_name()+"'";	
		List<BaseCostObject> list = this.getMapper(BaseCostObjectMapper.class).findWithCondition(null, condition, null, 0, 0);
		if (list!=null && list.size()>0) {
			throw new Exception("存在相同的成本对象名称，无法修改");
		}
		bco.setUpdate_man(userName);
		bco.setUpdate_time(new Date());
		this.getMapper(BaseCostObjectMapper.class).update(bco);
		//第3级，同步修改项目对照关系
		this.getMapper(BaseObjectCmpMapper.class).updateBaseObjectCmpByObjectCode(bco.getObject_code(),bco.getObject_name());
		 
		rm.setState("200");
		rm.setMsgInfo("修改成功");
		return rm;
	}
	
	/**
	 * 启用/禁止 成本对象
	 * @param cp memo1[0:禁用    1:启用]
	 * @return
	 * @throws Exception
	 */
	public ResultModel doChangeBaseCostObjectValidFlg(CommonPage<BaseCostObject> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		String opr = cp.getMemo1();
		String reslut = null;
		BaseCostObject bco = cp.getObject();
		if (bco.getObject_code()==null || "".equals(bco.getObject_code())) {
			throw new Exception("请传入对象代码");
		}
		bco.setUpdate_man(userName);
		bco.setUpdate_time(new Date());
		if ("1".equals(opr)) {//启用
			bco.setValid_flg("1");
			reslut = "启用";
		}else if ("0".equals(opr)) { //禁用
			bco.setValid_flg("0");
			reslut = "禁用";
		}
		this.getMapper(BaseCostObjectMapper.class).update(bco);
		rm.setState("200");
		rm.setMsgInfo(reslut + "操作成功");
		return rm;
	}
	
	/**
	 * 删除成本对象
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteBaseCostObject(CommonPage<BaseCostObject> cp) throws Exception{
		ResultModel rm = new ResultModel();
		BaseCostObject bco = cp.getObject();
		if (bco.getObject_code()==null || "".equals(bco.getObject_code())) {
			throw new Exception("请传入对象代码");
		}
		//判断当前成本对象下面是否存在子对象
		BaseCostObject BCO = new BaseCostObject();
		BCO.setParent_object_code(bco.getObject_code());		
		List<BaseCostObject> list = this.getMapper(BaseCostObjectMapper.class).find(BCO, 0, 0);
		if (list!=null && list.size()>0) {
			throw new Exception("当前成本对象下存在子级的成本对象，请先删除子级的成本对象");
		}
		//删除成本对象
		this.getMapper(BaseCostObjectMapper.class).delete(bco.getObject_code());
		//如果有成本对象对照关系，删除对照关系
		this.getMapper(BaseObjectCmpMapper.class).deleteByObjectCode(bco.getObject_code());
		rm.setState("200");
		rm.setMsgInfo("删除成功");
		return rm;
	}
	
	/**
	 * 成本对象的有效性验证
	 * @param bco
	 * @throws Exception
	 */
	public void doCheckBaseCostObject(BaseCostObject bco) throws Exception{
		if (bco.getObject_name()==null || "".equals(bco.getObject_name())) {
			throw new Exception("对象名称不能为空");
		}
		if (bco.getObject_type()==null || "".equals(bco.getObject_type())) {
			throw new Exception("对象类型不能为空");
		}
	}
	
	/**
	 * 成本对象：对照项目选择成本项目
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQuaryObjectCmp(CommonPage<BaseCostObject> cp) throws Exception{
		ResultModel rm = new ResultModel();
		BaseCostObject bco = cp.getObject();
		if (bco.getParent_object_code()==null || "".equals(bco.getParent_object_code())) {
			throw new Exception("请传入父级对象代码");
		}
		if (bco.getParent_object_name()==null || "".equals(bco.getParent_object_name())) {
			throw new Exception("请传入父级对象名称");
		}		
		BaseCostItem bci = new BaseCostItem();
		bci.setParent_item_name(bco.getParent_object_name());
		List<BaseCostItem> list = this.getMapper(BaseCostItemMapper.class).find(bci, 0, 0);
		rm.setData(list);
		rm.setState("200");
		rm.setMsgInfo("删除成功");
		return rm;
	} 
	
}
