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

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.YdmProductInlistMapper;
import market.Lms.Warehouse.vo.YdmProductInlist;
import market.Pms.Settlement.mapper.PurBalanceCMapper;
import market.Pms.Settlement.mapper.PurBalanceDMapper;
import market.Pms.Settlement.mapper.PurBalanceEMapper;
import market.Pms.Settlement.mapper.PurBalanceHMapper;
import market.Pms.Settlement.mapper.PurBalanceMMapper;
import market.Pms.Settlement.service.PurBalanceDService;
import market.Pms.Settlement.vo.PurBalanceC;
import market.Pms.Settlement.vo.PurBalanceD;
import market.Pms.Settlement.vo.PurBalanceD_E;
import market.Pms.Settlement.vo.PurBalanceE;
import market.Pms.Settlement.vo.PurBalanceH;
import market.Pms.Settlement.vo.PurBalanceM;

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;
import com.ibm.icu.text.SimpleDateFormat;

@RemoteService(path="PurBalanceDService")
public class PurBalanceDServiceImpl extends BaseServiceImpl<PurBalanceD,Object> implements PurBalanceDService {

	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月27日
	 * @description 冲减单编制界面：查询冲减单主信息
	 */
	public ResultModel doQueryPurBalanceD(CommonPage<PurBalanceD> cp){
		ResultModel rm=new ResultModel();
		PurBalanceD  pbd=cp.getObject();
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		try {
			String swhere="";
			//冲减单号
			if(pbd.getTicket_no()!=null&&!"".equals(pbd.getTicket_no())){
				swhere+=" and t.TICKET_NO like  '%"+pbd.getTicket_no()+"%'";
			}
			//供应商名称
			if(pbd.getSupp_name()!=null&&!"".equals(pbd.getSupp_name())){
				swhere+=" and t.SUPP_NAME like '%"+pbd.getSupp_name()+"%'";
			}			
			//数据状态
			if(pbd.getValidflag()!=null&&!"".equals(pbd.getValidflag())){
				swhere+=" and t.VALIDFLAG  = '"+pbd.getValidflag()+"'";
			}
			//评审状态
			if(pbd.getStatus()!=null&&!"".equals(pbd.getStatus())){
				swhere+=" and t.STATUS  = '"+pbd.getStatus()+"'";
			}
			if (startTime != null && !"".equals(startTime)) {
				swhere += " and to_char(t.CREATE_TIME, 'yyyy-mm-dd hh24:mi:ss') >='"
						+ startTime +" 00:00:00"+ "'";
			}
			if (endTime != null && !"".equals(endTime)) {
				swhere += " and to_char(t.CREATE_TIME, 'yyyy-mm-dd hh24:mi:ss') <= '"
						+ endTime +" 23:59:59"+ "'";
			}
			//若无查询条件时，则全数据查询返回VALIDFLAG>'00'的结果
			if (!swhere.contains("VALIDFLAG")) {
				swhere+=" and t.VALIDFLAG > '00'";
			}
			List<PurBalanceD> list = this.getMapper(PurBalanceDMapper.class).doQueryPurBalanceD(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月27日
	 * @description 新增冲减单信息
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddPurBalanceD(CommonPage<PurBalanceD_E> 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();
		PurBalanceD_E PBDE=cp.getObject();
		PurBalanceD PBD = PBDE.getPurBalanceD();//冲减单头
		List<PurBalanceE> PBEList = PBDE.getPurBalanceEList();//冲减单行信息			

		Date now = new Date();
		PurBalanceM pbm = this.getMapper(PurBalanceMMapper.class).findById(PBD.getBalance_no());
		if (pbm!=null) {
			// 新增冲减单头信息
			PurBalanceD pbd = new PurBalanceD();
			// 生成结算单号
			String ticket_no = "CJ"+ new SimpleDateFormat("yyyyMMdd").format(now);
			String maxD = this.getMapper(PurBalanceDMapper.class).findMaxTicketNo(ticket_no);
			if (maxD != null && maxD.length() > 3) {
				String seq = maxD.substring(maxD.length() - 3);
				int iseq = Integer.parseInt(seq) + 1;
				ticket_no += String.format("%03d", iseq);
			} else {
				ticket_no += "001";
			}
			pbd.setTicket_no(ticket_no);
			pbd.setBalance_no(pbm.getBalance_no());
			pbd.setSupp_code(pbm.getSupp_code());
			pbd.setSupp_name(pbm.getSupp_name());
			pbd.setContract_no(pbm.getContract_no());
			pbd.setContract_pk(pbm.getContract_pk());
			pbd.setContract_ver(pbm.getContract_ver());
			pbd.setBills_nos(pbm.getBills_nos());
			pbd.setBills_codes(pbm.getBills_codes());
			pbd.setTicket_type_code(PBD.getTicket_type_code());//冲减或补收类型代码(6035)
			pbd.setTicket_type_name(PBD.getTicket_type_name());
			pbd.setTicket_type_desc(PBD.getTicket_type_desc());//冲减或补收说明
			pbd.setTicket_date(PBD.getTicket_date());//冲减或补收日期(YYYY-MM-DD)
			pbd.setDept_code(deptId);
			pbd.setDept_desc(deptName);
			pbd.setBal_year_month(pbm.getBal_year_month());
			pbd.setValidflag("10");
			pbd.setStatus("00");
			pbd.setRemark(pbm.getRemark());//备注
			pbd.setCreate_userid(userId);
			pbd.setCreate_name(userName);
			pbd.setCreate_time(now);
			this.getMapper(PurBalanceDMapper.class).insert(pbd);
			
			for (PurBalanceE PBE : PBEList) {
				PurBalanceC pbc = this.getMapper(PurBalanceCMapper.class).findById(PBE.getBalance_sqe());
				if (pbc!=null) {
					PurBalanceE pbe = new PurBalanceE();
					pbe.setBalance_sqe(pbc.getBalance_sqe());
					pbe.setTicket_no(ticket_no);
					String ticketsqe = ticket_no;
					String maxSqe = this.getMapper(PurBalanceEMapper.class).findMaxTicketSqe(ticketsqe);
					if (maxSqe != null && maxSqe.length() > 3) {
						String seq = maxSqe.substring(maxSqe.length() - 3);
						int iseq = Integer.parseInt(seq) + 1;
						ticketsqe += String.format("%03d", iseq);
					} else {
						ticketsqe += "001";
					}
					pbe.setTicket_seq(ticketsqe);
					pbe.setBalance_no(pbc.getBalance_no());
					pbe.setRefe_no(pbc.getRefe_no());
					pbe.setRefe_type_code(pbc.getRefe_type_code());
					pbe.setRefe_type_name(pbc.getRefe_type_name());
					pbe.setContract_no(pbc.getContract_no());
					pbe.setContract_pk(pbc.getContract_pk());
					pbe.setOrder_no(pbc.getOrder_no());
					pbe.setOrder_pk(pbc.getOrder_pk());
					pbe.setSupp_code(pbc.getSupp_code());
					pbe.setSupp_name(pbc.getSupp_name());
					pbe.setBalance_qty(pbc.getBalance_qty());
					pbe.setUom_code(pbc.getUom_code());
					pbe.setUom_name(pbc.getUom_name());
					pbe.setItem_code(pbc.getItem_code());
					pbe.setItem_name(pbc.getItem_name());
					pbe.setItem_desc(pbc.getItem_desc());
					pbe.setItem_desc_e(pbc.getItem_desc_e());
					pbe.setItem_idx(pbc.getItem_idx());
					pbe.setItem_manage_type(pbc.getItem_manage_type());
					pbe.setMat_class_code(pbc.getMat_class_code());
					pbe.setMat_class_name(pbc.getMat_class_name());
					pbe.setSpec_name(pbc.getSpec_name());
					pbe.setStandards_code(pbc.getStandards_code());
					pbe.setStandards_name(pbc.getStandards_name());
					pbe.setSteel_code(pbc.getSteel_code());
					pbe.setSteel_name(pbc.getSteel_name());
					pbe.setAttr_code(pbc.getAttr_code());
					pbe.setAttr_name(pbc.getAttr_name());
					pbe.setDelivery_state_code(pbc.getDelivery_state_code());
					pbe.setDelivery_state_name(pbc.getDelivery_state_name());
					// 从入口记录里获取卷号和炉号(资材备件没有卷号和炉号，所有直接取YdmProductInlist)
					YdmProductInlist ypi = this.getMapper(YdmProductInlistMapper.class).findById(pbc.getRefe_no());
					if (ypi!=null) {
						pbe.setCoil_no(ypi.getCoilno());//卷号 
						pbe.setHeat_no(ypi.getHeatno());//炉号 							
					}
					pbe.setSal_order_pk(PBE.getSal_order_pk());//销售订单号PK
					pbe.setSal_order_no(PBE.getSal_order_no());//销售订单号 
					
					//运费单价(结算)
					Double price_freight = pbc.getPrice_freight()==null?0:pbc.getPrice_freight();
					pbe.setPrice_freight(price_freight); 
					pbe.setTax_rate_val(pbc.getTax_rate_val());
					pbe.setPrice_without_tax(pbc.getPrice_without_tax());
					//含税单价(结算)
					Double price_with_tax = pbc.getPrice_with_tax()==null?0:pbc.getPrice_with_tax();
					pbe.setPrice_with_tax(price_with_tax);
					pbe.setWithout_tax_amt(pbc.getWith_tax_amt());
					pbe.setWith_tax_amt(pbc.getWith_tax_amt());
					pbe.setTax_amt(pbc.getTax_amt());
					pbe.setTicket_atm(PBE.getTicket_atm());//进项冲减或补收金额
					pbe.setTicket_note(PBE.getTicket_note());//冲减或补收说明
					pbe.setSal_tax_rate_val(PBE.getSal_tax_rate_val());//销售税率 (%)
					
					//税率
					//Double d = (PBE.getSal_tax_rate_val()==null||"".equals(PBE.getSal_tax_rate_val()))?0:(Double.valueOf(PBE.getSal_tax_rate_val())/100);
					//销售含税单价 
					/*Double sal_price_with_tax = PBE.getSal_price_with_tax()!=null?PBE.getSal_price_with_tax():0;
					pbe.setSal_price_with_tax(sal_price_with_tax);
					//销售不含税单价=销售含税单价 * (1-销售税率)
					pbe.setSal_price_without_tax(sal_price_with_tax * (1-d));*/
					//结算数量
					Double balance_qty = pbc.getBalance_qty()==null?0:pbc.getBalance_qty();
					/*//销售不含总金额 = 销售不含税单价*结算数量
					pbe.setSal_without_tax_amt(pbe.getSal_price_without_tax() * balance_qty);
					//销售含税总金额 = 结算数量*销售含税单价
					pbe.setSal_with_tax_amt(sal_price_with_tax * balance_qty);
					//销售税额  = 销售含税单价*销售税率*结算数量 = 销售含税总金额 * 销售税率
					pbe.setSal_tax_amt(pbe.getSal_with_tax_amt() * d);
					//销购价差  = 销售含税单价-含税单价（结算）
					pbe.setDiffer_pirce_val(sal_price_with_tax - price_with_tax);
					//销项单价差额 
					Double sal_tax_differ = PBE.getSal_tax_differ()==null?0:PBE.getSal_tax_differ();
					pbe.setSal_tax_differ(sal_tax_differ);
					//销项金额差额  = 结算数量*销项单价差额
					pbe.setSal_atm_differ(sal_tax_differ * balance_qty); 
					
					pbe.setSal_reason_differ(PBE.getSal_reason_differ());//销项差额原因 
					pbe.setSal_situation_ticket(PBE.getSal_situation_ticket());//销项冲减或补收情况
					
					pbe.setSal_atm_ticket(PBE.getSal_atm_ticket());//销项冲减或补收金额 
					pbe.setSal_cycle(PBE.getSal_cycle());//销售接单周期
					
					//销售价格追补
					Double sal_price_add = PBE.getSal_price_add()==null?0:PBE.getSal_price_add();
					pbe.setSal_price_add(sal_price_add); 
					//销售追补金额  = 销售价格追补*结算数量
					pbe.setSal_atm_add(sal_price_add * balance_qty);*/
					
					
					//进项单价差额 (采购)
					Double pur_tax_differ = PBE.getPur_tax_differ()==null?0:PBE.getPur_tax_differ();
					pbe.setPur_tax_differ(pur_tax_differ);
					//进项金额差额 (采购) =  结算数量 * 进项单价差额
					pbe.setPur_atm_differ(pur_tax_differ * balance_qty); 
					//进项差额原因 (采购)
					pbe.setPur_reason_differ(PBE.getPur_reason_differ());
					pbe.setPur_cycle(PBE.getPur_cycle());//采购接单周期
					PurBalanceC pbc1 = this.getMapper(PurBalanceCMapper.class).doQuaryBySeqForPurchase(pbc.getBalance_sqe());
					if (pbc1!=null && pbc1.getDelivery_location().contains("优特钢带")
							&& "1".equals(pbc1.getMaterailtype())) {
						pbe.setPur_tax_differ(20.0);
						pbe.setPur_atm_differ(20.0 * balance_qty); 
						pbe.setPur_reason_differ("多收20元/吨的自提加价费");
					}
					//采购价格追补 
					Double pur_price_add = PBE.getPur_price_add()==null?0:PBE.getPur_price_add();
					pbe.setPur_price_add(pur_price_add);
					//采购追补金额  = 采购价格追补*结算数量
					pbe.setPur_atm_add(pur_price_add * balance_qty);
					 
					//销售运费单价
					/*Double sal_price_freight = PBE.getSal_price_freight()==null?0:PBE.getSal_price_freight();
					pbe.setSal_price_freight(sal_price_freight);
					//销购运费差  = 销售运费单价-运费单价（结算）
					pbe.setDiffer_freight_val(sal_price_freight - price_freight);							
											
					//销售盈亏 =采购价格追补+销售价格追补+销购价差+销购运费差
					pbe.setSal_profit_val(pur_price_add + sal_price_add
							+ pbe.getDiffer_pirce_val() + pbe.getDiffer_freight_val());
					
					//盈亏金额  = 销售盈亏*结算数量
					pbe.setSal_profit_atm(pbe.getSal_profit_val() * balance_qty);*/
					
					pbe.setDept_code(deptId);
					pbe.setDept_desc(deptName);
					pbe.setBal_year_month(pbc.getBal_year_month());
					pbe.setValidflag("10");
					pbe.setStatus("00");
					pbe.setRemark(pbc.getRemark());
					pbe.setCreate_userid(userId);
					pbe.setCreate_name(userName);
					pbe.setCreate_time(now);
					this.getMapper(PurBalanceEMapper.class).insert(pbe);
				}
			}
		}
		rm.setState("200");
		return rm; 
	} 

	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月27日
	 * @description 冲减单编制界面：自动审批
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doExamPurBalanceD(CommonPage<PurBalanceD> 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 (PurBalanceD pbd : cp.getObjectList()) {
			PurBalanceD pbd2=this.getMapper(PurBalanceDMapper.class).findById(pbd.getTicket_no());				
			if (pbd2!=null && "10".equals(pbd2.getValidflag())
					&& ("00".equals(pbd2.getStatus()) || "40".equals(pbd2
							.getStatus()))) {//草稿+ 待提报/审批退回
				//主表PurBalanceD
				PurBalanceD newPbd = new PurBalanceD();
				newPbd.setTicket_no(pbd2.getTicket_no());
				newPbd.setValidflag("20");//生效
				newPbd.setStatus("50");//审批通过
				newPbd.setUpdate_userid(userId);
				newPbd.setUpdate_name(userName);
				newPbd.setUpdate_time(now);
				this.getMapper(PurBalanceDMapper.class).update(newPbd);
				//从表PurBalanceE
				PurBalanceE pbe = new PurBalanceE();
				pbe.setTicket_no(pbd2.getTicket_no());
				pbe.setValidflag("10");//草稿
				List<PurBalanceE> pbeList = this.getMapper(PurBalanceEMapper.class).find(pbe, 0, 0);
				if (pbeList!=null && pbeList.size() > 0) {
					for (PurBalanceE pBe : pbeList) {
						pbe = new PurBalanceE();
						pbe.setTicket_seq(pBe.getTicket_seq());
						pbe.setValidflag("20"); //生效
						pbe.setStatus("50"); //审批通过
						pbe.setUpdate_userid(userId);
						pbe.setUpdate_name(userName);
						pbe.setUpdate_time(now);
						this.getMapper(PurBalanceEMapper.class).update(pbe);
					}
				}
			} else {
				throw new Exception("当前数据状态不能进行自动审批");
			}
		}
		rm.setState("200");
		rm.setMsgInfo("自动审批成功！");
		return rm;
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月27日
	 * @description 冲减单编制界面：撤销审批
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doCancelExamPurBalanceD(CommonPage<PurBalanceD> 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 (PurBalanceD pbd : cp.getObjectList()) {
			PurBalanceD pbd2=this.getMapper(PurBalanceDMapper.class).findById(pbd.getTicket_no());				
			if (pbd2!=null && "20".equals(pbd2.getValidflag())
					&& "50".equals(pbd2.getStatus())) {//生效+ 审批通过
				//主表PurBalanceD
				pbd = new PurBalanceD();
				pbd.setTicket_no(pbd2.getTicket_no());
				pbd.setValidflag("10");//草稿
				pbd.setStatus("00");//待提报
				pbd.setUpdate_userid(userId);
				pbd.setUpdate_name(userName);
				pbd.setUpdate_time(now);
				this.getMapper(PurBalanceDMapper.class).update(pbd);
				//从表PurBalanceE
				PurBalanceE pbe = new PurBalanceE();
				pbe.setTicket_no(pbd2.getTicket_no());
				pbe.setValidflag("20");//生效
				pbe.setStatus("50");//审批通过
				List<PurBalanceE> pbeList = this.getMapper(PurBalanceEMapper.class).find(pbe, 0, 0);
				if (pbeList!=null && pbeList.size() > 0) {
					for (PurBalanceE pBe : pbeList) {
						//判断冲减单是否已经进行报支,已报支的数据不能进行撤销审批
						String condition = "refe_no = '"+pBe.getTicket_seq()+"' and validflag > '00'";
						List<PurBalanceH> pbhList = this.getMapper(PurBalanceHMapper.class).findWithCondition(null, condition, null, 0, 0);
						if (pbhList!=null && pbhList.size()>0) {
							throw new Exception("冲减单号["+pbd2.getTicket_no()+"]下的冲减单行信息["+pBe.getTicket_seq()+"]已经进行了报支，无法撤销审批！");
						}
						pbe = new PurBalanceE();
						pbe.setTicket_seq(pBe.getTicket_seq());
						pbe.setValidflag("10"); //草稿
						pbe.setStatus("00"); //待提报
						pbe.setUpdate_userid(userId);
						pbe.setUpdate_name(userName);
						pbe.setUpdate_time(now);
						this.getMapper(PurBalanceEMapper.class).update(pbe);
					}
				}
			} else {
				throw new Exception("当前数据状态不能进行撤销审批");
			}
		}
		rm.setState("200");
		rm.setMsgInfo("撤销审批成功！");
		return rm;
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月27日
	 * @description 冲减单编制界面：删除
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDeletePurBalanceD(CommonPage<PurBalanceD> 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 (PurBalanceD pbd : cp.getObjectList()) {
			PurBalanceD pbd2=this.getMapper(PurBalanceDMapper.class).findById(pbd.getTicket_no());				
			if (pbd2!=null && "10".equals(pbd2.getValidflag())
					&& "00".equals(pbd2.getStatus())) {//草稿+ 待提报
				//主表PurBalanceD
				PurBalanceD newPbd = new PurBalanceD();
				newPbd.setTicket_no(pbd2.getTicket_no());
				newPbd.setValidflag("00");//无效
				newPbd.setUpdate_userid(userId);
				newPbd.setUpdate_name(userName);
				newPbd.setUpdate_time(now);
				this.getMapper(PurBalanceDMapper.class).update(newPbd);
				//从表PurBalanceE
				PurBalanceE pbe = new PurBalanceE();
				pbe.setTicket_no(pbd2.getTicket_no());
				pbe.setValidflag("10");//草稿
				pbe.setStatus("00");//待提报
				List<PurBalanceE> pbeList = this.getMapper(PurBalanceEMapper.class).find(pbe, 0, 0);
				if (pbeList!=null && pbeList.size() > 0) {
					for (PurBalanceE pBe : pbeList) {
						pbe = new PurBalanceE();
						pbe.setTicket_seq(pBe.getTicket_seq());
						pbe.setValidflag("00"); //无效
						pbe.setUpdate_userid(userId);
						pbe.setUpdate_name(userName);
						pbe.setUpdate_time(now);
						this.getMapper(PurBalanceEMapper.class).update(pbe);
					}
				}
			} else {
				throw new Exception("当前数据状态不能进行删除");
			}
		}
		rm.setState("200");
		rm.setMsgInfo("删除成功！");
		return rm;
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月27日
	 * @description 冲减单编制界面：修改
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUpdatePurBalanceD(CommonPage<PurBalanceD_E> 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();
		PurBalanceD_E PBDE=cp.getObject();
		PurBalanceD PBD = PBDE.getPurBalanceD();//冲减单头
		List<PurBalanceE> PBEList = PBDE.getPurBalanceEList();//冲减单行信息	
		/*if (cp.getMemo1() == null) {
			rm.setState("500");
			rm.setMsgInfo("请选择是否编辑冲减明细！");
			return rm;
		}*/
		Date now = new Date();
		PurBalanceD pbd = this.getMapper(PurBalanceDMapper.class).findById(PBD.getTicket_no());
		if (pbd!=null && "10".equals(pbd.getValidflag())
				&& ("00".equals(pbd.getStatus()) || "40".equals(pbd
						.getStatus()))) {
			PurBalanceD newPbd = new PurBalanceD();
			newPbd.setTicket_no(pbd.getTicket_no());
			newPbd.setTicket_type_code(PBD.getTicket_type_code());//冲减类型
			newPbd.setTicket_type_name(PBD.getTicket_type_name());
			newPbd.setTicket_type_desc(PBD.getTicket_type_desc());//冲减说明
			newPbd.setTicket_date(PBD.getTicket_date());//冲减时间
			newPbd.setUpdate_userid(userId);
			newPbd.setUpdate_name(userName);
			newPbd.setUpdate_time(now);
			this.getMapper(PurBalanceDMapper.class).update(newPbd);
			// 则禁止编辑明细，明细中的必填项“进项冲减或补收情况”=冲减说明，“进项冲减或补收金额”=冲减金额（平均值
			/*if ("0".equals(cp.getMemo1())) {
				if (PBD.getTicket_atm()==null) {
					throw new Exception("冲减金额不能为空！");
				}
				PurBalanceE pbe = new PurBalanceE();
				pbe.setTicket_no(pbd.getTicket_no());
				pbe.setValidflag("20");
				List<PurBalanceE> pbeList = this.getMapper(PurBalanceEMapper.class).find(pbe, 0, 0);
				int count = this.getMapper(PurBalanceEMapper.class).count(pbe);
				for (PurBalanceE PBE : pbeList) {
					pbe = new PurBalanceE();
					pbe.setTicket_seq(PBE.getTicket_seq());
					
					pbe.setTicket_atm(PBD.getTicket_atm()/count);
					pbe.setTicket_note(PBD.getTicket_type_desc());
					pbe.setUpdate_userid(userId);
					pbe.setUpdate_name(userName);
					pbe.setUpdate_time(now);
					this.getMapper(PurBalanceEMapper.class).update(pbe);
				}
			}*/ 
			//若勾选，则清除冲减金额TEXT内容，并禁用，金额由明细汇总SUM()
			//if ("1".equals(cp.getMemo1())) {}
			for (PurBalanceE PBE : PBEList) {
				PurBalanceE pBe = this.getMapper(PurBalanceEMapper.class).findById(PBE.getTicket_seq());
				if (pBe!=null && "10".equals(pBe.getValidflag())) {
					PurBalanceE pbe = new PurBalanceE();
					pbe.setTicket_seq(pBe.getTicket_seq());
					pbe.setTicket_atm(PBE.getTicket_atm());//进项冲减或补收金额
					pbe.setTicket_note(PBE.getTicket_note());//冲减或补收说明
					pbe.setSal_order_pk(PBE.getSal_order_pk());//销售订单号PK
					pbe.setSal_order_no(PBE.getSal_order_no());//销售订单号 
					
					//销售运费单价
					/*Double sal_price_freight = PBE.getSal_price_freight()==null?0:PBE.getSal_price_freight();
					pbe.setSal_price_freight(sal_price_freight);
					//销售税率 (%)
					pbe.setSal_tax_rate_val(PBE.getSal_tax_rate_val());
					double sal_tax_rate_val = (PBE.getSal_tax_rate_val()==null||"".equals(PBE.getSal_tax_rate_val()))?0:(Double.valueOf(PBE.getSal_tax_rate_val())/100); 
					
					//销售含税单价 
					Double sal_price_with_tax = PBE.getSal_price_with_tax()!=null?PBE.getSal_price_with_tax():0;
					pbe.setSal_price_with_tax(sal_price_with_tax);	*/						
					//结算数量
					Double balance_qty = pBe.getBalance_qty()==null?0:pBe.getBalance_qty();
					
					//销售不含税单价=销售含税单价 * (1-销售税率)
					/*pbe.setSal_price_without_tax(sal_price_with_tax * (1-sal_tax_rate_val));
					//销售不含总金额 = 销售不含税单价*结算数量
					pbe.setSal_without_tax_amt(pbe.getSal_price_without_tax() * balance_qty); 
					//销售含税总金额 = 结算数量*销售含税单价
					pbe.setSal_with_tax_amt(sal_price_with_tax * balance_qty); 
					//销售税额  = 销售含税单价*销售税率*结算数量 = 销售含税总金额 * 销售税率
					pbe.setSal_tax_amt(pbe.getSal_with_tax_amt() * sal_tax_rate_val);*/
					
					//销项单价差额 
					/*Double sal_tax_differ = PBE.getSal_tax_differ()==null?0:PBE.getSal_tax_differ();
					pbe.setSal_tax_differ(sal_tax_differ);
					//销项金额差额  = 销项单价差额 * 结算数量
					pbe.setSal_atm_differ(sal_tax_differ * balance_qty);*/
					
					/*pbe.setSal_reason_differ(PBE.getSal_reason_differ());//销项差额原因 
					pbe.setSal_situation_ticket(PBE.getSal_situation_ticket());//销项冲减或补收情况 
					pbe.setSal_atm_ticket(PBE.getSal_atm_ticket());//销项冲减或补收金额 
					pbe.setSal_cycle(PBE.getSal_cycle());//销售接单周期
					*/						
					//销售价格追补
					/*Double sal_price_add = PBE.getSal_price_add()==null?0:PBE.getSal_price_add();
					pbe.setSal_price_add(sal_price_add);
					//销售追补金额  = 销售价格追补*结算数量
					pbe.setSal_atm_add(sal_price_add * balance_qty);*/
					
					//进项单价差额 (采购)
					Double pur_tax_differ = PBE.getPur_tax_differ()==null?0:PBE.getPur_tax_differ();
					pbe.setPur_tax_differ(pur_tax_differ);
					//进项金额差额 (采购) =  结算数量*进项单价差额
					pbe.setPur_atm_differ(pur_tax_differ * balance_qty);
					pbe.setPur_reason_differ(PBE.getPur_reason_differ());//进项差额原因 (采购)
					//进项金额差额 (采购) =  结算数量 * 进项单价差额
					pbe.setPur_atm_differ(pur_tax_differ * balance_qty); 
					pbe.setPur_reason_differ(PBE.getPur_reason_differ());//进项差额原因 (采购)
					pbe.setPur_cycle(PBE.getPur_cycle());//采购接单周期
					PurBalanceC pbc1 = this.getMapper(PurBalanceCMapper.class).doQuaryBySeqForPurchase(pbe.getBalance_sqe());
					if (pbc1!=null && pbc1.getDelivery_location().contains("优特钢带")
							&& "1".equals(pbc1.getMaterailtype())) {
						pbe.setPur_tax_differ(20.0);
						pbe.setPur_atm_differ(20.0 * balance_qty); 
						pbe.setPur_reason_differ("多收20元/吨的自提加价费");
					}
					
					pbe.setPur_cycle(PBE.getPur_cycle());//采购接单周期
					
					//采购价格追补 
					Double pur_price_add = PBE.getPur_price_add()==null?0:PBE.getPur_price_add();
					pbe.setPur_price_add(pur_price_add);//采购价格追补 
					//采购追补金额  = 采购价格追补*结算数量
					pbe.setPur_atm_add(pur_price_add * balance_qty);
					
					//含税单价(结算)
					/*Double price_with_tax = pBe.getPrice_with_tax()==null?0:pBe.getPrice_with_tax();*/
					//销购价差  = 销售含税单价-含税单价（结算）
					/*pbe.setDiffer_pirce_val(sal_price_with_tax - price_with_tax);*/
					
					//运费单价(结算)
					/*Double price_freight = pBe.getPrice_freight()==null?0:pBe.getPrice_freight();*/							
					//销购运费差  = 销售运费单价-运费单价（结算）
					/*pbe.setDiffer_freight_val(sal_price_freight - price_freight);*/
					
					//销售盈亏 =采购价格追补+销售价格追补+销购价差+销购运费差
					/*pbe.setSal_profit_val(pur_price_add + sal_price_add 
							+ pbe.getDiffer_pirce_val() + pbe.getDiffer_freight_val());
					//盈亏金额  = 销售盈亏*结算数量
					pbe.setSal_profit_atm(pbe.getSal_profit_val() * balance_qty);*/
												
					pbe.setUpdate_userid(userId);
					pbe.setUpdate_name(userName);
					pbe.setUpdate_time(now);
					this.getMapper(PurBalanceEMapper.class).update(pbe);
				}
			} 
		}else {
			throw new Exception("当前数据状态不能进行修改");
		}
		rm.setState("200");
		rm.setMsgInfo("修改成功！");
		return rm;
	}
	
	
}
