/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-07-04
 * 描述            ：资材备件库-库存信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
 ***********************************************************/
package market.Lms.Equipment.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import market.Com.mapper.ComBaseInfoMapper;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Equipment.mapper.YdmEquipmentApplylistMapper;
import market.Lms.Equipment.mapper.YdmEquipmentDetailMapper;
import market.Lms.Equipment.service.YdmEquipmentAppService;
import market.Lms.Equipment.vo.YdmEquipmentApplylist;
import market.Lms.Equipment.vo.YdmEquipmentDetail;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
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 = "YdmEquipmentAppService")
public class YdmEquipmentAppServiceImpl extends BaseServiceImpl<Object, Object> implements YdmEquipmentAppService {

	public ResultModel doQueryEquipmentDetailApp(CommonPage<YdmEquipmentDetail> cp){
		ResultModel rm = new ResultModel();
		YdmEquipmentDetail yed = cp.getObject();
		try {
			String condition = "";
			if (StringUtils.isNotEmpty(yed.getMat_name())) {
				condition += " and mat_name like '%"+yed.getMat_name()+"%'";
			}
			if (StringUtils.isNotEmpty(yed.getMat_code())) {
				condition += " and mat_code like '%"+yed.getMat_code()+"%'";
			}
			if (StringUtils.isNotEmpty(yed.getSrot_name())) {
				condition += " and srot_name like '%"+yed.getSrot_name()+"%'";
			}
			if (StringUtils.isNotEmpty(yed.getSrot_code())) {
				condition += " and srot_code like '%"+yed.getSrot_code()+"%'";
			}
			if (StringUtils.isNotEmpty(yed.getSpec())) {
				condition += " and spec like '%"+yed.getSpec()+"%'";
			}
			if (StringUtils.isEmpty(condition)) {//未扫描出信息，直接退出
				return null;
			}
			condition += " and state = '0'";
			List<YdmEquipmentDetail> yedList = this.getMapper(YdmEquipmentDetailMapper.class).findWithCondition(null, condition, "", 0, 0);
			if (CollectionUtils.isNotEmpty(yedList)) {
				for (YdmEquipmentDetail y : yedList) {
					y.setState("在库");
					//判断是否存在申请数据
				}
			}
			rm.setData(yedList);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败");
		}
		return rm;
	}
	
	/**
	 * 查询申报
	 * @param cp
	 * @return
	 */
	public ResultModel doQueryApplyListApproval(CommonPage<YdmEquipmentApplylist> cp){
		ResultModel rm =new ResultModel();
		String condition = " and state in('0','1')";
		try{
			String sTime=cp.getStartTime();
			String eTime=cp.getEndTime();	
			YdmEquipmentApplylist yea = cp.getObject();
			if (StringUtils.isNotEmpty(yea.getOpr_man())) {
				condition += " and opr_man = '"+yea.getOpr_man()+"'";
			}
			List<YdmEquipmentApplylist> yeqList = this.getMapper(YdmEquipmentApplylistMapper.class).findWithCondition(null, condition, "apply_time", 0, 0);
			if (CollectionUtils.isNotEmpty(yeqList)) {
				for (YdmEquipmentApplylist y : yeqList) {
					if ("0".equals(y.getState())) {
						y.setState("申报");
					}else if ("1".equals(y.getState())) {
						y.setState("审批");
					}else if ("2".equals(y.getState())) {
						y.setState("执行");
					}else if ("3".equals(y.getState())) {
						y.setState("完成");
					}
				}
			}
			rm.setData(yeqList);
			rm.setState("200");
			
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败！"+ex.getMessage());
		}		
		return rm;
	}
	
	/**
	 * 查询审批
	 * @param cp
	 * @return
	 */
	public ResultModel doQueryApplyListExam(CommonPage<YdmEquipmentApplylist> cp){
		ResultModel rm =new ResultModel();
		String condition = " and state in ('0','1')";
		try{
			String sTime=cp.getStartTime();
			String eTime=cp.getEndTime();	
			YdmEquipmentApplylist yea = cp.getObject();
			/*if (StringUtils.isNotEmpty(yea.getOpr_man())) {
				condition += " and opr_man = '"+yea.getOpr_man()+"'";
			}*/
			//TODO 根据用户查询部门
			String apply_dept = "";
			ComBaseInfo cbi = new ComBaseInfo();
			cbi.setMemo(yea.getOpr_man());
			cbi.setSort_code("6039");
			List<ComBaseInfo> cbiList = this.getMapper(ComBaseInfoMapper.class).findWithCondition(cbi, null, "", 0, 0);
			if (CollectionUtils.isEmpty(cbiList)) {
				return null;
			}else {
				apply_dept += " (";
				for (ComBaseInfo c : cbiList) {
					apply_dept += "'" +c.getBase_name()+"',";
				}
				
				apply_dept += "'')";
			}
			if (StringUtils.isNotEmpty(apply_dept)) {
				condition += " and apply_dept in" + apply_dept;
			}
			List<YdmEquipmentApplylist> yeqList = this.getMapper(YdmEquipmentApplylistMapper.class).findWithCondition(null, condition, "apply_time desc", 0, 0);
			if (CollectionUtils.isNotEmpty(yeqList)) {
				for (YdmEquipmentApplylist y : yeqList) {
					if ("0".equals(y.getState())) {
						y.setState("申报");
					}else if ("1".equals(y.getState())) {
						y.setState("审批");
					}else if ("2".equals(y.getState())) {
						y.setState("执行");
					}else if ("3".equals(y.getState())) {
						y.setState("完成");
					}
				}
			}
			rm.setData(yeqList);
			rm.setState("200");
			
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败！"+ex.getMessage());
		}		
		return rm;
	}
	
