package market.Lms.Warehouse.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javassist.bytecode.SignatureAttribute.ObjectType;
import market.Api.Qms.impl.QmsApiServiceImpl;
import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseSteelMapper;
import market.Com.vo.ComBaseCbYdd;
import market.Com.vo.ComBaseChem;
import market.Com.vo.ComBaseSteel;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.IfRawMtrCoilMMapper;
import market.Lms.Warehouse.mapper.IfRawMtrCoilPfmcMapper;
import market.Lms.Warehouse.mapper.YdmProductButtresslistMapper;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.mapper.YdmProductInlistMapper;
import market.Lms.Warehouse.service.IfRawMtrCoilPfmcService;
import market.Lms.Warehouse.service.YdmProductInlistService;
import market.Lms.Warehouse.vo.ComPageIfRawMtrCoilPfmc;
import market.Lms.Warehouse.vo.IfRawMtrCoilM;
import market.Lms.Warehouse.vo.IfRawMtrCoilPfmc;
import market.Lms.Warehouse.vo.YdmProductButtresslist;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Lms.Warehouse.vo.YdmProductInlist;
import market.Qms.qcm.vo.QcmJhyElements;
import market.Qms.qcm.vo.QcmJhyPhyresult;
import market.Slm.FundManagement.service.SlmFundFirstDetailService;

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;

@SuppressWarnings("rawtypes")
@RemoteService(path="IfRawMtrCoilPfmcService")
public class IfRawMtrCoilPfmcServiceImpl extends BaseServiceImpl<IfRawMtrCoilPfmc, String> implements IfRawMtrCoilPfmcService {

	/**
	 * 生成主键
	 * @return
	 * @throws Exception 
	 */
	public String createXGPhySID() throws Exception
	{
		try 
		{
			String physid="";
			List<HashMap> list = this.getMapper(IfRawMtrCoilPfmcMapper.class).getNo("PHXG"+(new SimpleDateFormat("yyyyMMdd").format(new Date())));
			physid = (String) list.get(0).get("MAXNO");
			return physid;
		} 
		catch (Exception ex) 
		{
			throw (ex);
		}
	}
	/**
	 * 生成主键
	 * @return
	 * @throws Exception 
	 */
	public String createWGPhySID() throws Exception
	{
		try 
		{
			String physid="";
			List<HashMap> list = this.getMapper(IfRawMtrCoilPfmcMapper.class).getNo("PHWG"+(new SimpleDateFormat("yyyyMMdd").format(new Date())));
			physid = (String) list.get(0).get("MAXNO");
			return physid;
		} 
		catch (Exception ex) 
		{
			throw (ex);
		}
	}
	
