/***文档注释***********************************************
 * 作者               :                   易鑫
 * 创建日期      :                   2017.11.27
 * 描述               :                   Slm提供其他系统调用的公共接口
 * 注意事项      :                   无
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
 ***********************************************************/

package market.Api.Slm.impl;

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

import market.Api.Slm.service.SlmApiService;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderMapper;
import market.Mes.OrderManager.Plan.vo.PlnProdorder;
import market.Slm.ContractManagement.impl.SlmCustAlphaServiceImpl;
import market.Slm.ContractManagement.mapper.SlmContractBaseStationMapper;
import market.Slm.ContractManagement.mapper.SlmContractLineInfoMapper;
import market.Slm.ContractManagement.vo.SlmContractBaseStation;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.ContractManagement.vo.SlmCustAlpha;
import market.Slm.DeliveryManagement.impl.SlmLadingBillLineServiceImpl;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillLineMapper;
import market.Slm.DeliveryManagement.vo.SlmLadingBillLine;
import market.Slm.OrderManagement.mapper.SlmContractProcessPlanMapper;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.mapper.SlmProcessPlanMapper;
import market.Slm.OrderManagement.vo.SlmContractProcessPlan;
import market.Slm.OrderManagement.vo.SlmOrderInfo;
import market.Slm.OrderManagement.vo.SlmProcessPlan;

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="SlmApiService")
public class SlmApiServiceImpl extends BaseServiceImpl implements SlmApiService {
	/**
	 * 给质量的接口-根据订单号查询订单备注
	 * @throws Exception 
	 */
	public String getOrderMemo(String order_no) throws Exception{
		SlmOrderInfo order=this.getMapper(SlmOrderInfoMapper.class).findById(order_no);
		if(order==null){
			throw new Exception("未查询到订单号为【"+order_no+"】的订单");
		}
		return order.getMemo();
	}
	/**
	 * 计划管理--订单接收--查询订单信息
	 * 需传状态
	 * */
	public ResultModel doOrderQueryWeb(CommonPage<SlmOrderInfo> sum){
		ResultModel rm=new ResultModel();
		SlmOrderInfo order=sum.getObject();
		try{
			String sWhere=" 1=1 ";
			//假如为1则为下发产生时间  为2交货时间
			if("1".equals(sum.getMemo1())){
				sWhere+=" and issuer_time between to_date('"+sum.getStartTime()+"','yyyy-MM-dd HH24:mi:ss') and to_date('"+sum.getEndTime()+"','yyyy-MM-dd HH24:mi:ss') ";
			}else if("2".equals(sum.getMemo1())){
				sWhere+=" and deliver_date between to_date('"+sum.getStartTime()+"','yyyy-MM-dd') and to_date('"+sum.getEndTime()+"','yyyy-MM-dd') ";
			}
			List<SlmOrderInfo> list=this.getMapper(SlmOrderInfoMapper.class).doOrderQueryWeb(order, sWhere);

			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
		}
		return rm;
	}

