package com.dev.swms.server.service.base.pojo;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.dev.swms.server.model.abstractEntity.BomAccount;
import com.dev.swms.server.model.abstractEntity.Pinfan;
import com.dev.swms.server.model.abstractEntity.PlanAssembly;
import com.dev.swms.server.model.abstractEntity.PlanPickDetail;
import com.dev.swms.server.model.abstractEntity.PlanPickTicket;
import com.dev.swms.server.model.abstractEntity.ProduceMonthPlan;
import com.dev.swms.server.model.base.BillType;
import com.dev.swms.server.model.base.Location;
import com.dev.swms.server.model.base.Structure;
import com.dev.swms.server.model.base.WarehouseArea;
import com.dev.swms.server.model.shipping.PickTicket;
import com.dev.swms.server.model.shipping.PickTicketDetail;
import com.dev.swms.server.model.shipping.PickTicketStatus;
import com.dev.swms.server.model.shipping.PlanPickTicketDetail;
import com.dev.swms.server.model.shipping.PrintXppRecord;
import com.dev.swms.server.service.base.BillTypeManager;
import com.dev.swms.server.service.base.ItemManager;
import com.dev.swms.server.service.fee.FeeManager;
import com.dev.swms.server.service.interfaceLog.InterfaceLogManager;
import com.dev.swms.server.service.inventory.InventoryManager;
import com.dev.swms.server.service.picking.allocate.AutoAllocator;
import com.dev.swms.server.service.sequence.BussinessCodeManager;
import com.dev.swms.server.service.task.AllocateManager;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.dev.swms.server.model.base.Item;
import com.dev.energy.server.exception.BusinessException;
import com.dev.energy.server.model.EntityFactory;
import com.dev.energy.server.service.pojo.DefaultBaseManager;
import com.dev.energy.server.util.LocalizedMessage;
import com.dev.energy.server.web.security.UserHolder;

