/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-09-04
 * 描述            ：询价/报价从表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Pms.Quote.impl;
import java.util.Date;
import java.util.List;

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Mat.mapper.PurMatClassMapper;
import market.Pms.Mat.vo.PurMatClass;
import market.Pms.Quote.mapper.PurInquiryCMapper;
import market.Pms.Quote.mapper.PurInquiryMMapper;
import market.Pms.Quote.service.PurInquiryCService;
import market.Pms.Quote.vo.PurInquiryC;
import market.Pms.Quote.vo.PurInquiryM;

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="PurInquiryCService")
public class PurInquiryCServiceImpl extends BaseServiceImpl<PurInquiryC,Object> implements PurInquiryCService {

	/**
	 * 查询
	 * 报价单审批-报价单行信息
		object：
		报价单：inquiry_no
	 * @param sum
	 * @return
	 */ 
	public ResultModel doQueryWeb(CommonPage<PurInquiryC> sum) {
		ResultModel rm = new ResultModel();
		PurInquiryC purInquiryC = sum.getObject();
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
//		String userName = (String) this.getSession().getAttribute(
//				HomeService.SESSION_USER_NAME);
		try {	
			User user2=this.getMapper(UserMapper.class).findById(userId);
			String str="";
			if("资材备件科".equals(user2.getDept_name())||"原料科".equals(user2.getDept_name())){
				str+=user2.getDept_name();
			}  
			rm.setData(this.getMapper(PurInquiryCMapper.class)
					.doQueryWeb(purInquiryC.getInquiry_no(),str));
			rm.setState("200");
		} catch (Exception ex) { 
			rm.setState("500");
			rm.setMsgInfo("查询失败！" + ex.getMessage());
		}
		return rm;
	}
	/**
	 * 合同编制查询
	 * -供应商信息 ——报价单行信息
		object：
		报价单：inquiry_no
	 * @param sum
	 * @return
	 */ 
	public ResultModel doInquiryC(CommonPage<PurInquiryC> sum) {
		ResultModel rm = new ResultModel();
		PurInquiryC purInquiryC = sum.getObject();
		try {	
			rm.setData(this.getMapper(PurInquiryCMapper.class)
					.findInquiryC(purInquiryC));
			rm.setState("200");
		} catch (Exception ex) { 
			rm.setState("500");
			rm.setMsgInfo("查询失败！" + ex.getMessage());
		}
		return rm;
	}
	/**
	 * 修改
	 * 报价单审批-报价单行信息
	 * @param sum
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUpdateWeb(CommonPage<PurInquiryC> sum) 
			throws Exception {
		ResultModel rm = new ResultModel();
		try {
			PurInquiryC purC = sum.getObject();
			if(purC.getInquiry_sqe()==null || "".equals(purC.getInquiry_sqe())){
				throw new Exception("报价单行号为空");
			}
			int count = this.getMapper(PurInquiryCMapper.class).countWithCondition(null, "inquiry_sqe='"+purC.getInquiry_sqe()+"'");
			if(count<=0){
				throw new Exception("报价单行号【"+purC.getInquiry_sqe()+"】，在系统中不存在！");
			}
			PurInquiryC purC2=this.getMapper(PurInquiryCMapper.class).findById(purC.getInquiry_sqe());
			if("20".equals(purC2.getStatus())&&"10".equals(purC2.getValidflag())){
				
				this.getMapper(PurInquiryCMapper.class).update(purC);
				rm.setState("修改成功！");
				rm.setState("200");
			}else{
				rm.setState("500");
				rm.setMsgInfo("当前数据"+purC.getInquiry_sqe()+"状态不为待审批状态，修改失败！");
			}
			
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("修改失败！" + ex.getMessage());
		}
		return rm;
	}
	/**
	 * 报价行信息保存
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel upPurInquiryC(CommonPage<PurInquiryC> 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 (PurInquiryC purC : oci.getObjectList()) {
				PurInquiryC ppc=this.getMapper(PurInquiryCMapper.class).findById(purC.getInquiry_sqe());
				if ("20".equals(ppc.getValidflag())
						&& ("10".equals(ppc.getStatus()) || "40".equals(ppc
								.getStatus()))) {
					
				ppc.setBid_win_with_tax_price(purC.getBid_win_with_tax_price());//中标价格(含税)
				ppc.setBid_with_tax_amt(purC.getBid_with_tax_amt());//中标总金额（含税）
				ppc.setBid_qty(purC.getBid_qty());//中标数量
				ppc.setBid_win_without_tax_price(purC.getBid_win_without_tax_price());//中标价格
				ppc.setBid_without_tax_amt(purC.getBid_without_tax_amt());//中标总金额
				ppc.setBid_win_reason(purC.getBid_win_reason());//中标原因
				ppc.setUpdate_userid(userId);
				ppc.setUpdate_name(userName);
				ppc.setUpdate_time(new Date());
				this.getMapper(PurInquiryCMapper.class).update(ppc);
				}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;
	}
	/**
	 *报价单行信息新增
	 * 
	 * @param oci
	 * @return
	 * @throws Exception 
	 */
	public ResultModel doAddWeb(CommonPage<PurInquiryC> 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<PurInquiryC> ppcList = oci.getObjectList();
		String inquiry_no=oci.getMemo1();
		String purchase_no=oci.getMemo2();
		String purchase_desc=oci.getMemo3();
		User user2=this.getMapper(UserMapper.class).findById(userId);
		try {
			PurInquiryM  pim=this.getMapper(PurInquiryMMapper.class).findById(inquiry_no);
			boolean  b=true;//判断行信息是否全为资材备件材料标识，是，修改主信息为资材备件科。
			if("10".equals(pim.getValidflag())){//数据状态为草稿状态，才能新增
			for (PurInquiryC ppc : ppcList) {
				String inquiry_sqe = inquiry_no;
				String maxD = this.getMapper(PurInquiryCMapper.class)
						.findMaxInquirySeq(inquiry_no);
				if (maxD != null && maxD.length() > 4) {
					String seq = maxD.substring(maxD.length() - 3);
					int iseq = Integer.parseInt(seq) + 1;
					inquiry_sqe += String.format("%03d", iseq);
				} else {
					inquiry_sqe += "001";
				}
				PurInquiryC  ppch=new PurInquiryC();
				ppch.setInquiry_no(inquiry_no);//报价单号
				ppch.setInquiry_sqe(inquiry_sqe);//报价单行号
				ppch.setCreate_userid(userId);
				ppch.setCreate_name(userName);
				ppch.setCreate_time(new Date());
				ppch.setPurchase_no(purchase_no);//采购单号
				ppch.setPurchase_desc(purchase_desc);//采购单描述
				ppch.setPurchase_sqe(ppc.getPurchase_sqe());//采购单行号
				ppch.setBid_no(ppc.getBid_no());//标段号
				ppch.setPlan_sqe(ppc.getPlan_sqe());//采购计划行号
				ppch.setQty(ppc.getQty());//采购数量
				ppch.setTax_rate_val("600604");//默认税率
				ppch.setUom_code(ppc.getUom_code());
				ppch.setUom_name(ppc.getUom_name());//采购单位名称
				ppch.setValidflag("10");// 默认10草稿
				ppch.setStatus("00"); // 默认00代提报	
				ppch.setBuyer_dept_code(user2.getDept_id());//加入部门信息
				ppch.setBuyer_unit_desc(user2.getDept_name());
				
				PurMatClass  pmc=this.getMapper(PurMatClassMapper.class).findById(ppc.getMat_class_code());
				ppch.setBuyer_dept_code(pmc.getDept_code());//设置部门
				ppch.setBuyer_dept_desc(pmc.getDept_desc());
				ppch.setBuyer_unit_code(pmc.getUnit_code());//设置科室
				ppch.setBuyer_unit_desc(pmc.getUnit_desc());
				if(!"资材备件科".equals(pmc.getUnit_desc())){
					b=false;
				}
				ppch.setRes_qty(ppc.getRes_qty());//报价数量
				ppch.setRes_desc(ppc.getRes_desc());//报价描述
				ppch.setPurchase_price(ppc.getPurchase_price());//预算单价
				ppch.setRes_with_tax_price(ppc.getRes_with_tax_price());//报税单价（含税）
				ppch.setRes_with_tax_amt(ppc.getRes_with_tax_amt());//报税总额（含税）
				ppch.setRes_without_tax_price(ppc.getRes_without_tax_price());//报税单价（不含税）
				ppch.setRes_without_tax_amt(ppc.getRes_without_tax_amt());//报税总额（不含税）
				ppch.setRes_deliver_date(ppc.getRes_deliver_date());//到货时间
				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.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());
				ppch.setRemark(ppc.getRemark());//备注（采购单行）
				this.getMapper(PurInquiryCMapper.class).insert(ppch);
			}
			if(b&&"10".equals(pim.getValidflag())){
				pim.setBuyer_unit_desc("资材备件科");
				this.getMapper(PurInquiryMMapper.class).update(pim);
			}
			rm.setState("200");
			rm.setMsgInfo("新增成功");
		}else{
			rm.setState("500");
			rm.setMsgInfo("新增失败，当前报价单号"+inquiry_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<PurInquiryC> oci) throws Exception {
		ResultModel rm = new ResultModel();
		if (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		try {
			for (PurInquiryC pdc2 : oci.getObjectList()) {
				PurInquiryC pdc=this.getMapper(PurInquiryCMapper.class).findById(pdc2.getInquiry_sqe());
				//数据状态无效或草稿状态。审批状态待提报、拒绝、退回。可进行删除操作。
				if (("00".equals(pdc.getValidflag())||"10".equals(pdc.getValidflag()))
						&& ("00".equals(pdc.getStatus()) || "30".equals(pdc
								.getStatus())|| "40".equals(pdc
								.getStatus()))) {
				this.getMapper(PurInquiryCMapper.class).delete(pdc.getInquiry_sqe());	
				}else{
					rm.setState("500");
					rm.setMsgInfo(pdc2.getInquiry_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 appPurInquiryC(CommonPage<PurInquiryC> 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 (PurInquiryC purC : oci.getObjectList()) {
				PurInquiryC pdc=this.getMapper(PurInquiryCMapper.class).findById(purC.getInquiry_sqe());
				if ("10".equals(pdc.getStatus())) {
				pdc.setStatus("30");
				pdc.setValidflag("00");//数据状态为无效
				pdc.setUpdate_userid(userId);
				pdc.setUpdate_name(userName);
				pdc.setUpdate_time(new Date());
				this.getMapper(PurInquiryCMapper.class).update(pdc);
				PurInquiryC pdc2=new PurInquiryC();
				pdc2.setInquiry_no(pdc.getInquiry_no());
				List<PurInquiryC> list=this.getMapper(PurInquiryCMapper.class).find(pdc2,0,0);
				boolean a=true;
				for (PurInquiryC pDc : list) {
					if(!"30".equals(pDc.getStatus())){//如果存在信息不为审批拒绝，标志符为false,否则为true；
						a=false;
					}
				}
				if(a){
					PurInquiryM pdm=this.getMapper(PurInquiryMMapper.class).findById(pdc.getInquiry_no());
					pdm.setStatus("30");
					pdm.setValidflag("00");//数据状态为无效
					this.getMapper(PurInquiryMMapper.class).update(pdm);
				}
				}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;
	}
}
