/***文档注释***********************************************
 * 作者               :                   易鑫
 * 创建日期      :                   2017.10.24
 * 描述               :        			合同付款比例信息
 * 注意事项      :                   无
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
 ***********************************************************/
package market.Slm.ContractManagement.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
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.Lms.Warehouse.vo.YdmProductDetail;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractLineInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractPaymentConfigMapper;
import market.Slm.ContractManagement.mapper.SlmContractPaymentConfigureMapper;
import market.Slm.ContractManagement.mapper.SlmContractPaymentMapper;
import market.Slm.ContractManagement.mapper.SlmContractPaymentPlanMapper;
import market.Slm.ContractManagement.service.SlmContractPaymentService;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.ContractManagement.vo.SlmContractPayment;
import market.Slm.ContractManagement.vo.SlmContractPaymentConfig;
import market.Slm.ContractManagement.vo.SlmContractPaymentConfigure;
import market.Slm.ContractManagement.vo.SlmContractPaymentPlan;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillDetailMapper;
import market.Slm.DeliveryManagement.vo.SlmLadingBillDetail;
import market.Slm.DeliveryManagement.vo.SlmLadingBillLine;
import market.Slm.FundManagement.impl.SlmFundSecondDetailServiceImpl;
import market.Slm.FundManagement.impl.SlmFundThirdAccountServiceImpl;
import market.Slm.FundManagement.impl.SlmFundThirdAccountUsedServiceImpl;
import market.Slm.FundManagement.mapper.SlmFundFirstAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundSecondAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundThirdAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundThirdAccountUsedMapper;
import market.Slm.FundManagement.vo.SlmFundFirstAccount;
import market.Slm.FundManagement.vo.SlmFundSecondAccount;
import market.Slm.FundManagement.vo.SlmFundSecondDetail;
import market.Slm.FundManagement.vo.SlmFundThirdAccount;
import market.Slm.FundManagement.vo.SlmFundThirdAccountUsed;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.vo.SlmOrderInfo;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path="SlmContractPaymentService")
public class SlmContractPaymentServiceImpl extends BaseServiceImpl<SlmContractPayment,Object> implements SlmContractPaymentService {