public class DefaultBillTypeManager extends DefaultBaseManager implements BillTypeManager {
	private final BussinessCodeManager bussinessCodeManager;
	public DefaultBillTypeManager(
			BussinessCodeManager manager3) {
		super();
		this.bussinessCodeManager = manager3;
	}
	public void deleteBillType(List<Long> billTypeIds) {
		String errMsg = "";
		for(Long id : billTypeIds){
			Long countRev = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getASNCountByBillTypeId", new String[] {"billTypeId"}, new Long[] {id})));
			Long countPic = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getPickticketCountByBillTypeId", new String[] {"billTypeId"}, new Long[] {id})));
			Long countMov = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getMoveDocCountByBillTypeId", new String[] {"billTypeId"}, new Long[] {id})));
			BillType billType = commonDao.load(BillType.class,id);
			if (countRev+countPic+countMov == 0){
				billType.setDisabled(true);
				errMsg+=billType.getCode()+" 单据失效成功;";
			}
			else
				errMsg+=billType.getCode()+" 单据失效失败;";
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	public void activeBillType(List<Long> billTypeIds) {
		for (Long id : billTypeIds) {
			BillType billType = this.commonDao.load(BillType.class,id);
			billType.setDisabled(false);
		}
		
	}

	public void storeBillType(BillType billType) {
		if (billType.getCompany()!= null) {
			billType.setCompany(commonDao.load(Structure.class, billType.getCompany().getId()));
		} else {
			billType.setCompany(null);
		}
		this.store(billType);
	}
	
	public void createPickYjh(List<Long> pickTicketIds,int fs) {
		String flg=(new Date()).getTime()+"";
		String ptdIds=StringUtils.strip(pickTicketIds.toString(),"[]");
		List<Long> ptIds=commonDao.findByQuery("select distinct(p.planPickTicket.id) from PlanPickDetail p where p.id in ("+ptdIds+")");
		if(ptIds.size()>1){
			throw new BusinessException("只能选择一张计划出库"); 
		}else{
			PlanPickTicket ppt=this.commonDao.get(PlanPickTicket.class, ptIds.get(0));
			ppt.setRealWeight(fs);
			if(!ppt.getStatus().equals(PickTicketStatus.OPEN)){
				throw new BusinessException("状态不正确"); 
			}
			List<PlanPickDetail> ptds =this.commonDao.findByQuery("from PlanPickDetail d where d.planPickTicket.id="+ppt.getId());
			for(PlanPickDetail ptd:ptds){
				ptd.setAllocatedQuantity(ptd.getOrderQuantity());
				this.commonDao.store(ptd);
			}
			ppt.setStatus(PickTicketStatus.ALLOCATE);
			this.commonDao.store(ppt);
			
//			String hql="select max(b.id), sum(b.single*pptd.orderQuantity)  "
//					+ " from BomAccount b,PlanPickDetail pptd "
//					+ " where pptd.planPickTicket.id="+ppt.getId()+" and b.bigItem.id=pptd.bigItem.id and b.outType='CKD单点' "
//					+ " and b.strExtend1='"+gw+"' and b.bonded='"+bonded+"' and b.strExtend3='"+bpzl+"'"
//					+ " group by b.zzkw.id, b.item.id";
			String hql="select sum(d.orderQuantity*b.single),b.item.id,b.bonded,d.bigItem.code,b.item.code"
					+ " from PlanPickDetail d,BomAccount b where d.planPickTicket.id="+ppt.getId()
					+" and d.bigItem.id=b.bigItem.id and b.outType='CKD单点' and b.strExtend3='小' and d.orderQuantity>0"
					+ " group by b.bonded,b.item.id"
					+ " order by b.bonded,b.item.id";
			Structure company=commonDao.load(Structure.class, 1002L);
			WarehouseArea zone_ks=(WarehouseArea) this.commonDao.findByQuery("from WarehouseArea z where z.code='久荣协同仓库(课)CKD'").get(0);//commonDao.load(WarehouseArea.class, 21L);
			WarehouseArea zone_bs=(WarehouseArea) this.commonDao.findByQuery("from WarehouseArea z where z.code='久荣协同仓库(保)CKD'").get(0);//commonDao.load(WarehouseArea.class, 24L);
			Location dock=null;
			List<Location> locs=commonDao.findByQuery(" from Location b where b.type='SHIP' and b.warehouse.id="+WarehouseHolder.getWarehouse().getId());
			if(locs.size()>0) {
				dock=locs.get(0);
			}else{
				throw new BusinessException("维护发货暂存区"); 
			}
			BillType bt=null;
			List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='CKD单点' ");
			if(list2.size()>0) {
				bt=list2.get(0);
			}else {
				throw new BusinessException("维护CKD单点单据类型"); 
			}
			WarehouseArea zone=null;
			List<Object[]> objs=this.commonDao.findByQuery(hql);
			PickTicket pt=null;
			PickTicket ptk=null;//createPickTicket(ppt.getCode(),bonded, bt, dock, zone, company, 1,fs,flg);
			PickTicket ptb=null;//createPickTicket(ppt.getCode(),bonded, bt, dock, zone, company, 1,fs,flg);
			for(Object[] obj:objs){
				Double qty =Double.parseDouble(obj[0].toString());
				Long itemId=Long.parseLong(obj[1].toString());
				String bonded=obj[2].toString();
//				System.out.println(obj[3]+" 税别:"+bonded+" 品番:"+obj[4]);
				Item it=this.commonDao.get(Item.class, itemId);
				Pinfan pf=null;
				String pf_hql="from Pinfan pf where pf.item.id="+itemId+" and pf.bonded='"+bonded+"' ";
				if(bonded.equals("保税")){
					zone=zone_bs;
					pf_hql+=" and pf.zone.id="+zone_bs.getId();
				}else if(bonded.equals("课税")){
					zone=zone_ks;
					pf_hql+=" and pf.zone.id="+zone_ks.getId();
				}
				List<Pinfan> pfs=this.commonDao.findByQuery(pf_hql);
				if(pfs.size()<=0){
					throw new BusinessException(obj[3]+"中"+it.getCode()+"无品番关联"); 
				}else{
					pf=pfs.get(0);
					if(pf.isBeYb()==false){
						continue;
					}
				}
				if(bonded.equals("保税")){
					if(ptb==null){
						ptb=createPickTicket(ppt.getCode(),bonded, bt, dock, zone, company, 1,fs,flg);
						pt=ptb;
					}
				}else if(bonded.equals("课税")){
					if(ptk==null){
						ptk=createPickTicket(ppt.getCode(),bonded, bt, dock, zone, company, 1,fs,flg);
						pt=ptk;
					}
				}
				PickTicketDetail ptd=EntityFactory.getEntity(PickTicketDetail.class);
				
				ptd.setPickTicket(pt);
				ptd.setZone2(zone);
				ptd.setItem(it);
				ptd.setPf(pf);
				ptd.setQuantity(pf.getQuantity());
				ptd.setSpecs(pf.getSpecs());
				ptd.setContent(pf.getContent());
				ptd.setBonded(pf.getBonded());
				ptd.setRejectQuantity(qty);
				double d=1;
				if(ptd.getQuantity()>0) {//收容数大于0
					d=Math.ceil(ptd.getRejectQuantity()/ptd.getQuantity());//几份收容数
					ptd.setOrderQuantity(ptd.getQuantity()*d);//备货数量
				}else {
					ptd.setOrderQuantity(ptd.getRejectQuantity());//备货数量
				}
				ptd.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
				ptd.setAllocatedQuantity(ptd.getOrderQtyOfMasterUnit());
				ptd.setQuantity4(ptd.getOrderQuantity());
				this.commonDao.store(ptd);
				pt.setRelatedBill3(ppt.getRelatedBill3());
				pt.setBOLQuantity(pt.getBOLQuantity()+ptd.getRejectQuantity());
				pt.setOrderQuantity(pt.getOrderQuantity()+ptd.getOrderQtyOfMasterUnit());
				pt.setAllocatedQuantity(pt.getAllocatedQuantity()+ptd.getAllocatedQuantity());
				this.commonDao.store(pt);
			}
			if(ptk!=null){
				for(int i=1;i<fs;i++){
					createNewPlanPick(ptk, i, fs);
					this.commonDao.store(ptk);
				}
			}
			if(ptb!=null){
				for(int i=1;i<fs;i++){
					createNewPlanPick(ptb, i, fs);
					this.commonDao.store(ptb);
				}
			}
		}
	}
	public PickTicket createNewPlanPick(PickTicket pt,int i,int fs) {
		double new_qty=0;
		double old_qty=0;
		int row=0;
		PickTicket new_pt=EntityFactory.getEntity(PickTicket.class);
		new_pt.setWarehouse(pt.getWarehouse());
		new_pt.setStatus(PickTicketStatus.OPEN);
//		new_pt.setCode(pt.getCode()+"-"+i);
		new_pt.setCode(this.bussinessCodeManager.getCodeForYm("YB",3));
		new_pt.setWaveCode(pt.getWaveCode());
		new_pt.setDock(pt.getDock());
		new_pt.setCompany(pt.getCompany());
		new_pt.setBillType(pt.getBillType());
		new_pt.setUserTracking();
		new_pt.setRelatedBill1(pt.getRelatedBill1());
		new_pt.setRelatedBill2(pt.getRelatedBill2());
		new_pt.setRelatedBill3(pt.getRelatedBill3());
		new_pt.setZone(pt.getZone());
		new_pt.setOrderDate(new Date());
		new_pt.setOrderQuantity(pt.getOrderQuantity());
		new_pt.setZone1(pt.getZone1());
		new_pt.setZone2(pt.getZone2());
		new_pt.setQuantity1(pt.getQuantity1());
		new_pt.setQuantity2(pt.getQuantity2());
		new_pt.setQuantity3(pt.getQuantity3());
		new_pt.setQuantity4(pt.getQuantity4());
		new_pt.setExecutePlanNo(pt.getExecutePlanNo());
		new_pt.setApplyDoc(pt.getApplyDoc());
		new_pt.setPrintCount(i+1);
		new_pt.setRealWeight(fs);
		this.commonDao.store(new_pt);
		List<PickTicketDetail> ptds=this.commonDao.findByQuery("from PickTicketDetail p where p.pickTicket.id="+pt.getId());
		for(PickTicketDetail ptd_o:ptds){
			PickTicketDetail ptd=null;
			double qty=ptd_o.getQuantity4();
			double srs=ptd_o.getQuantity();
			if(ptd_o.getOrderQuantity()>srs&&srs>0){
				ptd=EntityFactory.getEntity(PickTicketDetail.class);
				row++;
				ptd.setLineNumber(ptd_o.getLineNumber());
				ptd.setXqQty(ptd_o.getXqQty());//需要数量
			
				ptd.setQuantity4(ptd_o.getQuantity4());
				ptd.setQuantity5(ptd_o.getQuantity5());
				ptd.setXs(ptd_o.getXs());
				int fs_srs=(int) (qty/srs)/fs;//每份多少收容数
				if(fs_srs==0){
					fs_srs=1;//当每次不足一个收容数时，按照一个收容计算
				}
				ptd.setOrderQuantity(fs_srs*srs);
				ptd.setRejectQuantity(ptd.getOrderQuantity());
				ptd_o.setOrderQuantity(ptd_o.getOrderQuantity()-ptd.getOrderQuantity());
				ptd_o.setOrderQtyOfMasterUnit(ptd_o.getOrderQuantity());
				ptd_o.setRejectQuantity(ptd_o.getRejectQuantity()-ptd.getOrderQuantity());
				this.commonDao.store(ptd_o);
			}else{
//				ptd.setOrderQuantity(0);
				continue;
				//直接覆盖
			}
			new_qty+=ptd.getOrderQuantity();
			ptd.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
			ptd.setAllocatedQuantity(ptd.getOrderQuantity());
			ptd.setZzkw(ptd_o.getZzkw());
			ptd.setPf(ptd_o.getPf());
			ptd.setZone(ptd_o.getZone());
			ptd.setZone1(ptd_o.getZone1());
			ptd.setZone2(ptd_o.getZone2());
			ptd.setPickTicket(new_pt);
			ptd.setItem(ptd_o.getItem());
			ptd.setSOI(ptd_o.getSOI());
			ptd.setSpecs(ptd_o.getSpecs());
			ptd.setSingle(ptd_o.getSingle());
			ptd.setBonded(ptd_o.getBonded());
			ptd.setContent(ptd_o.getContent());
			ptd.setHezi(ptd_o.getHezi());
			ptd.setQuantity(ptd_o.getQuantity());//收容数
			this.commonDao.store(ptd);
			new_pt.addPickTicketDetail(ptd);
		}
		new_pt.setOrderQuantity(new_qty);
		new_pt.setBOLQuantity(new_qty);
		this.commonDao.store(new_pt);
		pt.setOrderQuantity(pt.getOrderQuantity()-new_qty);
		pt.setBOLQuantity(pt.getBOLQuantity()-new_qty);
		this.commonDao.store(pt);
		if(row==0){
			this.commonDao.delete(new_pt);
			return null;
		}else{
			return new_pt;
		}
	}
	
	PickTicket createPickTicket(String jhh,String sb,BillType bt,Location dock,WarehouseArea zone,Structure company,int fs,double ysfs,String flg){
		List<PickTicket> pts=this.commonDao.findByQuery("from PickTicket pt where pt.waveCode='"+jhh+"' and pt.printCount="+fs+" and pt.packType3='"+flg+"'"
				+ " and pt.zone.id="+zone.getId());
		if(pts.size()>0){
			return pts.get(0);
		}
		PickTicket pt=EntityFactory.getEntity(PickTicket.class);
		pt.setWarehouse(WarehouseHolder.getWarehouse());
		pt.setStatus(PickTicketStatus.OPEN);
		pt.setCode(this.bussinessCodeManager.getCodeForYm("YB",3));
		pt.setWaveCode(jhh);
		pt.setUserTracking();
		pt.setRelatedBill1("月出库单");
		pt.setApplyDoc(sb);
		pt.setZone(zone);
		pt.setCompany(company);
		pt.setBillType(bt);
		pt.setDock(dock);
		pt.setPrintCount(1);
		pt.setRealWeight(ysfs);
		pt.setPackType3(flg);
		pt.setOrderDate(new Date());
		this.commonDao.store(pt);
		return pt;
	}
	@Override
	public void activePlan(List<Long> ids) {
		for(Long id:ids){
			PickTicket pt=this.commonDao.get(PickTicket.class, id);
			pt.setStatus(PickTicketStatus.ALLOCATE);
			pt.setAllocatedQuantity(pt.getOrderQuantity());
			this.commonDao.store(pt);
		}
		
	}
	
	@Override
	public void unActivePlan(List<Long> ids) {
		for(Long id:ids){
			PickTicket pt=this.commonDao.get(PickTicket.class, id);
			//删除对应生成的现品票数据
			List<PrintXppRecord> rs=this.commonDao.findByQuery("from PrintXppRecord x where x.ddbh='"+pt.getCode()+"'");
			this.commonDao.deleteAll(rs);
			pt.setPickedQuantity(0);
			pt.setStatus(PickTicketStatus.OPEN);
			this.commonDao.store(pt);
			
		}
		
	}
	@Override
	public void updatePrintXppRecord(Long id, int qty) {
		PrintXppRecord p=commonDao.get(PrintXppRecord.class, id);
		p.setShsl(qty);
		p.setUpdateDate(new Date());
		p.setUpdateBy(UserHolder.getUser().getName());
//		DecimalFormat decimalFormat=new DecimalFormat("000000");
//		String nrs_h=decimalFormat.format(qty);
//		StringBuffer xpp=new StringBuffer();
//		xpp.append(p.getXpp());
//		xpp.replace(46, 52,nrs_h);
//		p.setXpp(xpp.toString());
		this.commonDao.store(p);
		
	}
	//备货计划修改
	public void updatePlanPick (Long id,double qty,String des){
		PlanPickDetail pd=commonDao.get(PlanPickDetail.class, id);
		PlanPickTicket pt=pd.getPlanPickTicket();
		if(pt.getRelatedBill1()!=null&&pt.getRelatedBill1().equals("日出库单")){
			if(!pt.getStatus().equals(PickTicketStatus.OPEN)){
				throw new BusinessException("状态不正确"); 
			}
		}else{
			if(qty<pd.getAllocatedQuantity()){
				throw new BusinessException("修改数量不能小于出单数"); 
			}
			if(pd.getBigItem()!=null&&!pt.getStatus().equals("OPEN")){
				throw new BusinessException("成套指示不能修改部品数量"); 
			}
		}
		//if(pt.getStatus())
		pd.setOrderQuantity(qty);
		pd.setDescription(des);
		this.commonDao.store(pd);
	}
	@Override
	public void unUsableProduceMonthPlan(List<Long> ids) {
		for(Long id:ids){
			PlanAssembly p=this.commonDao.get(PlanAssembly.class, id);
			p.setBeUsable(Boolean.TRUE);
			p.setUsableBy(UserHolder.getUser().getName());
			p.setUsableDate(new Date());
			this.commonDao.store(p);
		}
		
	}
	@Override
	public void usableProduceMonthPlan(List<Long> ids) {
		for(Long id:ids){
			PlanAssembly p=this.commonDao.get(PlanAssembly.class, id);
			p.setBeUsable(Boolean.FALSE);
			p.setUsableBy(UserHolder.getUser().getName());
			p.setUsableDate(new Date());
			this.commonDao.store(p);
		}
		
		
	}
	

}
