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

import market.Cm.mapper.BaseCostItemMapper;
import market.Cm.mapper.BaseItemCmpMapper;
import market.Cm.service.BaseCostItemService;
import market.Cm.vo.BaseCostItem;
import market.Cm.vo.BaseItemCmp;
import market.Com.mapper.ComBaseSteelMapper;
import market.Com.pb.TreeNodeHelper;
import market.Com.vo.ComBaseSteel;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Com.vo.TreeNode;
import market.Pms.Mat.mapper.PurMatClassMapper;
import market.Pms.Mat.vo.PurMatClass;

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="BaseCostItemService")
public class BaseCostItemServiceImpl extends BaseServiceImpl<BaseCostItem,Object> implements BaseCostItemService {

	/**
	 * 查询成本项目
	 * @param cp  object[item_name,item_code项目编码,parent_item_name,parent_item_code父级项目,
	 *                   valid_flg是否有效,item_type项目类型,item_grade项目等级]
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryBaseCostItem(CommonPage<BaseCostItem> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		BaseCostItem bci = cp.getObject();
		try {
			String swhere = "";
			if (bci.getItem_name()!=null && !"".equals(bci.getItem_name())) {
				swhere+=" and t.item_name like  '%"+bci.getItem_name()+"%'";//项目名称
			}
			if (bci.getItem_code()!=null && !"".equals(bci.getItem_code())) {
				swhere+=" and t.item_code = '"+bci.getItem_code()+"'";//项目代码
			}
			if (bci.getParent_item_name()!=null && !"".equals(bci.getParent_item_name())) {
				swhere+=" and t.parent_item_name like  '%"+bci.getParent_item_name()+"%'";//父类名称
			}
			if (bci.getParent_item_code()!=null && !"".equals(bci.getParent_item_code())) {
				swhere+=" and (t.parent_item_code = '"+bci.getParent_item_code()+"' or t.item_code = '"+bci.getParent_item_code()+"')";//父类代码
			}
			if (bci.getValid_flg()!=null && !"".equals(bci.getValid_flg())) {
				swhere+=" and t.valid_flg = '"+bci.getValid_flg()+"'"; //是否启用(默认查询所有启用的数据)
			}
			if (bci.getItem_type()!=null && !"".equals(bci.getItem_type())) {
				swhere+=" and t.item_type = '"+bci.getItem_type()+"'"; //项目类型(A汇总项 B明细项)
			}
			if (bci.getItem_grade()!=null && !"".equals(bci.getItem_grade())) {
				swhere+=" and t.item_grade = "+bci.getItem_grade().longValue(); //项目级别
			}
			List<BaseCostItem> lists = this.getMapper(BaseCostItemMapper.class).doQueryBaseCostItem(swhere);
			rm.setData(lists);
			rm.setState("200");
			rm.setMsgInfo("查询成功");
		} catch (Exception e) {
			throw new Exception("查询失败:"+e.getMessage());
		}
		return rm;
	}	
	
	/**
	 * 成本基础数据树查询
	 * @param sum
	 * memo1 为 父节点值
	 * memo2 为 valid_flag[1有效 0无效]
	 * @return
	 */
	public ResultModel findBaseItemTreeNode(CommonPage<TreeNode> cp){
		ResultModel rm=new ResultModel();
		try{
			String parent_code = cp.getMemo1();
			List<TreeNode> ltn=this.getMapper(BaseCostItemMapper.class).findBaseItemTreeNode(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("获取数据失败:"+ex.getMessage());
		}
		return rm;
	}
	
	
	/**
	 * 新增成本项目
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertBaseCostItem(CommonPage<BaseCostItem> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<BaseCostItem> bciList = cp.getObjectList();
		if (bciList==null || bciList.size()<=0) {
			throw new Exception("请传入参数");
		}
		Date now = new Date();
		for (BaseCostItem bci : bciList) {
			//必填项验证
			this.doCheckBaseCostItem(bci);
			
			//验证相同父类下是否存在重复的成本项目名称
			BaseCostItem BCI = new BaseCostItem();
			//BCI.setParent_item_code(bci.getParent_item_code());//第一级的父类编码默认为0
			BCI.setItem_name(bci.getItem_name());
			int count = this.getMapper(BaseCostItemMapper.class).count(BCI);
			if (count > 0) {
				throw new Exception("已经存在相同的成本项目名称【"+bci.getItem_name()+"】");
				//throw new Exception("上级项目【"+bci.getParent_item_name()+"】下已经存在相同的成本项目名称【"+bci.getItem_name()+"】");
			}
			
			//生成项目的等级
			if ("".equals(bci.getParent_item_code())) {
				bci.setItem_grade(1L);
			}else {
				//查询上级项目的信息
				BaseCostItem b = this.getMapper(BaseCostItemMapper.class).findById(bci.getParent_item_code());
				if (b==null) {
					throw new Exception("上级项目不存在");
				}
				if (b.getItem_grade().longValue() == 5) {
					throw new Exception("项目等级最多到5级");//上层项目到第5级了,则不允许继续加子项目
				}
				bci.setItem_grade(b.getItem_grade()+1);					
			}
			
			//生成项目代码(ID)
			BCI = new BaseCostItem();
			BCI.setParent_item_code(bci.getParent_item_code());
			BCI.setParent_item_name(bci.getParent_item_name());
			List<BaseCostItem> list = this.getMapper(BaseCostItemMapper.class).findWithCondition(BCI, null, "item_code desc", 0, 0);
			if (list==null || list.size()<=0) {
				//如果当前父类项目下不存在子项目
				if (bci.getItem_grade().longValue() == 1) {//第一级编码
					bci.setItem_code("CT01");						
				}else if (bci.getItem_grade().longValue() == 5) {//第5层的流水号为3位
					bci.setItem_code(bci.getParent_item_code()+"001");//最后一层
				}else {
					bci.setItem_code(bci.getParent_item_code()+"01");
				}
			}else {
				//如果当前父类项目下存在子项目，则流水号+1
				String maxCode = list.get(0).getItem_code();
				if (bci.getItem_grade().longValue() == 1) {
					String seq = maxCode.substring(maxCode.length()-2);
					int iseq = Integer.parseInt(seq) + 1;						
					bci.setItem_code("CT" + String.format("%02d", iseq));
				}else if (bci.getItem_grade().longValue() == 5) { //第5层的流水号为3位
					String seq = maxCode.substring(maxCode.length()-3);
					int iseq = Integer.parseInt(seq) + 1;						
					bci.setItem_code(bci.getParent_item_code() + String.format("%03d", iseq));
				}else {
					String seq = maxCode.substring(maxCode.length()-2);
					int iseq = Integer.parseInt(seq) + 1;
					bci.setItem_code(bci.getParent_item_code() + String.format("%02d", iseq));
				}			
			}							
			bci.setCreate_man(userName);
			bci.setCreate_time(now);
			this.getMapper(BaseCostItemMapper.class).insert(bci);
			
			//2.生成项目对照关系 //第5层生成项目对照关系
			if (bci.getItem_grade().longValue() == 5 && bci.getCmp_code()!=null && !"".equals(bci.getCmp_code())) {
				BaseItemCmp bic = new BaseItemCmp();
				bic.setItem_code(bci.getItem_code());
				bic.setItem_name(bci.getItem_name());
				bic.setCmp_code(bci.getCmp_code());
				bic.setCmp_name(bci.getCmp_name());
				bic.setMdl_code(bci.getMdl_code());
				bic.setMdl_name(bci.getMdl_name());
				bic.setValid_flg("1");
				bic.setCreate_man(userName);
				bic.setCreate_time(now);
				this.getMapper(BaseItemCmpMapper.class).insert(bic);
			}			
		}
		rm.setState("200");
		rm.setMsgInfo("新增成功");
		return rm;
	}
	
	/**
	 * 修改成本项目
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doUpdateBaseCostItem(CommonPage<BaseCostItem> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		BaseCostItem bci = cp.getObject();
		if (bci==null) {
			throw new Exception("请传入参数");
		}
		//必填项验证
		this.doCheckBaseCostItem(bci);		
		 
		BaseCostItem BCI = this.getMapper(BaseCostItemMapper.class).findById(bci.getItem_code());
		if (BCI==null) {
			throw new Exception("当前选择的成本项目不存在，请重新查询");
		}
		if ("0".equals(BCI.getValid_flg())) {
			throw new Exception("成本项目【"+BCI.getItem_name()+"】已经禁用，无法修改");
		}
		//判断相同父类下的子类项目名称是否重复
		/*String condition = "item_code <> '"+bci.getItem_code()+"' and org_name = '"+bci.getItem_name()+"' "
				+ "and parent_item_code = '"+bci.getParent_item_code()+"'";*/
		//判断项目名称是否重复
		String condition = "item_code <> '"+bci.getItem_code()+"' and item_name = '"+bci.getItem_name()+"'";	
		List<BaseCostItem> list = this.getMapper(BaseCostItemMapper.class).findWithCondition(null, condition, null, 0, 0);
		if (list!=null && list.size()>0) {
			throw new Exception("存在相同的成本项目名称，无法修改");
		}
		bci.setUpdate_man(userName);
		bci.setUpdate_time(new Date());
		this.getMapper(BaseCostItemMapper.class).update(bci);
		//第5级，同步修改项目对照关系
		this.getMapper(BaseItemCmpMapper.class).updateBaseItemCmpByItemCode(bci.getItem_code(),bci.getItem_name());
		 
		rm.setState("200");
		rm.setMsgInfo("修改成功");
		return rm;
	}
	