	/**
	 * 付款要求-列表
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmContractPayment> sum) {
		ResultModel rm=new ResultModel();
		SlmContractPayment payment=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmContractPayment> pm=new PageModel<SlmContractPayment>(pageIndex, pageSize);
		try {
			String sWhere="";
			if(payment.getContract_line_no()==null||"".equals(payment.getContract_line_no()))
				sWhere=" contract_line_no is null";
			List<SlmContractPayment> list=this.getMapper(SlmContractPaymentMapper.class).findWithCondition(payment, sWhere, " create_time ", (pageIndex-1)*pageSize,pageSize);
			int count=this.getMapper(SlmContractPaymentMapper.class).countWithCondition(payment,sWhere);
			pm.setRows(list);
			pm.setTotal(count);
			rm.setState("200");
			rm.setData(pm);
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，查询失败!"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 付款要求-新增
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddWeb(CommonPage<SlmContractPayment> sum) 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);
		SlmContractPayment payment=sum.getObject();
		try {
			//节点判断
			SlmContractPayment newPayment=new SlmContractPayment();
			newPayment.setContract_pk(payment.getContract_pk());
			newPayment.setContract_line_no(payment.getContract_line_no());
			newPayment.setPayment_point_no(payment.getPayment_point_no());
			List<SlmContractPayment> paymentList=this.getMapper(SlmContractPaymentMapper.class).find(newPayment, 0, 0);
			for(SlmContractPayment payments:paymentList){
				payments.setValid_flag("0");
				this.getMapper(SlmContractPaymentMapper.class).update(payments);
			}
			String strNo=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			payment.setPayment_no(strNo+PbMethod.RandomCreate(3));
			payment.setCreate_man_no(userId);
			payment.setCreate_man_name(userName);
			payment.setCreate_time(new Date());
			payment.setValid_flag("1");
			this.getMapper(SlmContractPaymentMapper.class).insert(payment);

			//修改合同主表状态
			SlmContractHeatInfo heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(payment.getContract_pk());
			if(heat!=null){
				heat.setHave_control("1");
				this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
			}
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，新增失败!"+e.getMessage());
			e.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 付款要求-编辑
	 * 有效无效（valid_flag=0:无效,1:有效）
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdateWeb(CommonPage<SlmContractPayment> sum) 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);
		SlmContractPayment payment=sum.getObject();
		try {
			if(payment.getPayment_no()==null||"".equals(payment.getPayment_no())){
				rm.setState("500");
				rm.setMsgInfo("请选中一条数据进行操作");
				return rm;
			}
			SlmContractPayment pay=this.getMapper(SlmContractPaymentMapper.class).findById(payment.getPayment_no());
			if("0".equals(payment.getValid_flag())){
				payment.setDelete_man_no(userId);
				payment.setDelete_man_name(userName);
				payment.setDelete_time(new Date());
			}else{
				SlmContractPayment newPayment=new SlmContractPayment();
				newPayment.setContract_pk(pay.getContract_pk());
				newPayment.setContract_line_no(pay.getContract_line_no());
				newPayment.setPayment_point_no(pay.getPayment_point_no());
				List<SlmContractPayment> paymentList=this.getMapper(SlmContractPaymentMapper.class).find(newPayment, 0, 0);
				for(SlmContractPayment payments:paymentList){
					payments.setValid_flag("0");
					this.getMapper(SlmContractPaymentMapper.class).update(payments);
				}
				payment.setUpdate_man_no(userId);
				payment.setUpdate_man_name(userName);
				payment.setUpdate_time(new Date());
			}
			this.getMapper(SlmContractPaymentMapper.class).update(payment);

			//修改合同头状态
			SlmContractPayment param=new SlmContractPayment();
			param.setContract_pk(pay.getContract_pk());
			param.setValid_flag("1");
			int count=this.getMapper(SlmContractPaymentMapper.class).count(param);
			if(count==0){
				SlmContractHeatInfo heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(pay.getContract_pk());
				if(heat!=null){
					heat.setHave_control("0");
					this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
				}
			}

			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，编辑失败!"+e.getMessage());
			e.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 判断账户可用金额是否满足 新增的付款节点金额
	 * flag 1扣款 2吐出
	 * 
	 * "主合同", null, "提单行信息", "提货单付款节点","2吐出"
	 * @throws Exception 
	 * */
	/**
	 * @param heat
	 * @param order
	 * @param bill_line
	 * @param payment_point_no
	 * @param flag
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddOccupy(SlmContractHeatInfo heat,SlmOrderInfo order,SlmLadingBillLine bill_line,String payment_point_no,String flag) throws Exception{
		ResultModel rm=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			//查询该合同的付款节点信息
			SlmContractPayment param_payment=new SlmContractPayment();
			param_payment.setContract_pk(heat.getContract_pk());
			param_payment.setPayment_point_no(payment_point_no);
			param_payment.setCustomer_no(heat.getCustomer_no());
			param_payment.setValid_flag("1");
			List<SlmContractPayment> payment_list=this.getMapper(SlmContractPaymentMapper.class).find(param_payment, 0, 0);
			if(payment_list.size()==0){
				rm.setState("200");
				return rm;
			}
			SlmContractPayment payment=payment_list.get(0);
			//再找到对应的合同账户信息
			SlmFundThirdAccount t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(heat.getContract_no());
			SlmContractHeatInfo contract_heat=new SlmContractHeatInfo();
			contract_heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(payment.getContract_pk());
			if(contract_heat==null){
				contract_heat=heat;
			}
			if(t_account==null){
				if(contract_heat.getContract_no()!=null){
					t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(contract_heat.getContract_no());
					if(t_account==null){
						//如果没有合同账户 则自动新增一条【前提，拥有产线账户
						//找到对应的客户账户
						List<SlmFundFirstAccount> f_account_list=this.getMapper(SlmFundFirstAccountMapper.class).findWithCondition(null, " customer_no='"+heat.getCustomer_no()+"'", null, 0, 0);
						if(f_account_list.size()>0){		//有客户账户，再查找产线账户
							List<SlmFundSecondAccount> s_account_list=this.getMapper(SlmFundSecondAccountMapper.class).findWithCondition(null, " first_account_no='"+f_account_list.get(0).getFirst_account_no()+"'", null, 0, 0);
							if(s_account_list.size()==1){			//只有一条产线账户
								t_account=new SlmFundThirdAccount();			//生成合同账户
								t_account.setFirst_account_no(f_account_list.get(0).getFirst_account_no());
								t_account.setFirst_account_name(f_account_list.get(0).getFirst_account_name());
								t_account.setSecond_account_no(s_account_list.get(0).getSecond_account_no());
								t_account.setSecond_account_name(s_account_list.get(0).getSecond_account_name());
								t_account.setBalance_object_no(f_account_list.get(0).getBalance_object_no());
								t_account.setBalance_object_name(f_account_list.get(0).getBalance_object_name());
								t_account.setCustomer_no(f_account_list.get(0).getCustomer_no());
								t_account.setCustomer_name(f_account_list.get(0).getCustomer_name());
								t_account.setThird_account_no(contract_heat.getContract_no());
								t_account.setThird_account_name(contract_heat.getContract_no());
								t_account.setInit_fund(0d);
								this.getBean(SlmFundThirdAccountServiceImpl.class).doAddWeb(t_account);
							}else{
								rm.setState("500");
								rm.setMsgInfo("请确保在该客户账户下只有一条产线账户，以便自动生成合同账户");
								return rm;
							}
						}else{
							rm.setState("500");
							rm.setMsgInfo("请先新增该客户的账户，以便发生资金占用");
							return rm;
						}
					}
				}
			}
			if("1".equals(t_account.getLock_flag())){
				rm.setState("500");
				rm.setMsgInfo("对应的合同账户已经结转，如须资金占用请解锁");
				return rm;
			}
			//计算该节点需要到此合同账户里扣除的金额
			double total_money=0d;
			double rate=0.01;
			if("102902".equals(payment.getUnit_no())){
				rate=0.001;
			}
						
			if("102703".equals(payment.getPayment_point_no())){		//提货单
				//订单信息
				SlmOrderInfo bill_order=new SlmOrderInfo();
				bill_order.setContract_no(bill_line.getContract_no());
				bill_order.setContract_line_seq(bill_line.getContract_line_seq());
				bill_order.setOrder_seq(bill_line.getOrder_seq());
				List<SlmOrderInfo> order_list=this.getMapper(SlmOrderInfoMapper.class).find(bill_order, 0, 0);
				if(order_list.size()>0){
					order=order_list.get(0);
				}
				//合同行信息
				SlmContractLineInfo contract_line=new SlmContractLineInfo();
				contract_line.setContract_no(bill_line.getContract_no());
				contract_line.setContract_line_seq(bill_line.getContract_line_seq());
				List<SlmContractLineInfo> contract_list=this.getMapper(SlmContractLineInfoMapper.class).find(contract_line, 0, 0);
				double trade_price=0d; 	//运费
				//20210920 合同签订日期在0926后，取订单的运费
				String condition = " contract_pk = '"+ order.getContract_pk() +"' and sign_date > to_date('2021-09-26','yyyy-MM-dd') and valid_flag = '1'";
				List<SlmContractHeatInfo> schiList = this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, condition, "create_time desc", 0, 1);
				if (CollectionUtils.isNotEmpty(schiList)) {
					trade_price = order.getTrade_price();//取订单行的运费
				}else {				
					if(contract_list.size()>0&&"1".equals(order.getOrder_nature())){
						contract_line=contract_list.get(0);
						trade_price=contract_line.getTrade_price();
					}
					//20191130 需加工且净重交货的，吃合同行的运费(林q提出)
					if (contract_list.size()>0 && "2".equals(order.getOrder_nature()) && "102301".equals(order.getWeight_type_no())) {
						trade_price = contract_list.get(0).getTrade_price();
					}
					//20191130 冷轧订单或者酸洗订单，吃合同行的运费(丁y提出)
					//20210422 非计划订单，吃合同行的运费(王hw,李xq提出)
					if (contract_list.size()>0 && ("3".equals(order.getOrder_nature()) || "4".equals(order.getOrder_nature()) || "5".equals(order.getOrder_nature()))) {
						trade_price = contract_list.get(0).getTrade_price();
					}
				}
				
				
				//查询是否有合同占用，订单占用
				double order_money=0d;
				double contract_rate=0d;
				double order_rate=0d;
				
				//占用金额  （订单的加工配送费+订单的结算金额+合同行的运费）*提单行的重量*占用比例*比例符号
				double ratio=(payment.getRatio_value()+order_rate+contract_rate);
				double bill_price= 0d;
				if (CollectionUtils.isNotEmpty(schiList)) {//直接取结算价+加工配送费
					bill_price = DoubleUtil.round((order.getWork_price()+order.getBalance_price())*bill_line.getBill_weight()*ratio*rate,DoubleUtil.SCALE_PRICE);					
				}else {
					bill_price = DoubleUtil.round((order.getWork_price()+order.getBalance_price()+trade_price)*bill_line.getBill_weight()*ratio*rate,DoubleUtil.SCALE_PRICE);
				}
				
				// 还要加上根据每个卷的可发天数得出的：(转库费单价 + 资金占用费单价) * 单卷的实重 * 税率 20230218刘侣
				double zkfUPrice = 0d;
				double zhanyUPrice = 0d;
				double coilExtraMoney = 0d; // 提单所有卷应该缴纳的额外的钱  += (转库费单价 + 资金占用费单价) * 单卷的实重 * 税率；
				if(bill_line.getDetailList() == null || bill_line.getDetailList().size() <= 0) {
					// 点的废除提单按钮：可能有多个提单行，所以拿提单行号去查提单明细；
					List<SlmLadingBillDetail> detailsl = this.getMapper(SlmLadingBillDetailMapper.class).findWithCondition(null, " LINE_NO='"+bill_line.getLine_no()+"'", null, 0, 0);
					for(SlmLadingBillDetail slbd : detailsl) {
						coilExtraMoney = DoubleUtil.add(coilExtraMoney, slbd.getExtra_money());
					}
				} else {
					for(YdmProductDetail ypd:bill_line.getDetailList()){
						zkfUPrice = ypd.getKfts() == null ? 0d : Integer.parseInt(ypd.getKfts()) > 10 ? 30.00 : 0d;
						zhanyUPrice = ypd.getKfts() == null ? 0d : Integer.parseInt(ypd.getKfts()) > 30 ? 90.00 :
							Integer.parseInt(ypd.getKfts()) > 20 ? 60.00 : Integer.parseInt(ypd.getKfts()) > 10 ? 30.00 : 0d;
						coilExtraMoney += (DoubleUtil.round((zkfUPrice+zhanyUPrice)*ypd.getFactweight()*payment.getRatio_value()*rate,DoubleUtil.SCALE_PRICE));
					}
				}
				bill_price=DoubleUtil.add(bill_price, coilExtraMoney); // 最终的应该要占用多少钱；
				// end
				
				bill_line.setWork_price(bill_price);//占用金额
				total_money=bill_price;
			}

			//与一级账户和二级账户和三级账户里的可用金额进行比较
			double money=total_money;		//占用资金
			SlmFundFirstAccount account=this.getMapper(SlmFundFirstAccountMapper.class).findById(t_account.getFirst_account_no());
			if(account!=null&&t_account!=null){
				if((money>t_account.getUse_fund())&&!"2".equals(flag)){			//超过了3级账户的金额
					//查询二级账户
					SlmFundSecondAccount s_account=this.getMapper(SlmFundSecondAccountMapper.class).findById(t_account.getSecond_account_no());
					if(money>(s_account.getUse_fund()+t_account.getUse_fund())){			//与（二级账户的可用金额+三级账户的可用金额）比对
						//那么就去一级账户里薅钱  【应改为判断一级可拨+二三级可用
						// =============eason 2019-06-20 注释下面这行，然后调整为下下面那行================
						// if(money>account.getUse_fund()){
						if(money>account.getFinal_fund()){
							rm.setState("500");
							// rm.setMsgInfo("所需占用金额["+money+"]超出客户账户"+account.getFirst_account_name()+"下的可用金额["+account.getUse_fund()+"]");
							rm.setMsgInfo("所需占用金额["+money+"]超出客户账户"+account.getFirst_account_name()+"下的可拨金额["+account.getFinal_fund()+"]");
							return rm;
						}else{			//一级账户钱够
							double cha=DoubleUtil.sub(money,DoubleUtil.add(t_account.getUse_fund(),s_account.getUse_fund()));	//需要拨的金额
							double erji=s_account.getUse_fund();
							//从一级到二级
							SlmFundSecondDetail inOut=new SlmFundSecondDetail();
							inOut.setSecond_account_no(s_account.getSecond_account_no());
							inOut.setSecond_account_name(s_account.getSecond_account_name());
							inOut.setOther_account_no(account.getFirst_account_no());
							inOut.setOther_account_name(account.getFirst_account_name());
							inOut.setBalance_object_no(account.getBalance_object_no());
							inOut.setBalance_object_name(account.getBalance_object_name());
							inOut.setCustomer_no(account.getCustomer_no());
							inOut.setCustomer_name(account.getCustomer_name());
							inOut.setIn_out_fund(cha);
							inOut.setTrans_class("1");		//一级到二级
							
							//==================eason edit 2019-06-26 注释下面一行，新增其余的=============
							//this.getBean(SlmFundSecondDetailServiceImpl.class).doAddInWeb(inOut);
							rm = this.getBean(SlmFundSecondDetailServiceImpl.class).doAddInWeb(inOut);
							if("500".equals(rm.getState())) {
								return rm;
							}
							//===========================================================================
							
							//二级到三级
							inOut.setOther_account_no(t_account.getThird_account_no());
							inOut.setOther_account_name(t_account.getThird_account_name());
							inOut.setIn_out_fund(DoubleUtil.add(cha,erji));
							inOut.setTrans_class("3");		//二级到三级
							
							//==================eason edit 2019-06-26 注释下面一行，新增其余的=============
							//this.getBean(SlmFundSecondDetailServiceImpl.class).doAddOutWeb(inOut);
							rm = this.getBean(SlmFundSecondDetailServiceImpl.class).doAddOutWeb(inOut);
							if("500".equals(rm.getState())) {
								return rm;
							}
							//=============================================================================
						}
					}else{			//如果二级+三级有足够的钱 则 进行调拨
						SlmFundSecondDetail inOut=new SlmFundSecondDetail();
						inOut.setSecond_account_no(s_account.getSecond_account_no());
						inOut.setSecond_account_name(s_account.getSecond_account_name());
						inOut.setOther_account_no(t_account.getThird_account_no());
						inOut.setOther_account_name(t_account.getThird_account_name());
						inOut.setBalance_object_no(t_account.getBalance_object_no());
						inOut.setBalance_object_name(t_account.getBalance_object_name());
						inOut.setCustomer_no(t_account.getCustomer_no());
						inOut.setCustomer_name(t_account.getCustomer_name());
						inOut.setIn_out_fund(DoubleUtil.sub(money,t_account.getUse_fund()));
						inOut.setTrans_class("3");		//二级到三级
						
						//==================eason edit 2019-06-26 注释下面一行，新增其余的=============
						//this.getBean(SlmFundSecondDetailServiceImpl.class).doAddOutWeb(inOut);
						rm = this.getBean(SlmFundSecondDetailServiceImpl.class).doAddOutWeb(inOut);
						if("500".equals(rm.getState())) {
							return rm;
						}
						//=============================================================================
						
					}
				}
			}else{
				rm.setState("500");
				rm.setMsgInfo("账户数据丢失，请联系管理员修复");
				return rm;
			}
			t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(t_account.getThird_account_no());			//刷新三级账户
			account=this.getMapper(SlmFundFirstAccountMapper.class).findById(t_account.getFirst_account_no());

			//如果可占用，生成占用信息
			SlmFundThirdAccountUsed used=new SlmFundThirdAccountUsed();	
			used=this.getBean(SlmFundThirdAccountUsedServiceImpl.class).doAdd(t_account,payment,contract_heat);

			if("102703".equals(payment.getPayment_point_no())){		//提货单
				used.setContract_line_no(bill_line.getContract_line_no());
				used.setContract_line_seq(bill_line.getContract_line_seq());
				used.setOrder_no(bill_line.getOrder_no());
				used.setOrder_seq(bill_line.getOrder_seq());
				used.setPrice(DoubleUtil.add(order.getBalance_price(),order.getWork_price()));//价格 = 结算价+加工配送费：这里由于每个卷的转库费和资金占用费可能不一致，所以这里的单价没有加上转库费和资金占用费20230218刘侣
				used.setBill_no(bill_line.getBill_no());
				used.setWeight(bill_line.getBill_weight());
				used.setWeight_unit_no(bill_line.getBill_weight_unit_no());
				used.setWeight_unit_name(bill_line.getBill_weight_unit_name());
				used.setUsed_fund(bill_line.getWork_price());		//先前计算的占用金额
				used.setFlag("0");
				if("2".equals(flag)){			//释放
					SlmFundThirdAccountUsed check_param=new SlmFundThirdAccountUsed();
					check_param.setContract_no(used.getContract_no());
					check_param.setContract_line_no(used.getContract_line_no());
					check_param.setContract_line_seq(used.getContract_line_seq());
					check_param.setWeight(used.getWeight());
					check_param.setPrice(used.getPrice());
					check_param.setFlag("0");
					check_param.setBill_no(used.getBill_no());
					List<SlmFundThirdAccountUsed> check_list=this.getMapper(SlmFundThirdAccountUsedMapper.class).find(check_param, 0, 0);
					if(check_list.size()>0){
						check_list.get(0).setFlag("1");  		//释放原来的占用
						this.getMapper(SlmFundThirdAccountUsedMapper.class).update(check_list.get(0));
					}
					used.setFlag("1");			//也是释放
					used.setUsed_fund(-bill_line.getWork_price());
				}
				this.getMapper(SlmFundThirdAccountUsedMapper.class).insert(used);
			}

			if("2".equals(flag))
				money=-money;
			//账户金额修改
			account.setUse_fund(DoubleUtil.sub(account.getUse_fund(),money));		//一级 账期可用资金-money
			account.setUsed_fund(DoubleUtil.add(account.getUsed_fund(),money)); 		//一级  账期占用资金+money
			//=======eason add 2019-06-26 注释下面这行,因为资金调拨的时候就做了这个，这里不能再操作一级可拨=======
			// account.setFinal_fund(DoubleUtil.sub(account.getFinal_fund(), money));    //一级 账期可拨资金-money
			//===============================================================================================
			t_account.setUse_fund(DoubleUtil.sub(t_account.getUse_fund(),money)); 	//三级  可用资金-money
			t_account.setUsed_fund(DoubleUtil.add(t_account.getUsed_fund(),money)); 	//三级 占用资金+money
			if(account.getFinal_fund()>account.getUse_fund()) account.setFinal_fund(account.getUse_fund());
			this.getMapper(SlmFundThirdAccountMapper.class).update(t_account);
			this.getMapper(SlmFundFirstAccountMapper.class).update(account);
			//==================eason add 2019-06-26 注释一行，新增一行============
			//if(account.getUse_fund()<0){
			if(t_account.getUse_fund()<0){
			//===================================================================
				this.getBean(SlmFundSecondDetailServiceImpl.class).doAuto(account,t_account);
			}
			
			// 自动调拨资金：20220623 treals 作废提单时自动调拨资金 待测试
//			if("2".equals(flag)){			//释放
//				
//				SlmFundSecondAccount s_account=this.getMapper(SlmFundSecondAccountMapper.class).findById(t_account.getSecond_account_no());
//				if("1".equals(s_account.getLock_flag())){
//					rm.setState("500");
//					rm.setMsgInfo("该账户已经结转，如须拨款请解锁");
//					return rm;
//				}
//				// 三级到二级调拨：
//				SlmFundSecondDetail secondDetail = new SlmFundSecondDetail();
//				secondDetail.setSecond_account_no(s_account.getSecond_account_no());
//				secondDetail.setSecond_account_name(s_account.getSecond_account_name());
//
//				secondDetail.setOther_account_no(t_account.getThird_account_no());
//				secondDetail.setOther_account_name(t_account.getThird_account_name());
//				
//				secondDetail.setIn_out_fund(-money);
//				secondDetail.setTrans_class("3");
//				
//				this.getBean(SlmFundSecondDetailServiceImpl.class).doAddInWeb(secondDetail);
//				
//				// 二级到一级调拨：
//				SlmFundSecondDetail secondDetail2 = new SlmFundSecondDetail();
//				secondDetail2.setSecond_account_no(s_account.getSecond_account_no());
//				secondDetail2.setSecond_account_name(s_account.getSecond_account_name());
//
//				secondDetail2.setOther_account_no(t_account.getThird_account_no());
//				secondDetail2.setOther_account_name(t_account.getThird_account_name());
//				
//				secondDetail2.setIn_out_fund(-money);
//				secondDetail2.setTrans_class("1");
//				this.getBean(SlmFundSecondDetailServiceImpl.class).doAddOutWeb(secondDetail2);
//				//日志
//				MesOprLog mol = new MesOprLog("销售管理", "提货单管理", "作废提货单自动调拨资金", username, opr_time, null, null, null, null, "资金：" + (-money));
//				this.getMapper(MesOprLogMapper.class).insert(mol);
//			}
			// end
			
			// 增加或者废除占用时增加日志：
			//日志
			MesOprLog mol = new MesOprLog("销售管理", "汽运提货单管理", "2".equals(flag) ? "释放占用" : "增加占用", username, opr_time, null, bill_line.getOrder_no(), bill_line.getBill_no(), null, "占用金额：" + money  + "," + bill_line.getLine_no());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 释放资金占用 订单取消接收
	 * */
	public ResultModel doJudgeBill(SlmContractHeatInfo heat,SlmLadingBillLine old_bill,SlmLadingBillLine bill_line,String payment_point_no){
		ResultModel rm=new ResultModel();
		try{
			//查询该合同的付款节点信息
			SlmContractPayment param_payment=new SlmContractPayment();
			param_payment.setPayment_point_no(payment_point_no);
			param_payment.setCustomer_no(heat.getCustomer_no());
			param_payment.setValid_flag("1");
			List<SlmContractPayment> payment_list=this.getMapper(SlmContractPaymentMapper.class).find(param_payment, 0, 0);
			if(payment_list.size()==0){
				rm.setState("200");
				return rm;
			}
			SlmContractPayment payment=payment_list.get(0);
			//再找到对应的合同账户信息
			SlmFundThirdAccount t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(payment.getContract_pk());
			SlmContractHeatInfo contract_heat=new SlmContractHeatInfo();
			contract_heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(payment.getContract_pk());
			if(t_account==null){
				if(contract_heat==null){
					contract_heat=heat;
				}
				t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(contract_heat.getContract_no());
				if(t_account==null){
					rm.setState("500");
					rm.setMsgInfo("未找到对应的合同账户");
					return rm;
				}
			}
			if("1".equals(t_account.getLock_flag())){
				rm.setState("500");
				rm.setMsgInfo("对应的合同账户已经结转，如须资金占用请解锁");
				return rm;
			}
			//计算该节点需要到此合同账户里扣除的金额
			double rate=0.01;
			if("102902".equals(payment.getPayment_ratio_type_no())){
				rate=0.001;
			}
			double old_price=0d;
			double new_price=0d;
			double money=0d;
			if("102703".equals(payment.getPayment_point_no())){		//提货单
				SlmOrderInfo bill_order=new SlmOrderInfo();
				bill_order.setContract_no(bill_line.getContract_no());
				bill_order.setContract_line_seq(bill_line.getContract_line_seq());
				bill_order.setOrder_seq(bill_line.getOrder_seq());
				List<SlmOrderInfo> order_list=this.getMapper(SlmOrderInfoMapper.class).find(bill_order, 0, 0);
				if(order_list.size()>0){
					bill_order=order_list.get(0);
				}
				old_price=DoubleUtil.round(bill_order.getBalance_price()*old_bill.getBill_weight()*payment.getRatio_value()*rate,DoubleUtil.SCALE_PRICE);
				new_price=DoubleUtil.round(bill_order.getBalance_price()*bill_line.getBill_weight()*payment.getRatio_value()*rate,DoubleUtil.SCALE_PRICE);
				money=new_price-old_price;
			}
			if((t_account.getUse_fund()-money)<0){
				rm.setState("500");
				rm.setMsgInfo("所需占用金额["+money+"]超出合同账户"+t_account.getThird_account_name()+"的可用金额["+t_account.getUse_fund()+"]，无法新增");
				return rm;
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}


	/**
	 * 判断是否有足够的资金来发生占用
	 * */
	public ResultModel doJudgeAccount(SlmContractHeatInfo heat,List<SlmLadingBillLine> list){
		ResultModel rm=new ResultModel();
		try{
			//查询该合同的付款节点信息
			SlmContractPayment param_payment=new SlmContractPayment();
			param_payment.setPayment_point_no("102703");
			param_payment.setCustomer_no(heat.getCustomer_no());
			param_payment.setValid_flag("1");
			param_payment.setContract_pk(heat.getContract_pk());
			List<SlmContractPayment> payment_list=this.getMapper(SlmContractPaymentMapper.class).find(param_payment, 0, 0);
			if(payment_list.size()==0){
				rm.setState("500");
				rm.setMsgInfo("客户对应合同付款节点不一致");
				return rm;
			}
			SlmContractPayment payment=payment_list.get(0);
			//再找到对应的合同账户信息
			SlmFundThirdAccount t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(heat.getContract_no());
			SlmContractHeatInfo contract_heat=new SlmContractHeatInfo();
			if(t_account==null){
				contract_heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(payment.getContract_pk());
				if(contract_heat==null){
					contract_heat=heat;
				}
				if(contract_heat.getContract_no()!=null){
					t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(contract_heat.getContract_no());
					if(t_account==null){
						//如果没有合同账户 则自动新增一条【前提，拥有产线账户
						//找到对应的客户账户
						List<SlmFundFirstAccount> f_account_list=this.getMapper(SlmFundFirstAccountMapper.class).findWithCondition(null, " customer_no='"+heat.getCustomer_no()+"'", null, 0, 0);
						if(f_account_list.size()>0){		//有客户账户，再查找产线账户
							List<SlmFundSecondAccount> s_account_list=this.getMapper(SlmFundSecondAccountMapper.class).findWithCondition(null, " first_account_no='"+f_account_list.get(0).getFirst_account_no()+"'", null, 0, 0);
							if(s_account_list.size()==1){			//只有一条产线账户
								t_account=new SlmFundThirdAccount();			//生成合同账户
								t_account.setFirst_account_no(f_account_list.get(0).getFirst_account_no());
								t_account.setFirst_account_name(f_account_list.get(0).getFirst_account_name());
								t_account.setSecond_account_no(s_account_list.get(0).getSecond_account_no());
								t_account.setSecond_account_name(s_account_list.get(0).getSecond_account_name());
								t_account.setBalance_object_no(f_account_list.get(0).getBalance_object_no());
								t_account.setBalance_object_name(f_account_list.get(0).getBalance_object_name());
								t_account.setCustomer_no(f_account_list.get(0).getCustomer_no());
								t_account.setCustomer_name(f_account_list.get(0).getCustomer_name());
								t_account.setThird_account_no(contract_heat.getContract_no());
								t_account.setThird_account_name(contract_heat.getContract_no());
								t_account.setInit_fund(0d);
								this.getBean(SlmFundThirdAccountServiceImpl.class).doAddWeb(t_account);
							}else{
								rm.setState("500");
								rm.setMsgInfo("请确保在该客户账户下只有一条产线账户，以便自动生成合同账户");
								return rm;
							}
						}else{
							rm.setState("500");
							rm.setMsgInfo("请先新增该客户的账户，以便发生资金占用");
							return rm;
						}
					}
				}
			}
			if("1".equals(t_account.getLock_flag())){
				rm.setState("500");
				rm.setMsgInfo("对应的合同账户已经结转，如须资金占用请解锁");
				return rm;
			}
			//计算该节点需要到此合同账户里扣除的金额
			double rate=0.01;
			if("102902".equals(payment.getPayment_ratio_type_no())){
				rate=0.001;
			}

			double total=0d;
			for(SlmLadingBillLine lines:list){
				SlmOrderInfo bill_order=new SlmOrderInfo();
				bill_order.setContract_no(lines.getContract_no());
				bill_order.setContract_line_seq(lines.getContract_line_seq());
				bill_order.setOrder_seq(lines.getOrder_seq());
				List<SlmOrderInfo> order_list=this.getMapper(SlmOrderInfoMapper.class).find(bill_order, 0, 0);
				if(order_list.size()>0){
					bill_order=order_list.get(0);
				}

				//合同行信息
				SlmContractLineInfo contract_line=new SlmContractLineInfo();
				contract_line.setContract_no(lines.getContract_no());
				contract_line.setContract_line_seq(lines.getContract_line_seq());
				List<SlmContractLineInfo> contract_list=this.getMapper(SlmContractLineInfoMapper.class).find(contract_line, 0, 0);
				double trade_price=0d; 	//运费
				
				//20210920 合同签订日期在0926后，取订单的运费
				String condition = " contract_pk = '"+ bill_order.getContract_pk() +"' and sign_date > to_date('2021-09-26','yyyy-MM-dd') and valid_flag = '1'";
				List<SlmContractHeatInfo> schiList = this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, condition, "create_time desc", 0, 1);
				if (CollectionUtils.isNotEmpty(schiList)) {
					trade_price = bill_order.getTrade_price();//取订单行的运费
				}else {					
					if(contract_list.size()>0 && "1".equals(bill_order.getOrder_nature())){
						contract_line=contract_list.get(0);
						trade_price=contract_line.getTrade_price();
					}				
					//20191130 需加工且净重交货的，吃合同行的运费(林强提出)
					if (contract_list.size()>0 && "2".equals(bill_order.getOrder_nature()) && "102301".equals(bill_order.getWeight_type_no())) {
						trade_price = contract_list.get(0).getTrade_price();
					}
					//20191130 冷轧订单或者酸洗订单，吃合同行的运费(丁跃提出)
					if (contract_list.size()>0 && ("3".equals(bill_order.getOrder_nature()) || "4".equals(bill_order.getOrder_nature()) || "5".equals(bill_order.getOrder_nature()))) {
						trade_price = contract_list.get(0).getTrade_price();
					}
				}
				double bill_price = 0d;
				if (CollectionUtils.isNotEmpty(schiList)) {//0926后签订的合同：取结算价+加工配送费
					bill_price=DoubleUtil.round((bill_order.getWork_price()+bill_order.getBalance_price())*lines.getBill_weight()*payment.getRatio_value()*rate,DoubleUtil.SCALE_PRICE);
				}else {
					bill_price=DoubleUtil.round((bill_order.getWork_price()+bill_order.getBalance_price()+trade_price)*lines.getBill_weight()*payment.getRatio_value()*rate,DoubleUtil.SCALE_PRICE);
				}				
				total=DoubleUtil.add(total, bill_price);
				// 还要加上根据每个卷的可发天数得出的：(转库费单价 + 资金占用费单价) * 单卷的实重 * 税率 20230218刘侣
				double zkfUPrice = 0d;
				double zhanyUPrice = 0d;
				double coilExtraMoney = 0d; // 提单所有卷应该缴纳的额外的钱  += (转库费单价 + 资金占用费单价) * 单卷的实重 * 税率；
				for(YdmProductDetail ypd:lines.getDetailList()){	
					zkfUPrice = ypd.getKfts() == null ? 0d : Integer.parseInt(ypd.getKfts()) > 10 ? 30.00 : 0d;
					zhanyUPrice = ypd.getKfts() == null ? 0d : Integer.parseInt(ypd.getKfts()) > 30 ? 90.00 : 
						Integer.parseInt(ypd.getKfts()) > 20 ? 60.00 : Integer.parseInt(ypd.getKfts()) > 10 ? 30.00 : 0d;
					coilExtraMoney += (DoubleUtil.round((zkfUPrice+zhanyUPrice)*ypd.getFactweight()*payment.getRatio_value()*rate,DoubleUtil.SCALE_PRICE));
				}
				total=DoubleUtil.add(total, coilExtraMoney);
				// end
			}
			//目前只判断一级账户的可用是否足够  应改为【判断三级自己的可用+一级的可拨是否足够
			SlmFundFirstAccount f_account=this.getMapper(SlmFundFirstAccountMapper.class).findById(t_account.getFirst_account_no());
			double total_use=0d;
			if(f_account!=null){
				total_use=f_account.getUse_fund();
			}
			if(DoubleUtil.round(total_use,2)<DoubleUtil.round(total,2)){
				rm.setState("500");
				rm.setMsgInfo("所需占用金额["+DoubleUtil.round(total,2)+"]超出"+f_account.getCustomer_name()+"的可用金额["+DoubleUtil.round(total_use,2)+"]，无法新增");
				return rm;
			}
			rm.setState("200");
		}catch(Exception e){
			e.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	/***
	 * 方案替换
	 * [{"memo1":"contract_pk","memo2":"plan_no"}]
	 * */
	public ResultModel doReplaceWeb(CommonPage<SlmContractPayment> sum){
		ResultModel rm=new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String contract_pk=sum.getMemo1();
		String plan_no=sum.getMemo2();
		try{
			SlmContractPayment payment=new SlmContractPayment();
			payment.setContract_pk(contract_pk);
			SlmContractHeatInfo scli = this.getMapper(SlmContractHeatInfoMapper.class).findById(contract_pk);
			if(!userId.equals(scli.getCreate_man_no())){
				rm.setState("500");
				rm.setMsgInfo("当前用户不允许操作此合同！");
				return rm;
			}
			List<SlmContractPayment>  payment_list=this.getMapper(SlmContractPaymentMapper.class).find(payment, 0, 0);
			for(SlmContractPayment payments:payment_list){
				this.getMapper(SlmContractPaymentMapper.class).delete(payments.getPayment_no());
			}
			generateParam(plan_no,contract_pk);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	public void doAutoAdd(SlmContractHeatInfo bd) throws Exception {
		SlmContractPaymentPlan plan=new SlmContractPaymentPlan();
		plan.setValid_flag("1");
		//==============eason edit 2019-06-26 注释下面这2行的代码============
		//plan.setCustomer_no(bd.getCustomer_no());
		//List<SlmContractPaymentPlan> plan_list=this.getMapper(SlmContractPaymentPlanMapper.class).find(plan,0,0);
				
		// ===============eason add 2019-06-26==================
		List<SlmContractPaymentPlan> plan_list=new ArrayList<SlmContractPaymentPlan>();
		SlmContractPaymentConfig scpc=new SlmContractPaymentConfig();
		scpc.setCustomer_no(bd.getCustomer_no());
		List<SlmContractPaymentConfig> lscpc=this.getMapper(SlmContractPaymentConfigMapper.class).find(scpc, 0, 0);
		String sWh="";
		for(SlmContractPaymentConfig scpcc:lscpc){
			sWh+="'"+scpcc.getPlan_no()+"',";
		}
		if(!"".equals(sWh)){
			sWh=sWh.substring(0,sWh.length()-1);
			plan_list=this.getMapper(SlmContractPaymentPlanMapper.class).findWithCondition(plan, " plan_no in("+sWh+")", "", 0, 0);
		}
		// ====================================================
		
		if(plan_list.size()>0){			//该客户配置了方案
			plan=plan_list.get(0);
			generateParam(plan.getPlan_no(),bd.getContract_pk());
		}else{			
			//=================2019-07-02 edit 注释下面的代码=============================
			/*
			//没配置方案的情况，先取其他客户的付款方案
			plan.setCustomer_no(null);
			plan_list=this.getMapper(SlmContractPaymentPlanMapper.class).find(plan,0,0);
			if(plan_list.size()>0){
				plan=plan_list.get(0);
				generateParam(plan.getPlan_no(),bd.getContract_pk());
			}else{		
			*/
			//===========================================================================	
				//实在没有方案  提货单100%
				SlmContractPayment payment=new SlmContractPayment();
				payment.setCustomer_no(bd.getCustomer_no());
				payment.setCustomer_name(bd.getCustomer_name());
				payment.setPayment_point_no("102703");
				payment.setPayment_point_name("提货单");
				payment.setPayment_ratio_type_no("102803");
				payment.setPayment_ratio_type_name("交货款");
				payment.setRatio_value(100d);
				payment.setUnit_no("102901");
				payment.setUnit_name("%");
				payment.setPayment_content("");
				payment.setContract_pk(bd.getContract_pk());
				CommonPage<SlmContractPayment> pay_sum=new CommonPage<SlmContractPayment>();
				pay_sum.setObject(payment);
				this.getBean(SlmContractPaymentServiceImpl.class).doAddWeb(pay_sum);
			//}
		}
	}

	private void generateParam(String plan_no,String contract_pk){
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		SlmContractPaymentConfigure config=new SlmContractPaymentConfigure();
		config.setPlan_no(plan_no);
		config.setValid_flag("1");
		List<SlmContractPaymentConfigure> config_list=this.getMapper(SlmContractPaymentConfigureMapper.class).find(config,0,0);
		//===================eason add 2019-06-30 add=========================
		SlmContractHeatInfo schi=this.getMapper(SlmContractHeatInfoMapper.class).findById(contract_pk);
		//====================================================================
		for(SlmContractPaymentConfigure configs:config_list){
			SlmContractPayment payment=new SlmContractPayment();
			payment.setContract_pk(contract_pk);
			payment.setCustomer_no(configs.getCustomer_no());
			payment.setCustomer_name(configs.getCustomer_name());
			//===================eason add 2019-06-30 add，加两行=========================
			if(schi!=null&&schi.getCustomer_no()!=null){
				payment.setCustomer_no(schi.getCustomer_no());
				payment.setCustomer_name(schi.getCustomer_name());
			}
			//====================================================================
			payment.setPayment_content(configs.getPayment_content());
			payment.setPayment_point_no(configs.getPayment_point_no());
			payment.setPayment_point_name(configs.getPayment_point_name());
			payment.setPayment_ratio_type_no(configs.getPayment_ratio_type_no());
			payment.setPayment_ratio_type_name(configs.getPayment_ratio_type_name());
			payment.setRatio_value(configs.getRatio_value());
			payment.setUnit_no(configs.getUnit_no());
			payment.setUnit_name(configs.getUnit_name());
			String strNo=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			payment.setPayment_no(strNo+PbMethod.RandomCreate(3));
			payment.setCreate_man_no(userId);
			payment.setCreate_man_name(userName);
			payment.setCreate_time(new Date());
			payment.setValid_flag("1");
			this.getMapper(SlmContractPaymentMapper.class).insert(payment);
		}
		SlmContractHeatInfo heat=new SlmContractHeatInfo();
		heat.setContract_pk(contract_pk);
		heat.setHave_control("1");
		this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
	}
}

