/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-01-13
 * 描述            ：客户发票管理表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
 ***********************************************************/
package market.Slm.FundManagement.impl;
import java.util.Date;
import java.util.List;

import market.Com.pb.DoubleUtil;
import market.Com.pb.PbMethod;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillHeatMapper;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;
import market.Slm.FundManagement.mapper.SlmFundBalancePriceApplyMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleCarriageMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleGoodMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleOtherMapper;
import market.Slm.FundManagement.service.SlmFundBalancePriceApplyService;
import market.Slm.FundManagement.vo.SlmFundBalancePriceApply;
import market.Slm.FundManagement.vo.SlmFundSettleCarriage;
import market.Slm.FundManagement.vo.SlmFundSettleGood;
import market.Slm.FundManagement.vo.SlmFundSettleOther;

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="SlmFundBalancePriceApplyService")
public class SlmFundBalancePriceApplyServiceImpl extends BaseServiceImpl<SlmFundBalancePriceApply,Object> implements SlmFundBalancePriceApplyService {

	/**
	 * 申报信息查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmFundBalancePriceApply> sum){
		ResultModel rm=new ResultModel();
		SlmFundBalancePriceApply apply=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		try{
			String sWhere=" 1=1 ";
			if(startTime!=null&&!"".equals(startTime)){		//为创建时间
				sWhere+=" and to_char(create_time, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime+"'";
			}
			if(endTime!=null&&!"".equals(endTime)){
				sWhere+=" and to_char(create_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime+"'";
			}
			List<SlmFundBalancePriceApply> list=this.getMapper(SlmFundBalancePriceApplyMapper.class).findWithCondition(apply, sWhere, " create_time desc", (pageIndex-1)*pageSize, pageSize);
			for(SlmFundBalancePriceApply applys:list){
				if(applys.getCustomer_name()==null&&applys.getContract_no()!=null){
					List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+applys.getContract_no()+"'", null, 0, 0);
					if(heat_list.size()>0){
						applys.setCustomer_no(heat_list.get(0).getCustomer_no());
						applys.setCustomer_name(heat_list.get(0).getCustomer_name());
					}
				}
			}
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 申报信息新增
	 * */
	public ResultModel doAddWeb(CommonPage<SlmFundBalancePriceApply> sum){
		ResultModel rm=new ResultModel();
		SlmFundBalancePriceApply apply=sum.getObject();
		String userId=(String)this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String)this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3);
			apply.setApply_no(id);
			apply.setValid_flag("1"); 		//编辑
			apply.setCreate_man_no(userId);
			apply.setCreate_man_name(userName);
			apply.setCreate_time(new Date());
			if(apply.getContract_no()!=null){
				List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+apply.getContract_no()+"'", null, 0, 0);
				if(heat_list.size()>0){
					apply.setCustomer_no(heat_list.get(0).getCustomer_no());
					apply.setCustomer_name(heat_list.get(0).getCustomer_name());
				}
			}
			this.getMapper(SlmFundBalancePriceApplyMapper.class).insert(apply);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 是否可进行操作
	 * @return
	 */
	private ResultModel doValidDb(List<SlmFundBalancePriceApply> ls){
		ResultModel rm=new ResultModel();
		rm.setState("200");
		String applyNo="";
		for(SlmFundBalancePriceApply s:ls){
			applyNo+="'"+s.getApply_no()+"',";
		}
		if(applyNo.length()>0){
			applyNo=applyNo.substring(0,applyNo.length()-1);
			List<SlmFundBalancePriceApply> lsb=this.getMapper(SlmFundBalancePriceApplyMapper.class).findWithCondition(null, " apply_no in ("+applyNo+")", "", 0, 0);
			String billNo="";
			for(SlmFundBalancePriceApply sb:lsb){
				if(billNo.indexOf(sb.getBill_no())<0){
					billNo+="'"+sb.getBill_no()+"',";
				}
			}
			billNo=billNo.substring(0,billNo.length()-1);
			String msg="";
			List<SlmLadingBillHeat> lsh=this.getMapper(SlmLadingBillHeatMapper.class).findWithCondition(null, "bill_no in ("+billNo+") and valid_flag='1'", "", 0, 0);
			for(SlmLadingBillHeat sh:lsh){
				if(!"12".equals(sh.getValid_status())){
					//不可操作
					msg+="'"+sh.getBill_no()+"',";
				}
			}
			if(!"".equals(msg)){
				rm.setState("500");
				rm.setMsgInfo("提单号为："+msg+"的提单未出于票据核算状态，无法进行该操作！");
			}
			
		}else{
			rm.setState("500");
			rm.setMsgInfo("请选择需要操作的数据");
		}
		return rm;
	}
	
	/**
	 * 申报信息修改
	 * */
	public ResultModel doUpdateWeb(CommonPage<SlmFundBalancePriceApply> sum){
		ResultModel rm=new ResultModel();
		SlmFundBalancePriceApply apply=sum.getObject();
		try{
			if(apply.getApply_no()==null){
				rm.setState("500");
				rm.setMsgInfo("请选择需要修改的数据");
				return rm;
			}
			SlmFundBalancePriceApply check=this.getMapper(SlmFundBalancePriceApplyMapper.class).findById(apply.getApply_no());
			if(check!=null&&"1".equals(check.getValid_flag())){
				this.getMapper(SlmFundBalancePriceApplyMapper.class).update(apply);
			}else{
				rm.setState("500");
				rm.setMsgInfo("只有编辑状态才能修改");
				return rm;
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 申报信息删除
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteWeb(CommonPage<SlmFundBalancePriceApply> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmFundBalancePriceApply> list=sum.getObjectList();
		try{
			for(SlmFundBalancePriceApply apply:list){
				if(apply.getApply_no()!=null){
					apply=this.getMapper(SlmFundBalancePriceApplyMapper.class).findById(apply.getApply_no());
					if(apply!=null&&"1".equals(apply.getValid_flag())){
						this.getMapper(SlmFundBalancePriceApplyMapper.class).delete(apply.getApply_no());
					}
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw new Exception("操作失败："+e.getMessage());
		}
		return rm;
	}

	/**
	 * 申报信息提交
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSubmitWeb(CommonPage<SlmFundBalancePriceApply> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmFundBalancePriceApply> list=sum.getObjectList();
		try{
			// ================eason add 2019-06-22===============
			rm=doValidDb(list);
			if(!"200".equals(rm.getState())){
				return rm;
			}
			//====================================================
			
			for(SlmFundBalancePriceApply apply:list){
				if(apply.getApply_no()!=null){
					apply=this.getMapper(SlmFundBalancePriceApplyMapper.class).findById(apply.getApply_no());
					if(apply!=null&&"1".equals(apply.getValid_flag())){
						apply.setValid_flag("2"); 		//待审批
						this.getMapper(SlmFundBalancePriceApplyMapper.class).update(apply);
					}
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw new Exception("操作失败："+e.getMessage());
		}
		return rm;
	}

	/**
	 * 申报信息撤回
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRollbackWeb(CommonPage<SlmFundBalancePriceApply> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmFundBalancePriceApply> list=sum.getObjectList();
		try{
			// ================eason add 2019-06-22===============
			rm=doValidDb(list);
			if(!"200".equals(rm.getState())){
				return rm;
			}
			//====================================================
			for(SlmFundBalancePriceApply apply:list){
				if(apply.getApply_no()!=null){
					apply=this.getMapper(SlmFundBalancePriceApplyMapper.class).findById(apply.getApply_no());
					if(apply!=null&&"2".equals(apply.getValid_flag())){
						apply.setValid_flag("1"); 		//编辑
						this.getMapper(SlmFundBalancePriceApplyMapper.class).update(apply);
					}
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw new Exception("操作失败："+e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 申报信息  通过
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doPassWeb(CommonPage<SlmFundBalancePriceApply> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmFundBalancePriceApply> list=sum.getObjectList();
		try{
			// ================eason add 2019-06-22===============
			rm=doValidDb(list);
			if(!"200".equals(rm.getState())){
				return rm;
			}
			//====================================================
						
			for(SlmFundBalancePriceApply apply:list){
				if(apply.getApply_no()!=null){
					apply=this.getMapper(SlmFundBalancePriceApplyMapper.class).findById(apply.getApply_no());
					if(apply!=null&&"2".equals(apply.getValid_flag())){
						//修改价格
						SlmFundSettleCarriage carriage=this.getMapper(SlmFundSettleCarriageMapper.class).findById(apply.getObject_no());
						if(carriage!=null){
							carriage.setCarriage_price(apply.getNew_balance_price());
							carriage.setSettle_carriage_fund(DoubleUtil.round(DoubleUtil.mul(apply.getNew_balance_price(), carriage.getCarriage_weight()),DoubleUtil.SCALE_PRICE));
							this.getMapper(SlmFundSettleCarriageMapper.class).update(carriage);
						}else{
							SlmFundSettleGood good=this.getMapper(SlmFundSettleGoodMapper.class).findById(apply.getObject_no());
							if(good!=null){
								Double balance_price=good.getBalance_price()-good.getBalance_good_price()+apply.getNew_balance_price();
								good.setBalance_price(balance_price);
								good.setBalance_good_price(apply.getNew_balance_price());
								good.setBalance_amount(DoubleUtil.round(DoubleUtil.mul(apply.getNew_balance_price(), good.getBalance_weight()),DoubleUtil.SCALE_PRICE));
								this.getMapper(SlmFundSettleGoodMapper.class).update(good);
							}else{
								SlmFundSettleOther other=this.getMapper(SlmFundSettleOtherMapper.class).findById(apply.getObject_no());
								if(other!=null){
									other.setOther_price(apply.getNew_balance_price());
									other.setSettle_other_fund(DoubleUtil.round(DoubleUtil.mul(apply.getNew_balance_price(), other.getOther_weight()),DoubleUtil.SCALE_PRICE));
									// ======================eason add 2019-06-22======================
									other.setTrade_price(apply.getNew_trade_price());
									other.setProcess_price(apply.getNew_process_price());
									// ================================================================
									this.getMapper(SlmFundSettleOtherMapper.class).update(other);
								}
							}
						}
						apply.setValid_flag("3"); 		//通过
						this.getMapper(SlmFundBalancePriceApplyMapper.class).update(apply);
					}
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw new Exception("操作失败："+e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 申报信息  不通过
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doNotPassWeb(CommonPage<SlmFundBalancePriceApply> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmFundBalancePriceApply> list=sum.getObjectList();
		try{
			// ================eason add 2019-06-22===============
			rm=doValidDb(list);
			if(!"200".equals(rm.getState())){
				return rm;
			}
			//====================================================
			for(SlmFundBalancePriceApply apply:list){
				if(apply.getApply_no()!=null){
					apply=this.getMapper(SlmFundBalancePriceApplyMapper.class).findById(apply.getApply_no());
					if(apply!=null&&"2".equals(apply.getValid_flag())){
						apply.setValid_flag("4"); 		//不通过
						this.getMapper(SlmFundBalancePriceApplyMapper.class).update(apply);
					}
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw new Exception("操作失败："+e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 申报信息  撤销
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelWeb(CommonPage<SlmFundBalancePriceApply> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmFundBalancePriceApply> list=sum.getObjectList();
		try{
			// ================eason add 2019-06-22===============
			rm=doValidDb(list);
			if(!"200".equals(rm.getState())){
				return rm;
			}
			//====================================================
			for(SlmFundBalancePriceApply apply:list){
				if(apply.getApply_no()!=null){
					apply=this.getMapper(SlmFundBalancePriceApplyMapper.class).findById(apply.getApply_no());
					if(apply!=null&&("3".equals(apply.getValid_flag())||"4".equals(apply.getValid_flag()))){
						//修改价格
						SlmFundSettleCarriage carriage=this.getMapper(SlmFundSettleCarriageMapper.class).findById(apply.getObject_no());
						if(carriage!=null){
							if(!"1".equals(carriage.getFlag())){
								rm.setState("500");
								rm.setMsgInfo("该运费信息已被结算单使用，请删除结算单后进行撤销");
								return rm;
							}
							carriage.setCarriage_price(apply.getOld_balance_price());
							carriage.setSettle_carriage_fund(DoubleUtil.round(DoubleUtil.mul(apply.getOld_balance_price(), carriage.getCarriage_weight()),DoubleUtil.SCALE_PRICE));
							this.getMapper(SlmFundSettleCarriageMapper.class).update(carriage);
						}else{
							SlmFundSettleGood good=this.getMapper(SlmFundSettleGoodMapper.class).findById(apply.getObject_no());
							if(good!=null){
								if(!"1".equals(good.getFlag())){
									rm.setState("500");
									rm.setMsgInfo("该货款信息已被结算单使用，请删除结算单后进行撤销");
									return rm;
								}
								Double balance_price=good.getBalance_price()-good.getBalance_good_price()+apply.getOld_balance_price();
								good.setBalance_price(balance_price);
								good.setBalance_good_price(apply.getOld_balance_price());
								good.setBalance_amount(DoubleUtil.round(DoubleUtil.mul(apply.getOld_balance_price(), good.getBalance_weight()),DoubleUtil.SCALE_PRICE));
								this.getMapper(SlmFundSettleGoodMapper.class).update(good);
							}else{
								SlmFundSettleOther other=this.getMapper(SlmFundSettleOtherMapper.class).findById(apply.getObject_no());
								if(other!=null){
									if(!"1".equals(other.getFlag())){
										rm.setState("500");
										rm.setMsgInfo("该加工配送费信息已被结算单使用，请删除结算单后进行撤销");
										return rm;
									}
									other.setOther_price(apply.getOld_balance_price());
									other.setSettle_other_fund(DoubleUtil.round(DoubleUtil.mul(apply.getOld_balance_price(), other.getOther_weight()),DoubleUtil.SCALE_PRICE));
									// ======================eason add 2019-06-22======================
									other.setTrade_price(apply.getOld_trade_price());
									other.setProcess_price(apply.getOld_process_price());
									// ================================================================
									this.getMapper(SlmFundSettleOtherMapper.class).update(other);
								}
							}
						}
						apply.setValid_flag("2"); 		//待审批
						this.getMapper(SlmFundBalancePriceApplyMapper.class).update(apply);
					}
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw new Exception("操作失败："+e.getMessage());
		}
		return rm;
	}
}