	/**
	 * 启用/禁止 成本项目基础信息
	 * @param cp memo1[0:禁用    1:启用]
	 * @return
	 * @throws Exception
	 */
	public ResultModel doChangeItemValidFlg(CommonPage<BaseCostItem> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		String opr = cp.getMemo1();
		String reslut = null;
		BaseCostItem bci = cp.getObject();
		if (bci.getItem_code()==null || "".equals(bci.getItem_code())) {
			throw new Exception("请传入项目代码");
		}
		bci.setUpdate_man(userName);
		bci.setUpdate_time(new Date());
		if ("1".equals(opr)) {//启用
			bci.setValid_flg("1");
			reslut = "启用";
		}else if ("0".equals(opr)) { //禁用
			bci.setValid_flg("0");
			reslut = "禁用";
		}
		this.getMapper(BaseCostItemMapper.class).update(bci);
		rm.setState("200");
		rm.setMsgInfo(reslut + "操作成功");
		return rm;
	}
	
	/**
	 * 删除成本项目
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteBaseCostItem(CommonPage<BaseCostItem> cp) throws Exception{
		ResultModel rm = new ResultModel();
		BaseCostItem bci = cp.getObject();
		if (bci.getItem_code()==null || "".equals(bci.getItem_code())) {
			throw new Exception("请传入项目代码");
		}
		//判断当前成本项目下面是否存在子项目
		BaseCostItem BCI = new BaseCostItem();
		BCI.setParent_item_code(bci.getItem_code());		
		List<BaseCostItem> list = this.getMapper(BaseCostItemMapper.class).find(BCI, 0, 0);
		if (list!=null && list.size()>0) {
			throw new Exception("当前成本项目下存在子级的成本项目，请先删除子级的成本项目");
		}
		//删除成本项目
		this.getMapper(BaseCostItemMapper.class).delete(bci.getItem_code());
		//如果有成本项目对照关系，删除对照关系
		this.getMapper(BaseItemCmpMapper.class).deleteByItemCode(bci.getItem_code());
		rm.setState("200");
		rm.setMsgInfo("删除成功");
		return rm;
	}
	
	/**
	 * 物料对照项目，查找物料项目
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQuaryPurMatM(CommonPage<PurMatClass> cp) throws Exception{
		ResultModel rm = new ResultModel();
		try {
			String condition = "validflag = '1' and mat_class_code like 'W02%' ";
			List<PurMatClass> list = this.getMapper(PurMatClassMapper.class).findWithCondition(null, condition, "mat_class_code", 0, 0);
			rm.setData(list);
			rm.setState("200");
			rm.setMsgInfo("查询物料信息成功");
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	/**
	 * 
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQuaryComBaseSteel(CommonPage<ComBaseSteel> cp) throws Exception{
		ResultModel rm = new ResultModel();
		try {
			String condition = "validflag = '1'";
			List<ComBaseSteel> list = this.getMapper(ComBaseSteelMapper.class).findWithCondition(null, condition, "steel_name", 0, 0);
			rm.setData(list);
			rm.setState("200");
			rm.setMsgInfo("查询牌号信息成功");
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	/**
	 * 成本项目的有效性验证
	 * @param bci
	 * @throws Exception
	 */
	public void doCheckBaseCostItem(BaseCostItem bci) throws Exception{
		if (bci.getItem_name()==null || "".equals(bci.getItem_name())) {
			throw new Exception("项目名称不能为空");
		}
		if (bci.getItem_type()==null || "".equals(bci.getItem_type())) {
			throw new Exception("项目类型不能为空");
		}
		if (bci.getCost_type()==null || "".equals(bci.getCost_type())) {
			throw new Exception("成本类型不能为空");
		}
	}
	