	/**
	 * 订单接收 ，查询列表
	 * 下发时间startTime,endTime
	 * 交货时间memo1，memo2
	 * memo3 默认全部  1原料卷   2 需加工   3非计划(应客户需求增加查询条件)
	 * */
	public ResultModel doQueryOrderReceiveWeb(CommonPage<PlnProdorder> sum){
		ResultModel rm=new ResultModel();
		PlnProdorder order=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		//下发时间段
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		//交货时间段
		String de_startTime=sum.getMemo1();
		String de_endTime=sum.getMemo2();
		try{
			PageModel<PlnProdorder> pm=new PageModel<PlnProdorder>(pageIndex, pageSize);
			List<PlnProdorder> list=this.getMapper(PlnProdorderMapper.class).doQueryOrderReceive(order,startTime,endTime,de_startTime,de_endTime,(pageIndex-1)*pageSize,pageIndex*pageSize,sum.getMemo3());
			int count=this.getMapper(PlnProdorderMapper.class).doQueryOrderReceiveCount(order,startTime,endTime,de_startTime,de_endTime,sum.getMemo3());
//			for(PlnProdorder orders:list){
//				//横切方式
//				SlmProcessPlan plan=new SlmProcessPlan();
//				plan.setContract_line_no(orders.getContract_line_no());
//				plan.setContract_line_seq(orders.getContract_line_seq());
//				plan.setOrder_seq(orders.getOrder_seq());
//				plan.setValid_flag("1");
//				List<SlmProcessPlan> planList=this.getMapper(SlmProcessPlanMapper.class).findWithCondition(plan, "", " cut_order_no", 0, 0);
//				if(planList.size()>0){
//					String type="不横切";
//					if("2".equals(planList.get(0).getCrosscut_stype()))
//						type="一切二";
//					if("3".equals(planList.get(0).getCrosscut_stype()))
//						type="一切三";
//					orders.setCrosscut_stype(type);
//					//关联加工计划信息表SLM_PROCESS_PLAN查询加工计划备注
//					orders.setProcessMemo(planList.get(0).getMemo());
//				}
//				
//				String spec="";
//				for(SlmProcessPlan plans:planList){
//					spec+=plans.getWidth()+"*"+plans.getCut_num()+"+";
//				}
//				if(!"".equals(spec))
//					spec=spec.substring(0,spec.length()-1);
//				orders.setCut_style(spec);
//				
//				//2018.01.31 要求新增部分字段
//				SlmContractHeatInfo heat=new SlmContractHeatInfo();
//				heat.setContract_no(orders.getContract_no());
//				List<SlmContractHeatInfo> heatList=this.getMapper(SlmContractHeatInfoMapper.class).find(heat, 0, 0);
//				if(heatList.size()>0){
//					orders.setCustomer_no(heatList.get(0).getCustomer_no());
//					orders.setCustomer_name(heatList.get(0).getCustomer_name());
//				}
//				
//				
//				double s=this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getEstimate_weight(), orders.getEstimate_weight_unit_no(), "100305");
//				orders.setEstimate_weight(s);//单位转换为kg
//				orders.setEstimate_weight_unit_no("100305");
//				orders.setEstimate_weight_unit_name("kg");
//				orders.setDelivery_error_max(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getDelivery_error_max(), orders.getDelivery_unit_no(), "100305"));//单位转换为kg
//				orders.setDelivery_error_min(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getDelivery_error_min(), orders.getDelivery_unit_no(), "100305"));//单位转换为kg
//				orders.setDelivery_unit_no("100305");
//				orders.setDelivery_unit_name("kg");
//				orders.setSingle_weight(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getSingle_weight(), orders.getSingle_weight_unit_no(), "100305"));//单位转换为kg
//				orders.setSingle_weight_max(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getSingle_weight_max(), orders.getSingle_weight_unit_no(), "100305"));//单位转换为kg
//				orders.setSingle_weight_min(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getSingle_weight_min(), orders.getSingle_weight_unit_no(), "100305"));//单位转换为kg
//				orders.setSingle_weight_unit_no("100305");
//				orders.setSingle_weight_unit_name("kg");
//				//长度转换 mm
//				orders.setThick(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getThick(), orders.getThick_unit_no(), "100304"));//单位转换为mm
//				orders.setThick_max(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getThick_max(), orders.getThick_unit_no(), "100304"));//单位转换为mm
//				orders.setThick_min(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getThick_min(), orders.getThick_unit_no(), "100304"));//单位转换为mm
//				orders.setThick_unit_no("100304");
//				orders.setThick_unit_name("mm");
//				orders.setWidth(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getWidth(), orders.getWidth_unit_no(), "100304"));//单位转换为mm
//				orders.setWidth_max(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getWidth_max(), orders.getWidth_unit_no(), "100304"));//单位转换为mm
//				orders.setWidth_min(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getWidth_min(), orders.getWidth_unit_no(), "100304"));//单位转换为mm
//				orders.setWidth_unit_no("100304");
//				orders.setWidth_unit_name("mm");
//				orders.setLength(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getLength(), orders.getLength_unit_no(), "100304"));//单位转换为mm
//				orders.setLength_max(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getLength_max(), orders.getLength_unit_no(), "100304"));//单位转换为mm
//				orders.setLength_min(this.getBean(SlmBaseUnitConversionServiceImpl.class).doUnitConversion(orders.getLength_min(), orders.getLength_unit_no(), "100304"));//单位转换为mm
//				orders.setLength_unit_no("100304");
//				orders.setLength_unit_name("mm");
//			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
		}
		return rm;
	}

