/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-11-22
 * 描述            ：结算单从表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Pms.Settlement.impl;
import java.util.Date;
import java.util.List;

import market.Com.mapper.ComBaseInfoMapper;
import market.Com.pb.DoubleUtil;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Order.mapper.PurOrderCMapper;
import market.Pms.Order.vo.PurOrderC;
import market.Pms.Settlement.mapper.PurBalanceCMapper;
import market.Pms.Settlement.mapper.PurBalanceMMapper;
import market.Pms.Settlement.mapper.PurInterfaceInbillMapper;
import market.Pms.Settlement.service.PurBalanceCService;
import market.Pms.Settlement.vo.PurBalanceC;
import market.Pms.Settlement.vo.PurBalanceM;
import market.Pms.Settlement.vo.PurInterfaceInbill;

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="PurBalanceCService")
public class PurBalanceCServiceImpl extends BaseServiceImpl<PurBalanceC,Object> implements PurBalanceCService {

	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月26日
	 * @description 结算单编制界面:查询结算单行信息
	 */
	public ResultModel doQueryPurBalanceC(CommonPage<PurBalanceC> cp){
		ResultModel rm=new ResultModel();
		PurBalanceC pbc=cp.getObject();
		try {
			String swhere="";
			//结算单号
			if(pbc.getBalance_no()!=null&&!"".equals(pbc.getBalance_no())){
				swhere+=" and T.BALANCE_NO like '%"+pbc.getBalance_no()+"%'";
			}
			//合同号
			if(pbc.getContract_no()!=null&&!"".equals(pbc.getContract_no())){
				swhere+=" and T.CONTRACT_NO like '%"+pbc.getContract_no()+"%'";
			}
			//默认不显示无效的数据
			swhere+=" and T.VALIDFLAG > '00'";
			// 新增报支单行信息时，查询结算单行信息
			if ("balanceH".equals(cp.getMemo4())) {	
				// 已经报支的结算单行不能进行冲减
				swhere+=" and T.VALIDFLAG = '20' and T.STATUS = '50' and not exists "
						+ "(select h.balance_sqe from pur_balance_h h "
						+ "where h.balance_sqe = T.balance_sqe and h.validflag > '00')";
			}
			List<PurBalanceC> list = this.getMapper(PurBalanceCMapper.class).doQueryPurBalanceC(swhere);
			rm.setData(list);;
			rm.setState("200");
			rm.setMsgInfo("查询成功");		
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败，请联系管理员！");
			throw e;
		}
		return rm;
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月26日
	 * @description 结算单编制界面:新增结算单行信息
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel addPurBalanceC(CommonPage<PurInterfaceInbill> cp) throws Exception{
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String deptId= (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_ID);
		String deptName= (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_NAME);
		ResultModel rm=new ResultModel();
		List<PurInterfaceInbill> piiList=cp.getObjectList();
		String balanceno = cp.getMemo1(); // 结算单号		 
		if (balanceno==null || "".equals(balanceno)) {
			rm.setState("500");
			rm.setMsgInfo("请传入结算单号！");
			return rm;
		}
		if (piiList == null || piiList.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择入库单数据！");
			return rm;
		}

		PurBalanceM pbm = this.getMapper(PurBalanceMMapper.class).findById(balanceno);
		if (pbm==null) {
			rm.setState("500");
			rm.setMsgInfo("结算单号["+balanceno+"]对应的结算单不存在！");
			return rm;
		}
		if (pbm.getValidflag()==null || !"10".equals(pbm.getValidflag())) {
			rm.setState("500");
			rm.setMsgInfo("结算单号["+balanceno+"]无法创建结算单行信息！");
			return rm;
		}
		
		for (PurInterfaceInbill PII : piiList) {
			//判断数量是否超出待结算数量
			PurInterfaceInbill pii2=this.getMapper(
					PurInterfaceInbillMapper.class).findOnebill(PII);//用于判断数量
			if(pii2!=null){
				//如果已使用量为空，判断编辑量和入库单的入库量
				if(pii2.getUseqty()==null || "".equals(pii2.getUseqty())){
					if (PII.getEditqty()>pii2.getIn_num()) {
						throw new Exception("入库单["+PII.getInstock_no()+"]的编辑量超过待结算数量，请重新编辑");
					}
				}else {
					if(DoubleUtil.add(pii2.getUseqty(), PII.getEditqty())>pii2.getIn_num()){
						throw new Exception("入库单["+PII.getInstock_no()+"]的编辑量超过待结算数量，请重新编辑");
					}
				}
			}else {
				throw new Exception("入库单["+PII.getInstock_no()+"]信息不存在！");
			}
			Date now = new Date();
			PurInterfaceInbill pii = this.getMapper(PurInterfaceInbillMapper.class).findById(PII.getInstock_no());
			if (pii!=null) {
				PurBalanceC pbc = new PurBalanceC();
				pbc.setBalance_no(balanceno);
				String balanceSqe = balanceno;
				String maxSQE = this.getMapper(PurBalanceCMapper.class)
						.findMaxBalanceSqe(balanceSqe);
				if (maxSQE != null && maxSQE.length() > 3) {
					String seq = maxSQE.substring(maxSQE.length() - 3);
					int iseq = Integer.parseInt(seq) + 1;
					balanceSqe += String.format("%03d", iseq);
				} else {
					balanceSqe += "001";
				}
				pbc.setBalance_sqe(balanceSqe);
				pbc.setRefe_no(pii.getInstock_no());
				pbc.setRefe_type_code("603001");
				pbc.setRefe_type_name("入库单");
				pbc.setContract_no(pii.getContract_no());
				pbc.setContract_pk(pii.getContract_pk());
				pbc.setOrder_no(pii.getOrder_no());
				pbc.setOrder_pk(pii.getOrder_pk());
				pbc.setSupp_code(pii.getSupp_code());
				pbc.setSupp_name(pii.getSupp_name());
				pbc.setBalance_desc(pbm.getBalance_desc());//结算说明
				pbc.setBalance_date(pbm.getBalance_date());//结算日期
				pbc.setBase_qty(pii.getIn_num());//基础数量==入库数量
				pbc.setBase_price(pii.getBug_price());//基础单价==预算价
				//pbc.setChe_qty(che_qty);//成分数量
				//pbc.setChe_price(che_price);//成分单价
				//pbc.setQuantity_qty(quantity_qty);//保量数量
				//pbc.setQuantity_price(quantity_price);//保量单价
				//pbc.setOther_qty(other_qty);//其它数量
				//pbc.setOther_price(other_price);//其它单价
				//pbc.setAdd_subt_qty(add_subt_qty);//加扣数量
				//pbc.setAdd_subt_price(add_subt_price);//加扣单价					
				pbc.setBalance_qty(PII.getEditqty());//结算数量*****界面传入，必填
				
				if (pii.getOrder_pk()==null || "".equals(pii.getOrder_pk())) {
					throw new Exception("入库单号["+pii.getInstock_no()+"]的合同号不存在！");
				}
				PurOrderC poc = this.getMapper(PurOrderCMapper.class).findById(pii.getOrder_pk());
				if (poc!=null) {
					pbc.setUom_code(poc.getUom_code());//采购单位
					pbc.setUom_name(poc.getUom_name());
					pbc.setPrice_freight(poc.getPrice_freight_val());//运费含税单价(结算)
					pbc.setFreight_with_amt(PII.getEditqty()*pbc.getPrice_freight());//运费含税总额
					
					pbc.setPrice_with_tax(poc.getPrice_with_tax());//含税单价(结算)
					pbc.setWith_tax_amt(PII.getEditqty()*poc.getPrice_with_tax());//含税总金额金额(结算)
					if (poc.getTax_rate_val()!=null && !"".equals(poc.getTax_rate_val())) {						
						//税率(结算)
						pbc.setTax_rate_val(poc.getTax_rate_val());
						ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById(poc.getTax_rate_val());
						if (cbi!=null) {
							// 税率 转 Double
							Double tax_rate_val = (cbi.getBase_name()==null || "".equals(cbi.getBase_name()))?
									0:Double.parseDouble(cbi.getBase_name())/100;
							//运费不含税单价(结算)
							Double price_freight = poc.getPrice_freight_val()==null?0:poc.getPrice_freight_val();
							pbc.setPrice_without_freight(price_freight/(1+tax_rate_val));
							//运费不含税总额
							pbc.setFreight_without_amt(PII.getEditqty()*pbc.getPrice_without_freight());
							
							//不含税单价(结算)
							Double price_with_tax = poc.getPrice_with_tax()==null?0:poc.getPrice_with_tax();
							pbc.setPrice_without_tax(price_with_tax/(1+tax_rate_val));
							//不含总金额税金额(结算)			
							pbc.setWithout_tax_amt(PII.getEditqty()*pbc.getPrice_without_tax());
							//税额(结算)
							pbc.setTax_amt(pbc.getWith_tax_amt()-pbc.getWithout_tax_amt());							
						}
					}
				}
				pbc.setItem_code(pii.getItem_code());//物料名称
				pbc.setItem_name(pii.getItem_name());
				pbc.setItem_desc(pii.getItem_desc());//物料描述
				pbc.setItem_desc_e(pii.getItem_desc_e());//物料英文名称
				pbc.setItem_idx(pii.getItem_idx());//物料检索
				pbc.setMat_class_code(pii.getMat_class_code());
				pbc.setMat_class_name(pii.getMat_class_name());//分类名称
				pbc.setSpec_name(pii.getSpec_name());
				pbc.setStandards_code(pii.getStandards_code());
				pbc.setStandards_name(pii.getStandards_name());//标准号
				pbc.setSteel_code(pii.getSteel_code());
				pbc.setSteel_name(pii.getSteel_name());//牌号
				pbc.setAttr_code(pii.getAttr_code());
				pbc.setAttr_name(pii.getAttr_name());//属性名称
				pbc.setDelivery_state_code(pii.getDelivery_state_code());
				pbc.setDelivery_state_name(pii.getDelivery_state_name());//交货状态名称
				//pbc.setItem_manage_type(item_manage_type);//ABC分类
				//pbc.setCompany_code(company_code);
				//pbc.setCompany_name(company_name);//公司名称
				pbc.setDept_code(deptId);
				pbc.setDept_desc(deptName);//管理部门描叙
				//pbc.setUnit_code(unit_code);
				//pbc.setUnit_desc(unit_desc);//管理科室描叙
				pbc.setBal_year_month(pbm.getBal_year_month());//业务年月
				pbc.setValidflag("10");
				pbc.setStatus("00");
				pbc.setRemark(pii.getRemark());//备注
				pbc.setCreate_userid(userId);
				pbc.setCreate_name(userName);
				pbc.setCreate_time(now);
				this.getMapper(PurBalanceCMapper.class).insert(pbc);
				
				PurInterfaceInbill newPii = new PurInterfaceInbill();
				newPii.setInstock_no(pii.getInstock_no());
				newPii.setValidflag("10");
				if(pii2.getUseqty()==null || "".equals(pii2.getUseqty())){
					if (PII.getEditqty().doubleValue() == pii2.getIn_num().doubleValue()) {
						newPii.setValidflag("20");
					}
				}else {
					if(DoubleUtil.add(pii2.getUseqty(), PII.getEditqty())==pii2.getIn_num()){
						newPii.setValidflag("20");
					}
				}
				this.getMapper(PurInterfaceInbillMapper.class).update(newPii);
			}
		}
		rm.setState("200");
		rm.setMsgInfo("新增成功");
		return rm; 
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月26日
	 * @description 结算单编制界面:删除结算单行信息
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDeletePurBalanceC(CommonPage<PurBalanceC> cp)
			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 (cp.getObjectList() == null || cp.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择结算单数据！");
			return rm;
		}
		Date now = new Date();
		for (PurBalanceC pdc : cp.getObjectList()) {
			PurBalanceC pdc2=this.getMapper(PurBalanceCMapper.class).findById(pdc.getBalance_sqe());				
			if (pdc2!=null && "10".equals(pdc2.getValidflag())
					&& ("00".equals(pdc2.getStatus()))) {//草稿+ 待提报					 
				pdc = new PurBalanceC();
				pdc.setBalance_sqe(pdc2.getBalance_sqe());
				pdc.setValidflag("00");//无效
				pdc.setUpdate_userid(userId);
				pdc.setUpdate_name(userName);
				pdc.setUpdate_time(now);
				this.getMapper(PurBalanceCMapper.class).update(pdc);
				//入库单操作
				PurInterfaceInbill pii=this.getMapper(PurInterfaceInbillMapper.class).findById(pdc2.getRefe_no());
				if(pii!=null){
					PurInterfaceInbill newPii = new PurInterfaceInbill();
					newPii.setInstock_no(pii.getInstock_no());
					if(pdc2.getBalance_qty().doubleValue()==pdc2.getBase_qty().doubleValue()){
						//如果结算量等于基础数量，则置为初始
						newPii.setValidflag("00");
					}
					if(pdc2.getBalance_qty().doubleValue()<pdc2.getBase_qty().doubleValue()){
						//如果结算量小于基础数量，则置为锁定状态
						newPii.setValidflag("10");
					}
					newPii.setUpdate_userid(userId);
					newPii.setUpdate_name(userName);
					newPii.setUpdate_time(now);
					this.getMapper(PurInterfaceInbillMapper.class).update(newPii);
				}
			} else {
				throw new Exception("当前数据状态不能删除");
			}
		}
		rm.setState("200");
		rm.setMsgInfo("删除成功！");
		return rm;
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月30日
	 * @description 报支单行新增；查询结算单行
	 */
	public ResultModel doQueryPurBalanceC_G(CommonPage<PurBalanceC> cp){
		ResultModel rm=new ResultModel();
		PurBalanceC pbc=cp.getObject();
		try {
			String swhere="";
			//结算单号
			if(pbc.getBalance_no()!=null&&!"".equals(pbc.getBalance_no())){
				swhere+=" and T.BALANCE_NO like '%"+pbc.getBalance_no()+"%'";
			}
			//合同号
			if(pbc.getContract_no()!=null&&!"".equals(pbc.getContract_no())){
				swhere+=" and T.CONTRACT_NO like '%"+pbc.getContract_no()+"%'";
			}
			List<PurBalanceC> list = this.getMapper(PurBalanceCMapper.class).doQueryPurBalanceC_G(swhere);
			rm.setData(list);;
			rm.setState("200");
			rm.setMsgInfo("查询成功");		
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败，请联系管理员！");
			throw e;
		}
		return rm;
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年12月11日
	 * @description 前端界面：采购合同卸货点：优特钢带，酸洗卷做判断
	 */
	public ResultModel doQuaryBySeqForPurchase(CommonPage<PurBalanceC> cp){
		ResultModel rm = new ResultModel();
		PurBalanceC pbc = this.getMapper(PurBalanceCMapper.class).doQuaryBySeqForPurchase(cp.getMemo1());
		if (pbc!=null && pbc.getDelivery_location().contains("优特钢带") 
				&& "1".equals(pbc.getMaterailtype())) {
			rm.setData("200");
		}else {
			rm.setData("500");
		}
		return rm;
	}
	
}
