/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-09-04
 * 描述            ：采购单从表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Pms.Quote.impl;

import java.util.Date;
import java.util.List;

import market.Com.pb.DoubleUtil;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Demand.mapper.PurPlanCMapper;
import market.Pms.Demand.vo.PurPlanC;
import market.Pms.Mat.mapper.PurMatClassMapper;
import market.Pms.Mat.vo.PurMatClass;
import market.Pms.Quote.mapper.PurPurchaseCMapper;
import market.Pms.Quote.mapper.PurPurchaseMMapper;
import market.Pms.Quote.service.PurPurchaseCService;
import market.Pms.Quote.vo.PurPurchaseC;
import market.Pms.Quote.vo.PurPurchaseM;

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.mapper.UserMapper;
import com.hnshituo.core.auth.service.HomeService;
import com.hnshituo.core.auth.vo.User;

@RemoteService(path="PurPurchaseCService")
public class PurPurchaseCServiceImpl extends BaseServiceImpl<PurPurchaseC,Object> implements PurPurchaseCService {
	/**
	 *采购单行信息查询
	 * 
	 * @param oci
	 * @return
	 */
	public ResultModel doQueryWeb(CommonPage<PurPurchaseC> oci) {
		ResultModel rm = new ResultModel();
		PurPurchaseC ppf = oci.getObject();
		PurPurchaseC ppf2=new PurPurchaseC();
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
//		String userName = (String) this.getSession().getAttribute(
//				HomeService.SESSION_USER_NAME);
		User user2=this.getMapper(UserMapper.class).findById(userId);
		if("资材备件科".equals(user2.getDept_name())||"原料科".equals(user2.getDept_name())){
			ppf2.setUnit_desc(user2.getDept_name());
		}  
		ppf2.setPurchase_no(ppf.getPurchase_no());
		try {
			List<PurPurchaseC> list = this.getMapper(PurPurchaseCMapper.class)
//					.find(ppf2, 0, 0);
					.findWithCondition(ppf2, "", "purchase_sqe desc,create_time desc", 0, 0);
			rm.setData(list);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败，请联系管理员");
			throw ex;
		}
		return rm;
	}
	/**
	 *报价单——采购单行信息查询
	 * 
	 * @param oci
	 * @return
	 */
	public ResultModel doPurPurchaseC(CommonPage<PurPurchaseC> oci) {
		ResultModel rm = new ResultModel();
		PurPurchaseC ppf = oci.getObject();
		try {
			String userId = (String) this.getSession().getAttribute(
					HomeService.SESSION_USER_ID);
//			String userName = (String) this.getSession().getAttribute(
//					HomeService.SESSION_USER_NAME);
			User user2=this.getMapper(UserMapper.class).findById(userId);
			if("资材备件科".equals(user2.getDept_name())||"原料科".equals(user2.getDept_name())){
				ppf.setUnit_desc(user2.getDept_name());
			}  
			List<PurPurchaseC> list = this.getMapper(PurPurchaseCMapper.class).findPurchaseC(ppf);
			rm.setData(list);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败，请联系管理员");
			throw ex;
		}
		return rm;
	}
	/**
	 *采购单行信息新增
	 * 
	 * @param oci
	 * @return
	 * @throws Exception 
	 */
	public ResultModel doAddWeb(CommonPage<PurPlanC> oci) throws Exception {
		ResultModel rm = new ResultModel();
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		List<PurPlanC> ppcList = oci.getObjectList();
		String purchase_no=oci.getMemo1();
		String bid_no=oci.getMemo2();
//		User user2=this.getMapper(UserMapper.class).findById(userId);
		try {
			PurPurchaseM  ppm=this.getMapper(PurPurchaseMMapper.class).findById(purchase_no);
			boolean  b=true;//判断行信息是否全为资材备件材料标识，是，修改主信息为资材备件科。
			if("10".equals(ppm.getValidflag())){//数据状态为草稿状态，才能新增
			for (PurPlanC ppc : ppcList) {
				PurPlanC ppc2=new PurPlanC();
				ppc2.setPlan_no(ppc.getPlan_no());
				ppc2.setPlan_sqe(ppc.getPlan_sqe());
				PurPlanC ppc3=this.getMapper(PurPlanCMapper.class).findOnePurPlanC(ppc2, "", "");
				if(ppc3!=null){
				if(ppc3.getQty_useval()!=null&&!"".equals(ppc3.getQty_useval()))
				if(DoubleUtil.add(ppc.getQty_editval(), ppc3.getQty_useval())>ppc.getQty()){
					throw new Exception(ppc.getPlan_sqe()+"核准数量超过计划数量，请重新编辑");
				}
				}
				String purchase_sqe = purchase_no;
				String maxD = this.getMapper(PurPurchaseCMapper.class)
						.findMaxPurchaseSeq(purchase_no);
				if (maxD != null && maxD.length() > 4) {
					String seq = maxD.substring(maxD.length() - 3);
					int iseq = Integer.parseInt(seq) + 1;
					purchase_sqe += String.format("%03d", iseq);
				} else {
					purchase_sqe += "001";
				}
				PurPurchaseC  ppch=new PurPurchaseC();
				ppch.setPurchase_sqe(purchase_sqe);
				ppch.setCreate_userid(userId);
				ppch.setCreate_name(userName);
				ppch.setCreate_time(new Date());
				ppch.setPurchase_no(purchase_no);//采购单号
				ppch.setBid_no(bid_no);//标段号
				ppch.setPlan_sqe(ppc.getPlan_sqe());//采购计划行号
				ppch.setQty(ppc.getQty_editval());//采购数量
				ppch.setUom_code(ppc.getUom_code());
				ppch.setUom_name(ppc.getUom_name());//采购单位名称
				
				PurMatClass  pmc=this.getMapper(PurMatClassMapper.class).findById(ppc.getMat_class_code());
				ppch.setDept_code(pmc.getDept_code());//设置部门
				ppch.setDept_desc(pmc.getDept_desc());
				ppch.setUnit_code(pmc.getUnit_code());//设置科室
				ppch.setUnit_desc(pmc.getUnit_desc());
				if(!"资材备件科".equals(pmc.getUnit_desc())){
					b=false;
				}
				ppch.setValidflag("10");// 默认10草稿
				ppch.setStatus("00"); // 默认00代提报	
				ppch.setRemark(ppc.getRemark());//备注
				ppch.setPurchase_price(ppc.getBudget_price());//预算价格
				ppch.setPurchase_amt(ppc.getPurchase_amt());//预算总金额
				ppch.setMat_class_code(ppc.getMat_class_code());//物料分类
				ppch.setMat_class_name(ppc.getMat_class_name());
				ppch.setItem_code(ppc.getItem_code());//物料编码
				ppch.setItem_name(ppc.getItem_name());
				ppch.setItem_desc(ppc.getItem_desc());
				ppch.setItem_idx(ppc.getItem_idx());
				ppch.setStandards_code(ppc.getStandards_code());//标准代码
				ppch.setStandards_name(ppc.getStandards_name());
				ppch.setSpec_name(ppc.getSpec_name());//规格
				ppch.setSteel_code(ppc.getSteel_code());//钢种牌号
				ppch.setSteel_name(ppc.getSteel_name());
				ppch.setAttr_code(ppc.getAttr_code());//属性
				ppch.setAttr_name(ppc.getAttr_name());
				ppch.setDelivery_state_code(ppc.getDelivery_state_code());//交货状态
				ppch.setDelivery_state_name(ppc.getDelivery_state_name());
				ppch.setLast_delivery_date(ppc.getLast_delivery_date());//交货日期
				ppch.setDelivery_location_code(ppc.getDelivery_location_code());
				ppch.setDelivery_location(ppc.getDelivery_location());//交货地址
				ppch.setReceive_type_code(ppc.getReceive_type_code());//收货方式
				ppch.setReceive_type_name(ppc.getReceive_type_name());
				this.getMapper(PurPurchaseCMapper.class).insert(ppch);
			}
			if(b&&"10".equals(ppm.getValidflag())){
				ppm.setBuyer_unit_desc("资材备件科");
				this.getMapper(PurPurchaseMMapper.class).update(ppm);
			}
			rm.setState("200");
			rm.setMsgInfo("新增成功");
			}else{
				rm.setState("500");
				rm.setMsgInfo("新增失败，当前采购单号"+purchase_no+"不为草稿状态");
			}
		} catch (Exception ex) {
//			throw ex;
			throw new Exception(ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 采购单行信息删除
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDelete(CommonPage<PurPurchaseC> oci) throws Exception {
		ResultModel rm = new ResultModel();
		if (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		try {
			for (PurPurchaseC pdc : oci.getObjectList()) {
				//数据状态无效或草稿状态。审批状态待提报、拒绝、退回。可进行删除操作。
				if (("00".equals(pdc.getValidflag())||"10".equals(pdc.getValidflag()))
						&& ("00".equals(pdc.getStatus()) || "30".equals(pdc
								.getStatus())|| "40".equals(pdc
								.getStatus()))) {
				this.getMapper(PurPurchaseCMapper.class).delete(pdc.getPurchase_sqe());	
				}else{
					rm.setState("500");
					rm.setMsgInfo(pdc.getPurchase_sqe()+"该数据不能删除！");
					return rm;
				}		
			}
			rm.setState("200");
			rm.setMsgInfo("删除成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("删除失败，请联系管理员");
			throw ex;
		}
		return rm;
	}
	
	/**
	 * 采购单行信息审批
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel appPurPlanC(CommonPage<PurPurchaseC> oci) throws Exception {
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		if (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		try {
			for (PurPurchaseC ppc : oci.getObjectList()) {
				if ("10".equals(ppc.getStatus())) {
				ppc.setStatus("30");//审批拒绝
				ppc.setValidflag("00");//数据状态为无效
				ppc.setUpdate_userid(userId);
				ppc.setUpdate_name(userName);
				ppc.setUpdate_time(new Date());
				this.getMapper(PurPurchaseCMapper.class).update(ppc);
				String sWhere=" 1=1 ";
				if(ppc.getPurchase_no()!=null&&!"".equals(ppc.getPurchase_no())){
					sWhere+="and purchase_no = '"+ppc.getPurchase_no()+"'";
				}
				PurPurchaseC pc=new PurPurchaseC();
				List<PurPurchaseC> list=this.getMapper(PurPurchaseCMapper.class).findWithCondition(pc, sWhere, " create_time desc", 0, 0);
				boolean a=true;
				for (PurPurchaseC ppc2 : list) {
					if(!"30".equals(ppc2.getStatus())){//如果存在信息不为审批拒绝，标志符为false,否则为true；
						a=false;
					}
				}
				if(a){
					PurPurchaseM ppm=this.getMapper(PurPurchaseMMapper.class).findById(ppc.getPurchase_no());
					ppm.setStatus("30");//审批拒绝
					ppm.setValidflag("00");//数据状态为无效
					this.getMapper(PurPurchaseMMapper.class).update(ppm);
				}
				}else{
					rm.setState("500");
					rm.setMsgInfo("该数据不能审批！");
					return rm;
				}
				
			}
			rm.setState("200");
			rm.setMsgInfo("审批成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("审批失败，请联系管理员");
			throw ex;
		}
		return rm;
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月2日
	 * @parameter 
	 * @return 
	 * @description 采购单编制，采购单审批界面：通过采购单查询  采购单行 信息
	 */
	public ResultModel doQueryPurchaseC(CommonPage<PurPurchaseC> oci) {
		ResultModel rm = new ResultModel();
		PurPurchaseC ppc = oci.getObject();
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);		  
		try {
			String condition = "";
			if (ppc != null) {
				User user=this.getMapper(UserMapper.class).findById(userId);
				//管理科室
				if(user!=null && user.getDept_name()!=null 
						&& ("资材备件科".equals(user.getDept_name())||"原料科".equals(user.getDept_name()))){
					condition += " AND C.UNIT_DESC = '"+user.getDept_name()+"'";
				}
				//采购单号
				if (ppc.getPurchase_no()!=null && !"".equals(ppc.getPurchase_no())) {
					condition += " AND C.PURCHASE_NO = '"+ppc.getPurchase_no()+"'";
				}
			}
			List<PurPurchaseC> list = this.getMapper(PurPurchaseCMapper.class)
					.doQueryPurchaseC(condition);
			rm.setData(list);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败，请联系管理员");
			throw ex;
		}
		return rm;
	}
	
}