	/**
	 * 外购入库管理 材质结果ID编辑
	 * */
	public ResultModel doEditPhySID(CommonPage<IfRawMtrCoilPfmc> cp)
	{
		ResultModel rm=new ResultModel();
		try {
			IfRawMtrCoilPfmc pfmc=cp.getObject();
			if(pfmc.getPhysid()!=null&&pfmc.getPhysid()!="") {
				//若流水号为空生成
				if("PHWG".equals(pfmc.getPhysid())) {
					rm.setState("200");
					rm.setData(this.createWGPhySID());
				}
				else {
					//若不为空，判断是否存在
					List<IfRawMtrCoilPfmc> list=this.getMapper(IfRawMtrCoilPfmcMapper.class).find(pfmc, 0, 0);
					//存在返回材质项数据
					if(list!=null&&list.size()>0){
						rm.setState("600");
						rm.setData(list);
					}
					//不存在，生成
					else {
						rm.setState("200");
						rm.setData(this.createWGPhySID());
					}
				}
			}
		}
		catch(Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，材质结果ID编辑失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 外购入库管理-入库确认
	 * @param rw
	 * @return
	 */
	//@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doConfirmOuts(ComPageIfRawMtrCoilPfmc<ObjectType> cp) throws Exception {
		Date now = new Date();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String username=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String order=(String)this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String team=(String)this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);

		ResultModel rm =new ResultModel();
		if (cp.getObject()==null) {
			throw new Exception("请传入外购入库信息!");
		}
		YdmProductDetail ypd=cp.getObject();
		//判断原料卷是否存在
		YdmProductDetail ydA = new YdmProductDetail();		
		ydA.setMaterailcoilno(ypd.getMaterailcoilno());			
		List<YdmProductDetail> ydmlist =this.getMapper(YdmProductDetailMapper.class).find(ydA, 0, 0);	
		if(ydmlist!=null && ydmlist.size()>0){
			rm.setState("500");
			rm.setMsgInfo("存在相同原料卷号，请检查数据!");
			throw new Exception("存在相同原料卷号，请检查数据!");
		}									
		String id =this.createCoilNo();
		ypd.setCoilno(id);				
		//插入库存信息
		ypd.setCreater(username);
		if (ypd.getCreatedate()==null||"".equals(ypd.getCreatedate())) {
			ypd.setCreatedate(new Date());
		}								
		if (ypd.getInorder()==null||"".equals(ypd.getInorder())) {
			ypd.setInorder(order);
		}				
		if (ypd.getInteam()==null||"".equals(ypd.getInteam())) {
			ypd.setInteam(team);
		}
		if(ypd.getIndate()==null||"".equals(ypd.getIndate())){
			ypd.setIndate(new Date());
		}
		ypd.setCoiltype("0");
		ypd.setSource("1");
		ypd.setState("0");
		ypd.setJudgeresult("40740801");//默认外购入库的综判合格								
		ypd.setQuantity(0);
		if (ypd.getAllot_no()==null||"".equals(ypd.getAllot_no())) {
			ypd.setAllot_no("0");
		}	
		if (ypd.getMaterailtype()==null||"".equals(ypd.getMaterailtype())) {
			ypd.setMaterailtype("0");
		}		
		if (ypd.getTheoryweight()==null||"".equals(ypd.getTheoryweight())) {
			ypd.setTheoryweight(0.0);
		}
		if (ypd.getIndate()==null||"".equals(ypd.getIndate())) {
			ypd.setIndate(new Date());
		}		
		if (ypd.getFactweight()==null||"".equals(ypd.getFactweight())) {
			ypd.setFactweight(0.0);
		}
		if (ypd.getMemo()==null||"".equals(ypd.getMemo())) {
			ypd.setMemo("无");
		}			
		ypd.setSteelcode(ypd.getJudgesteelcode());
		if(cp.getMemo1()!=null&&cp.getMemo1()!=""){
			ypd.setPhysid(cp.getMemo1());					
		}
		if(cp.getMemo2()!=null&&cp.getMemo2()!=""){
			ypd.setChemid(cp.getMemo2());					
		}
		this.getMapper(YdmProductDetailMapper.class).doInsert(ypd);
		//插入原料主实绩
		IfRawMtrCoilM m=new IfRawMtrCoilM();
		m.setPhysid(cp.getMemo1());
		m.setChemid(cp.getMemo2());
		m.setCreateOpr(username);
		m.setCreateTime(new Date());
		m.setStatus("1");
		m.setCoilNo(ypd.getCoilno());
		m.setCoilSource(ypd.getSource());
		if (ypd.getMaterailtype()==null||ypd.getMaterailtype().equals("")) {
			m.setCoilSort("1");
		}else {
			m.setCoilSort(ypd.getMaterailtype());
		}
		//m.setSupplierCode(cp.getMemo3());
		m.setSupplierName(ypd.getMaterailsupplier());
		m.setHeatno(ypd.getHeatno());
		m.setPrdCode(ypd.getProd_code());
		m.setPrdName(ypd.getProd_name());
		m.setStdCode(ypd.getStd_code());
		m.setStdName(ypd.getStd_name());
		m.setSteelCode(ypd.getJudgesteelcode());
		m.setRemark(ypd.getMemo());
		m.setCoilThk(ypd.getThick());
		m.setCoilWdt(ypd.getWidth());
		m.setCoilLen(ypd.getLength());
		m.setCoilInnDia(ypd.getDiameter_inn());
		m.setCoilOutDia(ypd.getDiameter_out());
		m.setCoilThrWgt(ypd.getTheoryweight());
		m.setCoilActWgt(ypd.getFactweight());								
		this.getMapper(IfRawMtrCoilMMapper.class).delete(ypd.getCoilno());				
		this.getMapper(IfRawMtrCoilMMapper.class).insert(m);
		//插入入库信息
		YdmProductInlist ypi=new YdmProductInlist();
		ypi.setCreater(username);
		ypi.setCreatedate(new Date());
		ypi.setIntype("500406");
		ypi.setIndate(ypd.getIndate());
		ypi.setInorder(ypd.getInorder());
		ypi.setInteam(ypd.getInteam());				
		if (ypi.getInorder()==null||"".equals(ypi.getInorder())) {
			ypi.setInorder(order);
		}				
		if (ypi.getInteam()==null||"".equals(ypi.getInteam())) {
			ypi.setInteam(team);
		}				
		//ypi.setInteam(team);
		ypi.setInorder(ypd.getInorder());
		ypi.setInteam(ypd.getInteam());
		ypi.setInbillno(this.getBean(YdmProductInlistServiceImpl.class).createINBILLNO());
		ypi.setCoilno(ypd.getCoilno());
		ypi.setCoiltype(ypd.getCoiltype());
		ypi.setMaterailtype(ypd.getMaterailtype());
		ypi.setSource(ypd.getSource());
		ypi.setMaterailsupplier(ypd.getMaterailsupplier());
		ypi.setIsbox(ypd.getIsbox());
		ypi.setBoxno(ypd.getBoxno());
		ypi.setDrawingno(ypd.getDrawingno());
		ypi.setBatchno(ypd.getBatchno());
		ypi.setHeatno(ypd.getBatchno());
		ypi.setSmpno(ypd.getSmpno());
		ypi.setManagementno(ypd.getManagementno());
		ypi.setStorageattr(ypd.getStorageattr());
		ypi.setProd_code(ypd.getProd_code());
		ypi.setProd_name(ypd.getProd_name());
		ypi.setStd_code(ypd.getStd_code());			
		ypi.setStd_name(ypd.getStd_name());
		ypi.setUse_code(ypd.getUse_code());
		ypi.setUse_name(ypd.getUse_name());
		ypi.setPline_name(ypd.getPline_name());
		ypi.setPostid(ypd.getPostid());
		ypi.setThick(ypd.getThick());
		ypi.setWidth(ypd.getWidth());
		ypi.setLength(ypd.getLength());
		ypi.setDiameter_inn(ypd.getDiameter_inn());
		ypi.setDiameter_out(ypd.getDiameter_out());
		ypi.setQuantity(ypd.getQuantity());
		ypi.setTheoryweight(ypd.getTheoryweight());
		ypi.setCoreweight(ypd.getCoreweight());
		ypi.setGrossweight(ypd.getGrossweight());
		ypi.setPackweight(ypd.getPackweight());
		ypi.setFactweight(ypd.getFactweight());
		ypi.setCustomer_nm(ypd.getCustomer_nm());
		ypi.setCustomer_no(ypd.getCustomer_no());
		ypi.setReceiv_no(ypd.getReceiv_no());
		ypi.setReceiv_nm(ypd.getReceiv_nm());
		ypi.setOrderno(ypd.getOrderno());
		ypi.setProdorderno(ypd.getProdorderno());
		ypi.setSteelcode(ypd.getSteelcode());
		ypi.setJudgesteelcode(ypd.getJudgesteelcode());
		ypi.setPacking_group(ypd.getPacking_group());
		ypi.setChemresult(ypd.getChemresult());
		ypi.setSizeresult(ypd.getSizeresult());
		ypi.setSurfaceresult(ypd.getSurfaceresult());
		ypi.setWeightresult(ypd.getWeightresult());
		ypi.setJudgeresult(ypd.getJudgeresult());
		ypi.setPhysresult(ypd.getPhysresult());
		ypi.setSpyresult(ypd.getSpyresult());
		ypi.setProducedate(ypd.getProducedate());
		ypi.setProduceorder(ypd.getProduceorder());
		ypi.setProduceteam(ypd.getProduceteam());
		ypi.setOperator(username);
		if (ypd.getLocality()==null||"".equals(ypd.getLocality())) {
			ypi.setLocality("1");
		}
		else{
			ypi.setLocality(ypd.getLocality());
		}
		if(ypd.getLocality()!=null&&ypd.getLocality()!=""){
			ypi.setPosition(ypd.getLocality());
		}				
		ypi.setMemo(ypd.getMemo());
		ypi.setButtressno(ypd.getButtressno());
		ypi.setStorageattr(ypd.getStorageattr());
		
		// 加入物料属性：20230725刘侣
		ypi.setObj_attr_in(ypd.getObject_attr());
		// end
		
		this.getMapper(YdmProductInlistMapper.class).insert(ypi);
		//插入垛位信息
		YdmProductButtresslist ypb=new YdmProductButtresslist();
		ypb.setCreater(username);
		ypb.setCreatedate(new Date());
		ypb.setLayer(1);
		if(ypd.getLocality()!=null&&ypd.getLocality()!=""){
			ypb.setLocality(Integer.valueOf(ypd.getLocality()).intValue());
		}				
		ypb.setButtressno(ypd.getButtressno());
		ypb.setStorageattr(ypd.getStorageattr());
		ypb.setAreano(ypd.getAreano());
		ypb.setCoilno(ypd.getCoilno());
		ypb.setBoxno(ypd.getBoxno());
		this.getMapper(YdmProductButtresslistMapper.class).doInsert(ypb);
			
		//调用质量材质结果接口
		List<QcmJhyPhyresult> plist = cp.getObjectList();
		if (plist!=null && plist.size() > 0 && cp.getMemo1()!=null && !"".equals(cp.getMemo1())) {
			for (QcmJhyPhyresult jp : plist) {
				jp.setSpecimen_no(cp.getMemo1());//材质ID
				//jp.setPhy_code_l(phy_code_l);//检验大项
				//jp.setPhy_name_l(phy_name_l);
				//jp.setPhy_code_m(phy_code_m);//试样组代码
				//jp.setPhy_name_m(phy_name_m);
				//jp.setPhy_code_s(phy_code_s);//检验项代码
				//jp.setPhy_name_s(phy_name_s);
				//jp.setVal1(val1);//值1
			}		  
			ResultModel r = this.getBean(QmsApiServiceImpl.class).insertJhyPhy(plist);
			if (r.getMsgInfo()!=null) {
				throw new Exception(r.getMsgInfo());
			}
		}
		
		//调用质量成分接口
		List<QcmJhyElements> elist = cp.getList();
		if (elist!=null && elist.size() > 0 && cp.getMemo2()!=null && !"".equals(cp.getMemo2())) {			
			for (QcmJhyElements el : elist) {
				el.setAssay_no(cp.getMemo2());//成分ID
				el.setHeat_no(ypd.getHeatno());
				el.setMaterial_no(ypd.getMaterailcoilno());
				el.setSteel_code(ypd.getJudgesteelcode());
				ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getJudgesteelcode());
				if (cbs!=null) {
					el.setSteel_name(cbs.getSteel_name());
				}
				el.setSource("0");//外购
				//el.setChem_name(el.getChem_name());//Si
				//el.setChem_value(el.getChem_value());//0.001
				ResultModel r = this.getBean(QmsApiServiceImpl.class).doQueryPhyBWeb(el.getChem_name());
				ComBaseChem cbc = (ComBaseChem) r.getData();
				if (cbc!=null) {
					el.setChem_code(cbc.getChem_code());							
				}
			}
			ResultModel r = this.getBean(QmsApiServiceImpl.class).insertElement(elist);
			if (r.getMsgInfo()!=null) {
				throw new Exception(r.getMsgInfo());
			}
		}
		
		
		String isOpen = this.getMapper(ComBaseInfoMapper.class).findById("9512").getMemo();
		if ("1".equals(isOpen)) {
		
			// 记录成本异动点：20230811刘侣 20230824
			ComBaseCbYdd cd = new ComBaseCbYdd();
			cd.setCoilStus("0"); // 综判前算半成品，综判入库后算成品
			cd.setInstDisp("01");
			cd.setDataTypeIdx("N");
			// 当前产线：
			String currentMachine = "YT1";
			cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setInvQtyUnit("块");
			cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
			cd.setCreateId(userId);
			cd.setActivityId("12AB");
			cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
			cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setProdName(ypd.getProd_name());
			cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
			
			String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypd.getCoilno());
			// 上道产线：
			String prevMachine = "YT1";
			cd.setRefnoA(ypd.getMaterailcoilno()); // 投料卷号
			cd.setSysId("IA");
			cd.setOrderItem(ypd.getOrderno());
			cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setBeTransUnit("t");
			cd.setExecJobFunc("N");
			ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getSteelcode());
			if (cbs != null) {
				cd.setAlloyNo(cbs.getSteel_name()); // 牌号
			}
			
			cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
			cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setBeTransWgt(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
			cd.setProdTypeNo("HCR");
			cd.setAppId("优特外购原料入库");
			// 外购入库也抛原料卷号，20231214 董提出：
			cd.setInvId(ypd.getMaterailcoilno());
			cd.setInvQty("1");
			cd.setSrcFac("3");
			cd.setGrade("1"); // 正品　1　协议　3　次品　5
			cd.setProdClassNo("H");

			// setSrcFac根据卷的物料属性去判断：20231031刘侣
			cd.setSrcFac("507101".equals(ypd.getObject_attr()) ? "1" : "3");
			
			// 存入表：
			this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
			// end
		}
		
		
		rm.setState("200");
		rm.setMsgInfo("外购入库成功");
		return rm;
	}

	
	/**
	 * 外购入库管理 入库确认（材质）
	 * memo1传材质结果id
	 * */
	public ResultModel doConfirmOut(CommonPage<IfRawMtrCoilPfmc> cp){
		ResultModel rm=new ResultModel();
		try {
			List<IfRawMtrCoilPfmc> lpfmc=cp.getObjectList();
			if(cp.getMemo1()!=null&&cp.getMemo1()!=""){
				YdmProductDetail ypd=new YdmProductDetail();
				String username=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
				ypd.setPhysid(cp.getMemo1());
				if (ypd.getCreatedate()==null||"".equals(ypd.getCreatedate())) {
					ypd.setCreatedate(new Date());
				}
				ypd.setState("5");
				List<YdmProductDetail> list=this.getMapper(YdmProductDetailMapper.class).find(ypd, 0, 0);
				if(list!=null&&list.size()>0){
					
				}else{
					//删除材质实绩
					this.getMapper(IfRawMtrCoilPfmcMapper.class).doDelete(cp.getMemo1());
					//插入材质实绩
					if(lpfmc!=null&&lpfmc.size()>0){
						for(IfRawMtrCoilPfmc pfmc:lpfmc){
							pfmc.setCreateOpr(username);
							pfmc.setCreateTime(new Date());
							pfmc.setPhysid(cp.getMemo1());
							pfmc.setSource("1");
							this.getMapper(IfRawMtrCoilPfmcMapper.class).doInsert(pfmc);
						}
					}
				}
				
			}
			rm.setState("200");
		} 
		catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，入库确认材质失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	/**
	 * 生成卷号
	 * @return
	 * @throws Exception
	 */
	public String createCoilNo() throws Exception
	{
		try 
		{
			String coilno="";
			String month=Integer.toHexString(Integer.valueOf(new SimpleDateFormat("MM").format(new Date())).intValue()).toUpperCase();
			List<HashMap> list = this.getMapper(IfRawMtrCoilMMapper.class).getNoA("Y"+(new SimpleDateFormat("yy").format(new Date()))+month);
			coilno = (String) list.get(0).get("MAXNO");
			return coilno;
		} 
		catch (Exception ex) 
		{
			throw (ex);
		}
	}
	
	/**
	 * 材质查询
	 */
	public ResultModel doQueryPfmcList(CommonPage<IfRawMtrCoilPfmc> sum){
		  ResultModel rm = new ResultModel();
	  	if(sum.getMemo1()==null||"".equals(sum.getMemo1())){
	  		rm.setState("500");
	  		rm.setMsgInfo("请传入原料卷号");
	  		return rm;
	  	  }
	  	  try {
	  		    rm.setData(this.getMapper(IfRawMtrCoilPfmcMapper.class).doQueryPfmcList(sum.getMemo1()));
				rm.setState("200");
			} catch (Exception e) {
				// TODO: handle exception
				rm.setState("500");
				e.getStackTrace();
				rm.setMsgInfo("查询失败！"+e.getMessage());
			}
	  	return rm;
	  }
}