	/**
	 * 申报
	 * @param cp
	 * @return
	 */
	public ResultModel doAddEquipmentApplylistApp(CommonPage<YdmEquipmentApplylist> cp){
		ResultModel rm = new ResultModel();
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String dept_name = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_NAME);
		Date currentTime = new Date();
		YdmEquipmentApplylist yea = cp.getObject();
		try {
			String apply_bill_no=this.getMapper(YdmEquipmentApplylistMapper.class).getNo("SB"+new SimpleDateFormat("yyyyMMdd").format(new Date()));
			yea.setApply_bill_no(apply_bill_no);
			yea.setState("0");
			yea.setApply_dept(dept_name);
			yea.setApply_time(currentTime);
			yea.setStorage_code("500207");
			yea.setApply_type("500509");
			yea.setOpr_man(username);
			yea.setCreate_man_no(userId);
			yea.setCreate_man_name(username);
			yea.setCreate_time(currentTime);
			this.getMapper(YdmEquipmentApplylistMapper.class).insert(yea);
			rm.setState("200");	
			rm.setMsgInfo("申报成功 !");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("申报失败");
		}
		return rm;
	}
	
	/**
	 * 申报撤销(删除申报)
	 * @param cp
	 * @return
	 */
	public ResultModel doDeleteEquipmentApplylistApp(CommonPage<YdmEquipmentApplylist> cp){
		ResultModel rm =new ResultModel();
		YdmEquipmentApplylist yea = cp.getObject();
		try{
			YdmEquipmentApplylist yeal=this.getMapper(YdmEquipmentApplylistMapper.class).findById(yea.getApply_bill_no());
			if(yeal==null){
				rm.setState("500");
				rm.setMsgInfo("不存在该申报记录，请刷新页面重新查看！");
				return rm;
			}
			
			if (!"0".equals(yeal.getState())) {
				rm.setState("500");
				rm.setMsgInfo("该申报记录的状态不是【申报】的状态，不允许撤销！");
				return rm;
			}
			this.getMapper(YdmEquipmentApplylistMapper.class).delete(yea.getApply_bill_no());
			rm.setState("200");
			rm.setMsgInfo("删除成功");			
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("撤销申报失败!"+ex.getMessage());
		}		
		return rm;	
	}
	
	/**
	 * 审批
	 * @param cp
	 * @return
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)	
	public ResultModel doApproveEquipmentApplylistApp(CommonPage<YdmEquipmentApplylist> cp){
		ResultModel rm =new ResultModel();
		String man = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String dept = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_NAME);
		List<YdmEquipmentApplylist> yeaList = cp.getObjectList();
		try{
			if (CollectionUtils.isNotEmpty(yeaList)) {
				for (YdmEquipmentApplylist yea : yeaList) {
					YdmEquipmentApplylist yeal=this.getMapper(YdmEquipmentApplylistMapper.class).findById(yea.getApply_bill_no());
					if (yeal==null || !"0".equals(yeal.getState())) {
						rm.setState("500");
						rm.setMsgInfo("此状态不允许撤销 !");
						return rm;
					}
					yeal.setState("1");
					yeal.setApproval_quantity(yea.getApply_quantity());
					yeal.setApproval_time(new Timestamp(new Date().getTime()));
					yeal.setApproval_dept(dept);
					yeal.setApproval_man(man);
					yeal.setGrant_quantity(0d); // 发放数量默认为0
					this.getMapper(YdmEquipmentApplylistMapper.class).update(yeal);
					rm.setState("200");
					rm.setMsgInfo("审批成功");
				}
			}				
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("参数传入错误!"+ex.getMessage());
		}		
		return rm;	
	}
	
	/**
	 * 审批撤销
	 * @param cp
	 * @return
	 */
	public ResultModel doApproveEquipmentApplylistCancelApp(CommonPage<YdmEquipmentApplylist> cp){
		ResultModel rm =new ResultModel();
		List<YdmEquipmentApplylist> yeaList = cp.getObjectList();
		try{
			if (CollectionUtils.isNotEmpty(yeaList)) {
				for (YdmEquipmentApplylist yea : yeaList) {
					YdmEquipmentApplylist yeal=this.getMapper(YdmEquipmentApplylistMapper.class).findById(yea.getApply_bill_no());
					if (yeal==null || !"1".equals(yeal.getState())) {
						rm.setState("500");
						rm.setMsgInfo("此状态数据不允许撤销 !");
						return rm;
					}
					String sql = "update ydm_equipment_applylist set state= '0', approval_time=null, approval_dept=null,"
					+"approval_man=null, approval_quantity=null where apply_bill_no='"+yea.getApply_bill_no()+"'";		
					this.getMapper(YdmEquipmentApplylistMapper.class).doApproveEquipmentApplylistCancelApp(sql);
					rm.setState("200");
					rm.setMsgInfo("撤销审批成功");
				}
			}				
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("参数传入错误!"+ex.getMessage());
		}		
		return rm;	
	}
	
	/**
	 * 
	 * @param cp
	 * @return
	 * @throws Exception 
	 */
	public ResultModel doApproveEquipmentDetailChangeApp(CommonPage<YdmEquipmentDetail> cp) throws Exception{
		ResultModel rm = new ResultModel();
		if (cp.getObject() == null) {
			throw new Exception("请传入参数！");
		}
		YdmEquipmentDetail yed = cp.getObject();
		String quantity = cp.getMemo1();//支数
		if (quantity == null || quantity.equals("")) {
			throw new Exception("请传入数量！");
		}
		String object_no = cp.getMemo2(); // 获取原来库存编码
		// 判断原库存编码对应的产品是否在库
		YdmEquipmentDetail t = new YdmEquipmentDetail();
		t.setObject_no(object_no);
		t.setState("0");
		int ct = this.getMapper(YdmEquipmentDetailMapper.class).count(t);
		if (ct == 0) {
			throw new Exception("请选择在库状态的数据进行操作！");
		}
		if (object_no == null || object_no.equals("")) {
			throw new Exception("请传入库存编码！");
		}
		Double count = Double.valueOf(quantity);
		// 判断是否存在相同的产品的库存编码
		List<YdmEquipmentDetail>  list = this.getMapper(YdmEquipmentDetailMapper.class).findWithCondition(yed, null, null, 0, 0);
		if (CollectionUtils.isNotEmpty(list)) {
			YdmEquipmentDetail yed1 = new YdmEquipmentDetail();
			yed1.setObject_no(list.get(0).getObject_no());
			yed1.setState("0");
			list = this.getMapper(YdmEquipmentDetailMapper.class).find(yed1, 0, 0); // 判断是否存在该库存编码在库的数据
			if (list.size() > 0) {
				YdmEquipmentDetail tmp = list.get(0);
				System.out.println(tmp);
				tmp.setQuantity(count + tmp.getQuantity());
				this.getMapper(YdmEquipmentDetailMapper.class).doUpdateQuantity(tmp); // 更新该库存编码在库数据数量
			} else {
				String ymd = new SimpleDateFormat("yyyyMMdd").format(new Date()); // 开始计算库存编号
				int lsh = this.getMapper(YdmEquipmentDetailMapper.class).findMaxObject_no(); // 流水号生产
				yed.setObject_no("KC" + ymd + String.format("%04d", lsh)); // 库存编号
				yed.setState("0");
				yed.setQuantity(count);
				this.getMapper(YdmEquipmentDetailMapper.class).insert(yed); // 库存表新增记录
			}
		} else {
			String ymd = new SimpleDateFormat("yyyyMMdd").format(new Date()); // 开始计算库存编号
			int lsh = this.getMapper(YdmEquipmentDetailMapper.class).findMaxObject_no(); // 流水号生产
			yed.setObject_no("KC" + ymd + String.format("%04d", lsh)); // 库存编号
			yed.setState("0");
			yed.setQuantity(count);
			this.getMapper(YdmEquipmentDetailMapper.class).insert(yed); // 库存表新增记录
		}
		YdmEquipmentDetail yed2 = new YdmEquipmentDetail();
		yed2.setObject_no(object_no);
		yed2.setState("0");
		list = this.getMapper(YdmEquipmentDetailMapper.class).find(yed2, 0, 0);
		yed2 = list.get(0);
		yed2.setQuantity(yed2.getQuantity() - count);
		if (yed2.getQuantity() < 0) {
			throw new Exception("调整数量超过该库存编号库存在库数量！");
		} else if (yed2.getQuantity() == 0) {
			this.getMapper(YdmEquipmentDetailMapper.class).doDelete(yed2); // 删除原来库存信息
		} else {
			this.getMapper(YdmEquipmentDetailMapper.class).doUpdateQuantity(yed2); // 更新原来库存信息
		}
		rm.setState("200");
		rm.setMsgInfo("区域调整成功！");
		return rm;
	}
	
}