	/**
	 * 成本报表开发界面：初始化查询成本组织
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryBaseCostForReport(CommonPage<BaseCostItem> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		BaseCostItem bci = cp.getObject();
		try {
			String swhere = " and parent_item_code not like 'CT010101%' and item_code <> 'CT010101'";
			if (bci.getItem_name()!=null && !"".equals(bci.getItem_name())) {
				swhere+=" and item_name like  '%"+bci.getItem_name()+"%'";//项目名称
			}
			if (bci.getItem_code()!=null && !"".equals(bci.getItem_code())) {
				swhere+=" and item_code = '"+bci.getItem_code()+"'";//项目代码
			}
			if (bci.getParent_item_name()!=null && !"".equals(bci.getParent_item_name())) {
				swhere+=" and parent_item_name like '%"+bci.getParent_item_name()+"%'";//父类名称
			}
			if (bci.getParent_item_code()!=null && !"".equals(bci.getParent_item_code())) {
				swhere+=" and parent_item_code = '"+bci.getParent_item_code()+"'";//父类代码
			}
			if (bci.getValid_flg()!=null && !"".equals(bci.getValid_flg())) {
				swhere+=" and valid_flg = '"+bci.getValid_flg()+"'"; //是否启用(默认查询所有启用的数据)
			}
			if (bci.getItem_type()!=null && !"".equals(bci.getItem_type())) {
				swhere+=" and item_type = '"+bci.getItem_type()+"'"; //项目类型(A汇总项 B明细项)
			}
			if (bci.getItem_grade()!=null && !"".equals(bci.getItem_grade())) {
				swhere+=" and item_grade = "+bci.getItem_grade().longValue(); //项目级别
			}
			List<BaseCostItem> lists = this.getMapper(BaseCostItemMapper.class).findWithCondition(null, swhere, "item_code", 0, 0);
			rm.setData(lists);
			rm.setState("200");
			rm.setMsgInfo("查询成功");
		} catch (Exception e) {
			throw new Exception("查询失败:"+e.getMessage());
		}
		return rm;
	}	
	
}
