/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-08-26
 * 描述            ：资材备件需求审批(单独流程)
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Pms.Demand.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import market.Com.mapper.ComBaseInfoMapper;
import market.Com.pb.SpeOptBaseService;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Demand.mapper.PurDemandMatMapper;
import market.Pms.Demand.service.PurDemandMatService;
import market.Pms.Demand.vo.PurDemandMat;
import market.Pms.Mat.mapper.PurMatClassMapper;
import market.Pms.Mat.mapper.PurMatMMapper;
import market.Pms.Mat.vo.PurMatClass;
import market.Pms.Mat.vo.PurMatM;

import org.apache.commons.collections.CollectionUtils;
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="PurDemandMatService")
public class PurDemandMatServiceImpl extends BaseServiceImpl<PurDemandMat,Object> implements PurDemandMatService {

	public ResultModel doQueryPurDemandMat(CommonPage<PurDemandMat> cp) throws Exception {
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		PurDemandMat pdm = cp.getObject();
		if (pdm.getBal_year_month()!=null && pdm.getBal_year_month().length()!=6) {
			throw new Exception("需求年月参数有误");
		}
		if (pdm.getBal_year_month2()!=null && pdm.getBal_year_month2().length()!=6) {
			throw new Exception("需求年月参数有误");
		}
		String page = cp.getMemo1();//采购需求申报0   组织主管审批1   资材备件审批2   主管领导审批3   总经理审批4
		try {
			String condition = "";	
			if (!"管理员".equals(userName)) {				
				if ("0".equals(page)) {
					ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById("6038");
					if (cbi!=null && userName.equals(cbi.getMemo())) {
						//资材备件采购员需要看到所有的采购信息
					}else {
						//其它人员只能看到各自的申报信息
						condition += " and t.apply_man = '"+userName+"'"; 
					}			
				} else if ("1".equals(page)) {// 组织主管审批
					if ("聂飞".equals(userName) || "陈小波".equals(userName)) {
						condition += " and t.state >= '0'";
					}else {						
						condition += " and t.state >= '0' and (t.apply_man like '%"+userName+"%' or t.dept_man like '%"+userName+"%')";
					}
				} else if ("2".equals(page)) { //资材备件审批
					condition += " and t.state >= '1' and t.valid_flag = '1'";
				} else if ("3".equals(page) || "4".equals(page)) {//主管领导审批
					condition += " and t.state >= '2' and t.valid_flag = '1'";
				}		
			}
			
			if (pdm.getBal_year_month()!=null && !"".equals(pdm.getBal_year_month())) {
				condition += " and t.bal_year_month >= '"+pdm.getBal_year_month()+"'";//需求年月开始
			}
			if (pdm.getBal_year_month2()!=null && !"".equals(pdm.getBal_year_month2())) {
				condition += " and t.bal_year_month <= '"+pdm.getBal_year_month2()+"'";//需求年月结束
			}
			
			if (pdm.getMat_class_code()!=null && !"".equals(pdm.getMat_class_code())) {
				condition += " and t.mat_class_code = '"+pdm.getMat_class_code()+"'";//分类代码
			} 
			if (pdm.getMat_class_name()!=null && !"".equals(pdm.getMat_class_name())) {
				condition += " and t.mat_class_name like '%"+pdm.getMat_class_name()+"%'";//分类名称
			}
			if (pdm.getItem_code()!=null && !"".equals(pdm.getItem_code())) {
				condition += " and t.item_code = '"+pdm.getItem_code()+"'";//物料代码
			}
			if (pdm.getItem_name()!=null && !"".equals(pdm.getItem_name())) {
				condition += " and t.item_name like '%"+pdm.getItem_name()+"%'";//物料名称
			}
			if (pdm.getApply_man()!=null && !"".equals(pdm.getApply_man())) {
				condition += " and t.apply_man = '"+pdm.getApply_man()+"'";//申请人
			}
			if (pdm.getState()!=null && !"".equals(pdm.getState())) {
				condition += " and t.state = '"+pdm.getState()+"'";//状态
			}

			List<PurDemandMat> list = this.getMapper(PurDemandMatMapper.class).doQueryPurDemandMat(pdm,condition);//(null, condition, "bal_year_month desc,apply_time desc", 0, 0);
			rm.setData(list);
			rm.setState("200");		
		} catch (Exception ex) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	/**
	 * 新增采购需求申请
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doInsertPurDemandMat(CommonPage<PurDemandMat> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		List<PurDemandMat> lists = cp.getObjectList();
		if (lists==null || lists.size()<=0) {
			throw new Exception("请传入需新增的数据");
		}
		for (PurDemandMat pdm : lists) {
			String demand_no = "XQ" + new SimpleDateFormat("yyyyMM").format(now);
			String maxD = this.getMapper(PurDemandMatMapper.class).findMaxDemandNo(demand_no);
			if (maxD != null && maxD.length() > 4) {
				String seq = maxD.substring(maxD.length() - 4);
				int iseq = Integer.parseInt(seq) + 1;
				demand_no += String.format("%04d", iseq);
			} else {
				demand_no += "0001";
			}
			if (pdm.getApply_department()==null || "".equals(pdm.getApply_department())) {	
				throw new Exception("申请部门不能为空！");
			}
			ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById(pdm.getApply_department());
			if (cbi!=null) {
				pdm.setDept_man(cbi.getMemo());
			}
			pdm.setDemand_no(demand_no);
			pdm.setState("-1");			
			pdm.setApply_man(userName);
			pdm.setApply_time(now);
			//带物料的附件
			PurMatM pmm = this.getMapper(PurMatMMapper.class).findById(pdm.getItem_code());
			if (pmm!=null) {
				pdm.setAnnex_path(pmm.getAnnex_path());
			}
			this.getMapper(PurDemandMatMapper.class).insert(pdm);
		}
		rm.setMsgInfo("新增成功");
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 需求修改
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doUpdatePurDemandMat(CommonPage<PurDemandMat> cp) throws Exception{
		ResultModel rm = new ResultModel();
		PurDemandMat pdm = cp.getObject();
		if (pdm.getDemand_no()==null || "".equals(pdm.getDemand_no())) {
			throw new Exception("请传入需要修改的需求单号");
		}
		if (pdm.getApply_department()!=null && !"".equals(pdm.getApply_department())) {				
			ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById(pdm.getApply_department());
			if (cbi!=null) {
				pdm.setDept_man(cbi.getMemo());
			}
		}
		//判断当前需求是否可以修改
		this.getMapper(PurDemandMatMapper.class).update(pdm);
		rm.setMsgInfo("修改成功");
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 需求删除
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDeletePurDemandMat(CommonPage<PurDemandMat> cp) throws Exception{
		ResultModel rm = new ResultModel();
		List<PurDemandMat> lists = cp.getObjectList();
		if (lists==null || lists.size()<=0) {
			throw new Exception("请勾选需要删除的数据");
		}
		for (PurDemandMat pdm : lists) {
			//判断当前数据是否已经经过审批
			PurDemandMat PDM = this.getMapper(PurDemandMatMapper.class).findById(pdm.getDemand_no());
			if (PDM==null) {
				throw new Exception("未找到需求单号【"+pdm.getDemand_no( )+"】对应的需求申报信息");
			}
			if (Integer.parseInt(PDM.getState()) > 0) {
				throw new Exception("需求单号【"+pdm.getDemand_no()+"已通过上级领导审批，无法删除");
			}
			this.getMapper(PurDemandMatMapper.class).delete(pdm.getDemand_no());
		}		
		rm.setMsgInfo("删除成功");
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 调整需求状态
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doChangePurDemandMatState(CommonPage<PurDemandMat> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		List<PurDemandMat> lists = cp.getObjectList();
		String opr = cp.getMemo1();//1审批   0撤回
		String state = cp.getMemo2();//0个人提报 1部门主管审批 2资材备件审批 3主管领导审批 4总经理审批
		if (lists==null || lists.size()<=0) {
			throw new Exception("请勾选需要操作的数据");
		}
		for (PurDemandMat pdm : lists) {
			//判断当前数据是否存在
			PurDemandMat PDM = this.getMapper(PurDemandMatMapper.class).findById(pdm.getDemand_no());
			if (PDM==null) {
				throw new Exception("未找到需求单号【"+pdm.getDemand_no()+"】对应的需求申报信息");
			}
			
			if ("1".equals(opr)) {
				//审批操作
				if ("0".equals(state)) {
					pdm.setState("0");
				}else if ("1".equals(state)) {
					pdm.setState("1");
					pdm.setOrg_man(userName);
					pdm.setOrg_time(now);
				}else if ("2".equals(state)) {
					pdm.setState("2");
					pdm.setMat_man(userName);
					pdm.setMat_time(now);
				}else if ("3".equals(state)) {
					pdm.setState("3");
					pdm.setLead_man(userName);
					pdm.setLead_time(now);
				}else if ("4".equals(state)) {
					pdm.setState("4");
					pdm.setManage_man(userName);
					pdm.setManage_time(now);
				}
				//pdm.setState(Integer.parseInt(PDM.getState())+1+"");
				this.getMapper(PurDemandMatMapper.class).update(pdm);
			}else if ("0".equals(opr)) {
				//反审操作 
				if ("0".equals(state)) {//撤销申报
					pdm.setState("-1");
					this.getMapper(PurDemandMatMapper.class).doChangePurDemandMatState0(pdm.getDemand_no());
				}else if ("1".equals(state)) {//撤销部门审批
					pdm.setState("0");
					this.getMapper(PurDemandMatMapper.class).doChangePurDemandMatState1(pdm.getDemand_no());
				}else if ("2".equals(state)) {//撤销资材备件审批
					pdm.setState("1");
					this.getMapper(PurDemandMatMapper.class).doChangePurDemandMatState2(pdm.getDemand_no());
				}else if ("3".equals(state)) {//撤销资材备件领导审批
					pdm.setState("2");
					this.getMapper(PurDemandMatMapper.class).doChangePurDemandMatState3(pdm.getDemand_no());
				}else if ("4".equals(state)) {//撤销总经理审批
					pdm.setState("3");
					this.getMapper(PurDemandMatMapper.class).doChangePurDemandMatState4(pdm.getDemand_no());
				}
			}
			
		}		
		rm.setMsgInfo("操作成功");
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 查询物料分类
	 * @param cp
	 * @return
	 */
	public ResultModel doQueryPurMatClass(CommonPage<PurMatClass> cp){
		ResultModel rm=new ResultModel();
		try{
			String condition = " and validflag = '1' and parent_code like 'W02%'";
			List<PurMatClass> list = this.getMapper(PurMatClassMapper.class).findWithCondition(null, condition, "mat_class_code", 0, 0);		
			rm.setData(list);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询错误："+ex.getMessage());
		}
		return rm;
	}
	
	public ResultModel doQueryPurMat(CommonPage<PurMatM> cp){
		ResultModel rm=new ResultModel();
		PurMatM pmm = cp.getObject();
		try{
			String condition = " and mat_class_code like 'W02%' and validflag = '1'";
			if (pmm.getMat_class_code()!=null && !"".equals(pmm.getMat_class_code())) {
				condition += " and mat_class_code = '"+pmm.getMat_class_code()+"'";
			}
			if (pmm.getMat_class_name()!=null && !"".equals(pmm.getMat_class_name())) {
				condition += " and mat_class_name like '%"+pmm.getMat_class_name()+"%'";
			}
			if (pmm.getItem_code()!=null && !"".equals(pmm.getItem_code())) {
				condition += " and item_code = '"+pmm.getItem_code()+"'";
			}
			if (pmm.getItem_name()!=null && !"".equals(pmm.getItem_name())) {
				condition += " and item_name like '%"+pmm.getItem_name()+"%'";
			}
			List<PurMatM> list = this.getMapper(PurMatMMapper.class).findWithCondition(null, condition, "item_name", 0, 0);		
			rm.setData(list);
			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 doReturnPurDemandMat(CommonPage<PurDemandMat> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String oprTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		List<PurDemandMat> pdmList = cp.getObjectList();
		if (CollectionUtils.isEmpty(pdmList)) {
			throw new Exception("请勾选需要回退的数据");
		}
		for (PurDemandMat pdm : pdmList) {
			pdm = this.getMapper(PurDemandMatMapper.class).findById(pdm.getDemand_no());
			pdm.setValid_flag("0");
			pdm.setMemo(oprTime+"物料【"+pdm.getItem_name()+"】被"+userName+"退回");
			this.getMapper(PurDemandMatMapper.class).update(pdm);
		}
		rm.setMsgInfo("回退成功");
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 上传附件保存
	 * @return
	 * @throws Exception 
	 */
	public ResultModel doUpLoadMatFile(CommonPage<PurDemandMat> cp) throws Exception{
		ResultModel rm= new ResultModel();
		PurDemandMat pdm = cp.getObject();
		if(cp.getMemo1()==null){
			throw new Exception("请传入附件路径");
		}
		if(!cp.getMemo1().contains("group1/M00")){
			pdm.setAnnex_path(this.getBean(SpeOptBaseService.class).doAdd(cp.getMemo1()));
		}		
		this.getMapper(PurDemandMatMapper.class).update(pdm);
		rm.setState("200");
		rm.setMsgInfo("附件上传成功");
		return rm;
	}
}