	/**
	 * 提单装车
	 * */
	public ResultModel doLadingWeb(CommonPage<SlmLadingBillLine> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillLine line=sum.getObject();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			SlmLadingBillLine newLine=this.getBean(SlmLadingBillLineServiceImpl.class).doQueryOne(line.getLine_no());
			newLine.setActual_quantity(line.getActual_quantity()==null?0:line.getActual_quantity()+(newLine.getActual_quantity()==null?0:newLine.getActual_quantity()));
			newLine.setActual_weight(line.getActual_weight()==null?0:line.getActual_weight()+(newLine.getActual_weight()==null?0:newLine.getActual_weight()));
			newLine.setVirtual_quantity(line.getVirtual_quantity()==null?0:line.getVirtual_quantity()+(newLine.getVirtual_quantity()==null?0:newLine.getVirtual_quantity()));
			newLine.setVirtual_weight(line.getVirtual_weight()==null?0:line.getVirtual_weight()+(newLine.getVirtual_weight()==null?0:newLine.getVirtual_weight()));
			line.setUpdate_man_no(userId);
			line.setUpdate_man_name(userName);
			line.setUpdate_time(new Date());
			this.getMapper(SlmLadingBillLineMapper.class).update(line);
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("操作失败"+e.getMessage());
		}
		return rm;
	}

	/**
	 * for 质量模块 ，反写加工计划中的评审状态，MSC
	 * 合同号/合同行序号/订单序号/具体规格记录序号(分切序号) 
	 * */
	public ResultModel doQueryProcessPlanWeb(CommonPage<SlmContractProcessPlan> sum){
		ResultModel rm=new ResultModel();
		SlmContractProcessPlan plan=sum.getObject();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmContractProcessPlan> pm=new PageModel<SlmContractProcessPlan>(pageIndex, pageSize);
		try{
			if(plan!=null){
				//看需要什么查询条件
				if(plan.getContract_manage_no()!=null&&!"".equals(plan.getContract_manage_no())){		//合同管理号
					String[] manageNo=plan.getContract_manage_no().split("/");
					if(manageNo.length==1){		//合同号/合同行序号/订单序号
						plan.setContract_no(manageNo[0]);
					}else if(manageNo.length==2){
						plan.setContract_no(manageNo[0]);
						plan.setContract_line_seq(manageNo[1]);
					}else if(manageNo.length==3){
						plan.setContract_no(manageNo[0]);
						plan.setContract_line_seq(manageNo[1]);
						plan.setOrder_seq(manageNo[2]);
					}
				}
			}

			List<SlmContractProcessPlan> list=this.getMapper(SlmContractProcessPlanMapper.class).doQueryProcessPlan(plan,startTime,endTime,(pageIndex-1)*pageSize,pageSize*pageIndex);
			long count=this.getMapper(SlmContractProcessPlanMapper.class).doQueryProcessPlanCount(plan,startTime,endTime);
			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;
	}
	/**
	 * 给质量的接口-验证customer_alpha_no在订单表中是否存在关联的记录 嘿嘿。。试一下。。
	 */
	public List<String> doJudgeCustomerAlphaNo(String customer_alpha_no) {

		List<String> 合同号合同行号的拼接字符串 = new ArrayList<>();
		SlmContractLineInfo t = new SlmContractLineInfo();
		t.setCustomer_alpha_no(customer_alpha_no);
		List<SlmContractLineInfo> line = this.getMapper(SlmContractLineInfoMapper.class).find(t, 0, 0);
		if (line != null && line.size() > 0) {
			for (SlmContractLineInfo lines : line) {
				合同号合同行号的拼接字符串.add(lines.getContract_no() + "/" + lines.getContract_line_seq());
			}
		}
		return 合同号合同行号的拼接字符串;

	}
	/**
	 * 通过合同行号更新 技术要求 contract_line_no customer_alpha_no
	 * 
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel updateCustomerAlphaNoByContractLineNo(CommonPage<SlmContractLineInfo> 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);
		try {
			// 更新编码
			SlmContractLineInfo line = sum.getObject();
			line.setUpdate_time(new Date());
			line.setUpdate_man_no(userId);
			line.setUpdate_man_name(userName);
			this.getMapper(SlmContractLineInfoMapper.class).update(line);
			// 更新描述
			CommonPage<SlmCustAlpha> cm = new CommonPage<>();
			SlmCustAlpha alpha = new SlmCustAlpha();
			alpha.setCust_alpha_no(line.getCustomer_alpha_no());
			cm.setObject(alpha);
			cm.setMemo1(line.getContract_line_no());
			this.getBean(SlmCustAlphaServiceImpl.class).doSelectWeb(cm);

			rm.setMsgInfo("更新成功！");
			rm.setState("200");
		} catch (Exception e) {
			throw new Exception("更新失败！" + e.getMessage());
		}
		return rm;
	}

	/**
	 * 根据加工计划获取工艺要求关联的工序点集合接口
	 * @throws Exception 
	 * */
	public List<SlmContractBaseStation> getSlmContractBaseStationByContractLineNo(String plan_no) throws Exception {
		 List<SlmContractBaseStation> list=new ArrayList<SlmContractBaseStation>();
		try {
			SlmProcessPlan plan=this.getMapper(SlmProcessPlanMapper.class).findById(plan_no);
			if(plan==null){
				throw new Exception("未查询到对应的加工计划，请检查参数");
			}
			SlmOrderInfo order=new SlmOrderInfo();
			order.setContract_no(plan.getContract_no());
			order.setContract_line_seq(plan.getContract_line_seq());
			order.setOrder_seq(plan.getOrder_seq());
			List<SlmOrderInfo> order_list=this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order," valid_flag='1' and (change_flag is null or change_flag!='1')" ,null,0, 0);
			if(order_list.size()>0){
				order=order_list.get(0);
				list=this.getMapper(SlmContractBaseStationMapper.class).findWithCondition(null, " order_no='"+order.getOrder_no()+"'", " rnum,seq", 0, 0);
				if(list.size()<1){
					SlmContractBaseStation station=new SlmContractBaseStation();
					station.setContract_no(order.getContract_no());
					station.setContract_line_seq(order.getContract_line_seq());
					station.setOrder_seq(order.getOrder_seq());
					station.setOrder_no(order.getOrder_no());
					list=this.getMapper(SlmContractBaseStationMapper.class).find(station,  0, 0);
				}
			}
		} catch (Exception e) {
			throw new Exception("查询失败！" + e.getMessage());
		}
		return list;
	}
}
