package market.Slm.DeliveryManagement.impl;

import java.util.Date;
import java.util.List;

import market.Api.Lms.impl.LmsApiServiceImpl;
import market.Com.pb.DoubleUtil;
import market.Com.vo.CommonPage;
import market.Com.vo.PassportInfo;
import market.Com.vo.ResultModel;
import market.Lms.Logistics.mapper.LmsPassportinfoMapper;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Slm.ContractManagement.impl.SlmContractHeatInfoServiceImpl;
import market.Slm.ContractManagement.impl.SlmContractLineInfoServiceImpl;
import market.Slm.ContractManagement.impl.SlmContractPaymentServiceImpl;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractPaymentMapper;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.ContractManagement.vo.SlmContractPayment;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillDetailMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillHeatMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillLineMapper;
import market.Slm.DeliveryManagement.service.SlmLadingBillLineService;
import market.Slm.DeliveryManagement.vo.SlmLadingBillDetail;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;
import market.Slm.DeliveryManagement.vo.SlmLadingBillLine;
import market.Slm.FundManagement.impl.SlmFundSettleCarriageServiceImpl;
import market.Slm.FundManagement.impl.SlmFundSettleGoodServiceImpl;
import market.Slm.FundManagement.impl.SlmFundSettleOtherServiceImpl;
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.vo.SlmFundBalancePriceApply;
import market.Slm.FundManagement.vo.SlmFundSettleCarriage;
import market.Slm.FundManagement.vo.SlmFundSettleGood;
import market.Slm.FundManagement.vo.SlmFundSettleOther;
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 = "SlmLadingBillLineService")
public class SlmLadingBillLineServiceImpl extends
BaseServiceImpl<SlmLadingBillLine, Object> implements
SlmLadingBillLineService {
	/**
	 * 查询行
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmLadingBillLine> sum) {
		ResultModel rm = new ResultModel();
		SlmLadingBillLine line = sum.getObject();
		int pageIndex = sum.getPageIndex();
		int pageSize = sum.getPageSize();
		PageModel<SlmLadingBillLine> pm = new PageModel<SlmLadingBillLine>(
				pageIndex, pageSize);
		String flag = sum.getMemo1();
		try {
			List<SlmLadingBillLine> list = this.getMapper(
					SlmLadingBillLineMapper.class).findWithCondition(line,
							null, " valid_flag desc,create_time desc",
							(pageIndex - 1) * pageSize, pageSize);
			int count = this.getMapper(SlmLadingBillLineMapper.class)
					.countWithCondition(line, null);
			for (SlmLadingBillLine lines : list) {
				if ("1".equals(flag)) {
					SlmContractLineInfo contract_line = new SlmContractLineInfo();
					contract_line.setContract_no(lines.getContract_no());
					contract_line.setContract_line_seq(lines.getContract_line_seq());
					List<SlmContractLineInfo> lineList = this.getBean(SlmContractLineInfoServiceImpl.class)	.doQueryWithCondition(contract_line, null, null, 0,	0);
					SlmOrderInfo order = new SlmOrderInfo();
					order.setContract_no(lines.getContract_no());
					order.setContract_line_seq(lines.getContract_line_seq());
					order.setOrder_seq(lines.getOrder_seq());
					//===============eason edit 2019-07-31 注释一行，新增一行=================
					//List<SlmOrderInfo> orderList = this.getBean(SlmOrderInfoServiceImpl.class).doQuery(order);
					
					List<SlmOrderInfo> orderList = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order, " (change_flag is null or change_flag != '1') ", "create_time desc", 0, 0);
					//=====================================================
					if (orderList.size() > 0) {
						lines.setWork_price(orderList.get(0).getWork_price());
						lines.setBalance_price(orderList.get(0)	.getBalance_price());
					}
					if (lineList.size() > 0) {
						lines.setTrade_price(lineList.get(0).getTrade_price());
						if (lines.getBalance_price() == 0) {
							lines.setTrade_price(0d);
						}
					}
					// 带入申报过后的价格
					SlmFundBalancePriceApply apply = new SlmFundBalancePriceApply();
					apply.setBill_no(lines.getBill_no());
					apply.setLine_no(lines.getLine_no());
					apply.setValid_flag("3");
					List<SlmFundBalancePriceApply> apply_list = this.getMapper(SlmFundBalancePriceApplyMapper.class).find(apply,0, 0);
					for (SlmFundBalancePriceApply applys : apply_list) {
						SlmFundSettleCarriage carriage = this.getMapper(SlmFundSettleCarriageMapper.class).findById(applys.getObject_no());
						if (carriage != null) {
							lines.setTrade_price(applys.getNew_balance_price());
						} else {
							SlmFundSettleOther other = this.getMapper(	SlmFundSettleOtherMapper.class).findById(applys.getObject_no());
							if (other != null) {
								lines.setWork_price(applys.getNew_balance_price());
							} else {
								SlmFundSettleGood good = this.getMapper(SlmFundSettleGoodMapper.class).findById(applys.getObject_no());
								if (good != null) {
									lines.setBalance_price(applys.getNew_balance_price());
								}
							}
						}
					}
				} else {
					String order_no = lines.getContract_no()	+ lines.getContract_line_seq()+ lines.getOrder_seq();
					lines.setOrder_no(order_no);
				}
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setState("200");
			rm.setData(pm);
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 查询子提单以及明细
	 * */
	public ResultModel doQueryBillDetailWeb(CommonPage<SlmLadingBillLine> sum) {
		ResultModel rm = new ResultModel();
		SlmLadingBillLine line = sum.getObject();
		try {
			List<SlmLadingBillLine> line_list = this.getMapper(	SlmLadingBillLineMapper.class).findWithCondition(null,	" bill_no='" + line.getBill_no() + "' and valid_flag='1'",	null, 0, 0);
			for (SlmLadingBillLine lines : line_list) {
				String order_no = lines.getContract_no()	+ lines.getContract_line_seq() + lines.getOrder_seq();
				lines.setOrder_no(order_no);
				// 查询明细
				SlmLadingBillDetail detail = new SlmLadingBillDetail();
				detail.setLine_no(lines.getLine_no());
				detail.setBill_no(line.getBill_no());
				List<SlmLadingBillDetail> detail_list = this.getMapper(SlmLadingBillDetailMapper.class).find(detail, 0, 0);
				lines.setBillList(detail_list);
			}
			rm.setData(line_list);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 提单行新增
	 * 
	 * @throws Exception
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddWeb(CommonPage<SlmLadingBillLine> 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);
		SlmLadingBillLine line = sum.getObject();
		try {
			// 重量验证
			// SlmOrderInfo
			// order=this.getBean(SlmOrderInfoServiceImpl.class).doQueryOne(line.getOrder_no());
			// Double limitWeight=order.getEstimate_weight();
			// SlmLadingBillHeat
			// heat=this.getBean(SlmLadingBillHeatServiceImpl.class).doQueryOne(line.getBill_no());
			// if(("1".equals(heat.getBill_type())&&limitWeight<line.getActual_weight())||("2".equals(heat.getBill_type())&&limitWeight<line.getVirtual_weight())){
			// rm.setState("500");
			// rm.setMsgInfo(" 提单重量不能大于订单的计划重量 ");
			// return rm;
			// }
			SlmOrderInfo order=new SlmOrderInfo();
			order.setContract_no(line.getContract_no());
			order.setContract_line_seq(line.getContract_line_seq());
			order.setOrder_seq(line.getOrder_seq());
			List<SlmOrderInfo> order_list=this.getMapper(SlmOrderInfoMapper.class).find(order, 0, 0);
			if(order_list.size()>0){
				
				// 增加提单行计重方式的校验：20230721刘侣 废掉
//				if (!order_list.get(0).getWeight_type_no().equals(line.getWeight_type_no())) {
//					throw new Exception("提单行计重方式与订单不一致，请检查。");
//				}
				// end
				
				line.setProcess(order_list.get(0).getProcess());
			}
			int count = this.getMapper(SlmLadingBillLineMapper.class).countWithCondition(null," BILL_NO like concat('" + line.getBill_no()	+ "','%')") + 1;
			line.setLine_no(line.getBill_no() + String.format("%03d", count));
			line.setCreate_man_no(userId);
			line.setCreate_man_name(userName);
			line.setCreate_time(new Date());
			line.setValid_flag("1");
			line.setIs_detail("0");

			// 反写主提单的合同号
			rm = doAddContractNo(line);
			if ("500".equals(rm.getState()))
				return rm;
			if (line.getDetailList() != null && line.getDetailList().size() > 0) {
				String msg=doAddDetail(line); // 新增提单明细
				if(msg!=null){
					throw new Exception(msg);
				}
				line.setIs_detail("1");
			}
			this.getMapper(SlmLadingBillLineMapper.class).insert(line);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("子提单新增失败" + ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 子提单编辑
	 * 
	 * @throws Exception
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUpdateWeb(CommonPage<SlmLadingBillLine> 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);
		SlmLadingBillLine line = sum.getObject();
		try {
			// 判断何种状态可以进行编辑
			SlmLadingBillHeat heat = this.getBean(SlmLadingBillHeatServiceImpl.class).doQueryOne(	line.getBill_no());
			if (heat != null && !"1".equals(heat.getValid_status())) { // 只有编辑状态才可修改
				rm.setMsgInfo("当前状态无法编辑");
				rm.setState("500");
				return rm;
			}

			// 删除原有明细
			SlmLadingBillDetail detail = new SlmLadingBillDetail();
			detail.setLine_no(line.getLine_no());
			List<SlmLadingBillDetail> detailList = this.getBean(
					SlmLadingBillDetailServiceImpl.class).doQuery(detail);
			for (SlmLadingBillDetail details : detailList) {
				YdmProductDetail ypDetail = new YdmProductDetail();
				ypDetail.setCoilno(details.getCoilno());
				ypDetail.setBoxno(details.getBoxno());
				CommonPage<YdmProductDetail> cp = new CommonPage<YdmProductDetail>();
				cp.setObject(ypDetail);
				this.getBean(LmsApiServiceImpl.class).doShippingLockCanl(cp);
				this.getBean(SlmLadingBillDetailServiceImpl.class).doDelete(		details);
			}
			// 再新增
			if (line.getDetailList() != null && line.getDetailList().size() > 0) {
				doAddDetail(line);
				line.setIs_detail("1");
			} else {
				line.setIs_detail("0");
			}

			line.setUpdate_man_no(userId);
			line.setUpdate_man_name(userName);
			line.setUpdate_time(new Date());
			this.getMapper(SlmLadingBillLineMapper.class).update(line);

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

	/**
	 * 反写合同号
	 * @throws Exception 
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddContractNo(SlmLadingBillLine line) throws Exception {
		ResultModel rm = new ResultModel();
		try {
			// 反写合同号
			SlmLadingBillHeat bill_heat = this.getMapper(		SlmLadingBillHeatMapper.class).findById(line.getBill_no());
			if (bill_heat == null) {
				rm.setState("500");
				rm.setMsgInfo("提单数据丢失，请联系管理员");
				return rm;
			}
			if (bill_heat.getContract_no() == null		|| "".equals(bill_heat.getContract_no())) { // 如果主提单没有合同号，则赋值
				bill_heat.setContract_no(line.getContract_no());
				this.getMapper(SlmLadingBillHeatMapper.class).update(bill_heat);
			} else {
				if (!line.getContract_no().equals(bill_heat.getContract_no())) {
					rm.setState("500");
					rm.setMsgInfo("子提单与主提单的合同号不一致，无法新增");
					return rm;
				}
			}
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 子提单启用停用
	 * 
	 * @throws Exception
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doSwitchWeb(CommonPage<SlmLadingBillLine> 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);
		SlmLadingBillLine line = sum.getObject();
		String state = "1".equals(line.getValid_flag()) ? "启用" : "停用";
		try {
			// 判断何种状态可以进行启用停用
			SlmLadingBillHeat heat = this.getBean(	SlmLadingBillHeatServiceImpl.class).doQueryOne(line.getBill_no());
			if (heat != null && !"1".equals(heat.getValid_status())) { // 只有编辑状态才可修改
				rm.setMsgInfo("当前状态无法" + state);
				rm.setState("500");
				return rm;
			}
			String contract_no=heat.getContract_no();
			if ("0".equals(line.getValid_flag())) { // 停用
				line.setDelete_man_no(userId);
				line.setDelete_man_name(userName);
				line.setDelete_time(new Date());
				this.getMapper(SlmLadingBillLineMapper.class).update(line);
				// 提单头的合同号清空
				int count=this.getMapper(SlmLadingBillLineMapper.class).countWithCondition(null, " valid_flag='1' and bill_no='"+heat.getBill_no()+"'");
				if(count>1){
					heat.setContract_no("");
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}
				doInvalidDetail(line.getLine_no());
				//删除占用
				List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+contract_no+"'", null, 0, 0);
				SlmLadingBillLine check=this.getMapper(SlmLadingBillLineMapper.class).findById(line.getLine_no());
				if(heat_list.size()>0&&check!=null){
					this.getBean(SlmContractPaymentServiceImpl.class).doAddOccupy(heat_list.get(0), null, check, "102703","2");
				}
			} else { // 启用
				line.setUpdate_man_no(userId);
				line.setUpdate_man_name(userName);
				line.setUpdate_time(new Date());
				this.getMapper(SlmLadingBillLineMapper.class).doEnable(line);
			}
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo(state + "失败" + ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 子提单启用停用
	 * 
	 * @throws Exception
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDeleteWeb(CommonPage<SlmLadingBillLine> sum)
			throws Exception {
		ResultModel rm = new ResultModel();
		SlmLadingBillLine line = sum.getObject();
		try {
			// 判断何种状态可以进行启用停用
			SlmLadingBillHeat heat = this.getBean(	SlmLadingBillHeatServiceImpl.class).doQueryOne(line.getBill_no());
			if (heat != null && !"1".equals(heat.getValid_status())) { // 只有编辑状态才可修改
				rm.setMsgInfo("当前状态无法删除");
				rm.setState("500");
				return rm;
			}
			// 删除原有明细
			this.getMapper(SlmLadingBillLineMapper.class).delete(
					line.getLine_no());
			// 库存关闭锁定
			doInvalidDetail(line.getLine_no());

			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("删除失败" + ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 公用失效方法
	 * */
	public ResultModel doInvalidDetail(String line_no) {
		ResultModel rm = new ResultModel();
		// 库存关闭锁定
		SlmLadingBillDetail detail = new SlmLadingBillDetail();
		detail.setLine_no(line_no);
		List<SlmLadingBillDetail> detailList = this.getBean(
				SlmLadingBillDetailServiceImpl.class).doQuery(detail);
		for (SlmLadingBillDetail details : detailList) {
			YdmProductDetail ypDetail = new YdmProductDetail();
			ypDetail.setCoilno(details.getCoilno());
			ypDetail.setBoxno(details.getBoxno());
			CommonPage<YdmProductDetail> cp = new CommonPage<YdmProductDetail>();
			cp.setObject(ypDetail);
			this.getBean(LmsApiServiceImpl.class).doShippingLockCanl(cp);
			this.getBean(SlmLadingBillDetailServiceImpl.class)
			.doDelete(details);
		}
		rm.setState("200");
		return rm;
	}

	/**
	 * 详情
	 * */
	public ResultModel doQueryDetailWeb(CommonPage<SlmLadingBillLine> sum) {
		ResultModel rm = new ResultModel();
		SlmLadingBillLine line = sum.getObject();
		try {
			line = this.getMapper(SlmLadingBillLineMapper.class).findById(
					line.getLine_no());
			if (line != null) {
				String order_no = line.getContract_no()
						+ line.getContract_line_seq() + line.getOrder_seq();
				line.setOrder_no(order_no);
			}
			rm.setData(line);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 给合同跟踪查看发货量、结算量时 调用 memo1,1发货量 2结算量
	 * */
	public ResultModel doQueryForContractWeb(CommonPage<SlmLadingBillLine> sum) {
		ResultModel rm = new ResultModel();
		SlmLadingBillLine line = sum.getObject();
		if (line == null)
			line = new SlmLadingBillLine();
		String flag = sum.getMemo1();
		try {
			String param2 = " and h.valid_status >5";
			if ("2".equals(flag))
				param2 = " and h.valid_status >7";
			List<SlmLadingBillLine> list = this.getMapper(	SlmLadingBillLineMapper.class).doQueryForContract(line,	param2);
			rm.setData(list);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败" + ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	// 三种费用新增-结算单 核算
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddFund(SlmLadingBillHeat heat, SlmLadingBillLine lines) throws Exception {
		ResultModel rm = new ResultModel();
		try {
			double carriage_money = 0d; // 运费
			double goods_money = 0d; // 货款
			double other_money = 0d; // 加工配送费
			SlmContractHeatInfo contract_heat = this.getBean(SlmContractHeatInfoServiceImpl.class).doQueryOne(lines.getContract_pk());
			SlmContractLineInfo contract_line = new SlmContractLineInfo();
			contract_line.setContract_no(lines.getContract_no());
			contract_line.setContract_line_seq(lines.getContract_line_seq());
			List<SlmContractLineInfo> lineList = this.getBean(SlmContractLineInfoServiceImpl.class).doQueryWithCondition(contract_line, null, null, 0, 0);
			SlmOrderInfo order = new SlmOrderInfo();
			order.setContract_no(lines.getContract_no());
			order.setContract_line_seq(lines.getContract_line_seq());
			order.setOrder_seq(lines.getOrder_seq());

			
			List<SlmOrderInfo> orderList = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order, " (change_flag is null or change_flag != '1') ", "create_time desc", 0, 0);
			//=====================================================
			if (lineList.size() > 0 && contract_heat != null	&& orderList.size() > 0) {
				contract_line = lineList.get(0);
				order = orderList.get(0);
				
				//20210920 合同签订日期在0926后，取订单的运费
				Double carriage_price = 0d;
				Double other_price = 0d; //加工配送费
				Double goods_price = order.getBalance_price();//货价，结算价
				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)) {
					//20210926之后的逻辑 
					carriage_price = order.getTrade_price();//取订单行的运费
					other_price = order.getProcess_price();//0925之后的订单，直接取订单的【加工费】
				}else {
					//20210926之前的逻辑 
					carriage_price = contract_line.getTrade_price();
					other_price = order.getWork_price();//0925之前的订单，直接取订单的【加工配送费】
				}				 
				 
				
				//现在使用理论重量作为结算重量(毛重) ，实际重量(净重)
				double bill_weight=0d;
				SlmLadingBillDetail detail=new SlmLadingBillDetail();
				detail.setBill_no(lines.getBill_no());
				detail.setLine_no(lines.getLine_no());
				List<SlmLadingBillDetail> detail_list=this.getMapper(SlmLadingBillDetailMapper.class).find(detail, 0, 0);
				for(SlmLadingBillDetail details:detail_list){
					if (details.getFactweight() < 0) {
						continue;//冲减的卷不进行重量判定
					}
					//20200319 根据订单的属性进行重量的计算，不取合同行的计重方式
					if ("102301".equals(order.getWeight_type_no())) {
						bill_weight+=details.getFactweight();
					}else{
						bill_weight+=details.getTheoryweight();
					}
				}
				
				//==================eason add 2019-07-11 增加一个验证==============
				SlmLadingBillLine lineDetail=this.getMapper(SlmLadingBillLineMapper.class).findById(lines.getLine_no());
				if(DoubleUtil.round(lineDetail.getActual_weight().doubleValue(),DoubleUtil.DEF_DIV_SCALE) != DoubleUtil.round(bill_weight,DoubleUtil.DEF_DIV_SCALE)){
					throw new Exception("提单明细"+lineDetail.getLine_no()+"汇总重量与库存反写实绩重量不一致");
				}

				carriage_money = DoubleUtil.round(DoubleUtil.mul(carriage_price == null ? 0: carriage_price, bill_weight),DoubleUtil.SCALE_PRICE);
				goods_money = DoubleUtil.round(DoubleUtil.mul(goods_price,	 bill_weight),DoubleUtil.SCALE_PRICE);
											
				if (CollectionUtils.isEmpty(schiList)) {//20210926之前的逻辑
					if (goods_money == 0){
						carriage_money = 0;					
					}
				}
				
				
				// 运费
				SlmFundSettleCarriage carriage = new SlmFundSettleCarriage();
				carriage.setSettle_carriage_fund(carriage_money);
				carriage.setCarriage_weight(bill_weight);
				carriage.setCarriage_price(carriage_price);
				if (carriage_money == 0)
					carriage.setCarriage_price(0d);
				carriage.setCustomer_no(contract_heat.getCustomer_no());
				carriage.setCustomer_name(contract_heat.getCustomer_name());
				carriage.setBalance_unit_no(contract_heat.getBalance_unit_no());
				carriage.setBalance_unit_name(contract_heat.getBalance_unit_name());
				carriage.setSolutions_no(heat.getSolutions_no());
				carriage.setSolutions_name(heat.getSolutions_name());
				carriage.setTrans_unit_no(heat.getTrans_unit_no());
				carriage.setTrans_unit_name(heat.getTrans_unit_name());
				carriage.setOrder_no(lines.getOrder_no());
				carriage.setOrder_seq(lines.getOrder_seq());
				carriage.setContract_pk(lines.getContract_pk());
				carriage.setContract_no(lines.getContract_no());
				carriage.setContract_line_no(lines.getContract_line_no());
				carriage.setContract_line_seq(lines.getContract_line_seq());
				carriage.setBill_no(lines.getBill_no());
				carriage.setLine_no(lines.getLine_no());
				rm = this.getBean(SlmFundSettleCarriageServiceImpl.class).doAdd(carriage);
				if ("500".equals(rm.getState()))
					throw new Exception(rm.getMsgInfo());
				
				// 货款
				SlmFundSettleGood good = new SlmFundSettleGood();
				good.setCustomer_no(contract_heat.getCustomer_no());
				good.setCustomer_name(contract_heat.getCustomer_name());
				good.setBalance_unit_no(contract_heat.getBalance_unit_no());
				good.setBalance_unit_name(contract_heat.getBalance_unit_name());
				good.setOrder_no(lines.getOrder_no());
				good.setOrder_seq(lines.getOrder_seq());
				good.setContract_pk(lines.getContract_pk());
				good.setContract_no(lines.getContract_no());
				good.setContract_line_no(lines.getContract_line_no());
				good.setContract_line_seq(lines.getContract_line_seq());
				good.setBill_no(lines.getBill_no());
				good.setLine_no(lines.getLine_no());
				good.setBalance_quantity(lines.getBill_quantity());
				good.setBalance_weight(bill_weight);
				good.setBalance_price(DoubleUtil.add(order.getBalance_price(),order.getWork_price()));
				good.setBalance_good_price(order.getBalance_price());
				good.setBalance_work_price(order.getWork_price());
				good.setPrice_type_no(order.getPrice_type_no());
				good.setPrice_type_name(order.getPrice_type_name());
				good.setIs_tax(order.getIs_tax());
				good.setBalance_amount(goods_money);
				good.setMeasure_no(contract_line.getMeasure_no());
				rm = this.getBean(SlmFundSettleGoodServiceImpl.class).doAdd(
						good);
				if ("500".equals(rm.getState()))
					throw new Exception(rm.getMsgInfo());
				
				// 加工配送费
				SlmFundSettleOther other = new SlmFundSettleOther();
				
				other.setOther_weight(bill_weight);
				
				if (CollectionUtils.isNotEmpty(schiList)) {
					//20210926之后的逻辑 
					other.setOther_price(order.getProcess_price());//加工费
					other.setTrade_price(0d);//运费
					other.setProcess_price(order.getProcess_price());//加工费
					other_money = DoubleUtil.round(DoubleUtil.mul(other_price,	 bill_weight),DoubleUtil.SCALE_PRICE);
					other.setSettle_other_fund(other_money);
				}else {
					//20210926之前的逻辑 
					other.setOther_price(order.getWork_price());
					other.setTrade_price(order.getTrade_price()==null?0d:order.getTrade_price());//运费
					other.setProcess_price(order.getProcess_price()==null?0d:order.getProcess_price());//加工费
					other_money = DoubleUtil.round(DoubleUtil.mul(other_price,	 bill_weight),DoubleUtil.SCALE_PRICE);
					other.setSettle_other_fund(other_money);
				}
								
				other.setCustomer_no(contract_heat.getCustomer_no());
				other.setCustomer_name(contract_heat.getCustomer_name());
				other.setBalance_unit_no(contract_heat.getBalance_unit_no());
				other.setBalance_unit_name(contract_heat.getBalance_unit_name());
				other.setOrder_no(lines.getOrder_no());
				other.setOrder_seq(lines.getOrder_seq());
				other.setContract_pk(lines.getContract_pk());
				other.setContract_no(lines.getContract_no());
				other.setContract_line_no(lines.getContract_line_no());
				other.setContract_line_seq(lines.getContract_line_seq());
				other.setBill_no(lines.getBill_no());
				other.setLine_no(lines.getLine_no());
				rm = this.getBean(SlmFundSettleOtherServiceImpl.class).doAdd(other);
				if ("500".equals(rm.getState()))
					throw new Exception(rm.getMsgInfo());
			}
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			e.printStackTrace();
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	private String doAddDetail(SlmLadingBillLine line) {
		String msg=null;
		try{
			for (YdmProductDetail details : line.getDetailList()) {
				// 在提单新增的时候检测该卷是否已经编进了转库出厂证的小票里：2023013101刘侣
				// details.getCoilno()
				String condition = "COILLIST like '%"+ details.getCoilno() + "%' and nvl(IS_MOVE, 0) != '1'";
				List<PassportInfo> piList = this.getMapper(LmsPassportinfoMapper.class).findWithCondition(null, condition, "TICKET desc", 0, 1);
				if (piList.size() > 0) {
					// 说明该卷已经被编进了小票中，抛出：
					throw new Exception("卷号：" + details.getCoilno() + " 已经被编入小票且等待移送至贸易外库，请联系发运。");
				}
				// end
				
				// 对比订单号是否一致：20230413 刘侣
				YdmProductDetail ypdConNo = this.getMapper(YdmProductDetailMapper.class).doFind(details.getCoilno(), null);
				if (!line.getOrder_no().equals(ypdConNo.getOrderno())) {
					throw new Exception("卷号：" + details.getCoilno() + " 的订单号：" + ypdConNo.getOrderno() + " 和传入的订单号不一致，请联系管理员");
				}
				// end
				
				SlmLadingBillDetail detail = new SlmLadingBillDetail();
				detail.setLine_no(line.getLine_no());
				detail.setBill_no(line.getBill_no());
				detail.setOrder_no(line.getOrder_no());
				detail.setOrder_seq(line.getOrder_seq());
				detail.setContract_no(line.getContract_no());
				detail.setContract_pk(line.getContract_pk());
				detail.setContract_line_no(line.getContract_line_no());
				detail.setContract_line_seq(line.getContract_line_seq());
				detail.setCustomer_no(details.getCustomer_no());
				detail.setCustomer_name(details.getCustomer_nm());
				detail.setReciver_unit_no(details.getReceiv_no());
				detail.setReciver_unit_name(details.getReceiv_nm());
				detail.setCoilno(details.getCoilno());
				detail.setBoxno(details.getBoxno());
				detail.setStd_code(details.getStd_code());
				detail.setStd_name(details.getStd_name());
				// 保持和订单牌号一致，所以使用steelcode：20230202刘侣
//				detail.setJudgesteelcode(details.getJudgesteelcode());
				detail.setJudgesteelcode(details.getSteelcode());
				// end
				detail.setProd_code(details.getProd_code());
				detail.setProd_name(details.getProd_name());
				detail.setThick(details.getThick());
				detail.setWidth(details.getWidth());
				detail.setLen(details.getLength());
				detail.setBlock_num(details.getQuantity());
				detail.setFactweight(details.getFactweight());
				detail.setTheoryweight(details.getTheoryweight());
				detail.setMaterailcoilno(details.getMaterailcoilno());
				// 提单明细表增加：转库费单价，资金占用费单价；20230218刘侣
				detail.setZkf_u_price(details.getKfts() == null ? 0d : Integer.parseInt(details.getKfts()) > 10 ? 30.00 : 0d);
				detail.setZj_u_price(details.getKfts() == null ? 0d : Integer.parseInt(details.getKfts()) > 30 ? 90.00 : 
					Integer.parseInt(details.getKfts()) > 20 ? 60.00 : Integer.parseInt(details.getKfts()) > 10 ? 30.00 : 0d);
				// 计算额外的加价的总额：
				detail.setExtra_money(getExtraMoney(detail));
				// end
				msg=this.getBean(SlmLadingBillDetailServiceImpl.class).doAdd(detail);
				if(msg!=null) throw new Exception(msg);
				CommonPage<YdmProductDetail> cp = new CommonPage<YdmProductDetail>();
				details.setBill_no(line.getBill_no());
				details.setLine_no(line.getLine_no());
				cp.setObject(details);
				ResultModel lms_rm=this.getBean(LmsApiServiceImpl.class).doShippingLock(cp);
				if("500".equals(lms_rm.getState())){
					throw new Exception(lms_rm.getMsgInfo());
				}
			}
		}catch(Exception e){
			msg=e.getMessage();
		}
		return msg;
	}
	
	double getExtraMoney (SlmLadingBillDetail sd) throws Exception {
		//查询该合同的付款节点信息
		SlmContractPayment param_payment=new SlmContractPayment();
		param_payment.setContract_pk(sd.getContract_pk());
		param_payment.setPayment_point_no("102703");
		param_payment.setCustomer_no(sd.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){
			throw new Exception("未找到 "+ sd.getContract_no() +" 的付款节点信息。"); 
		}
		SlmContractPayment payment=payment_list.get(0);
		double rate=0.01;
		if("102902".equals(payment.getUnit_no())){
			rate=0.001;
		}
		return DoubleUtil.round((sd.getZkf_u_price()+sd.getZj_u_price())*sd.getFactweight()*payment.getRatio_value()*rate,DoubleUtil.SCALE_PRICE);
	}

	public List<SlmLadingBillLine> doQuery(SlmLadingBillLine line) {
		return this.getMapper(SlmLadingBillLineMapper.class).find(line, 0, 0);
	}

	public void doUpdate(SlmLadingBillLine line) {
		this.getMapper(SlmLadingBillLineMapper.class).update(line);
	}

	public SlmLadingBillLine doQueryOne(String line_no) {
		return this.getMapper(SlmLadingBillLineMapper.class).findById(line_no);
	}
}
