/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-07-04
 * 描述            ：资材备件库-入库信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Lms.Equipment.impl;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Equipment.mapper.YdmEquipmentDetailMapper;
import market.Lms.Equipment.mapper.YdmEquipmentInlistMapper;
import market.Lms.Equipment.service.YdmEquipmentInlistService;
import market.Lms.Equipment.vo.YdmEquipmentDetail;
import market.Lms.Equipment.vo.YdmEquipmentInlist;

import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;

@RemoteService(path="YdmEquipmentInlistService")
public class YdmEquipmentInlistServiceImpl extends BaseServiceImpl<YdmEquipmentInlist,Object> implements YdmEquipmentInlistService {
	/**
	 * 资材备件库-入库查询
	 * @param[{"object":{"storage_code":"v_storage","srot_code":"产品分类编码","mat_code":"产品编码","purc_order_no":"采购订单号","supplier_no":"供应商编码","in_type":"入库类型编码"},"startTime":"入库日期开始时间","endTime":"入库日期结束时间","pageIndex":"","pageSize":""}]
	 * @return
	 */
	public ResultModel doQueryYdmeiByWeb(CommonPage<YdmEquipmentInlist> cp){
		ResultModel rm=new ResultModel();
		try {
			if (cp!=null && cp.getObject()!=null && cp.getObject().getStorage_code()!=null 
					&& !"".equals(cp.getObject().getStorage_code())) {
				YdmEquipmentInlist ydmEi=cp.getObject();
				String swhere = "1=1";				
				if(cp.getStartTime()!=null&&!"".equals(cp.getStartTime())){
					swhere +=" and in_date  >= '"+cp.getStartTime()+"'";
				}
				if(cp.getEndTime()!=null&&!"".equals(cp.getEndTime())){
					swhere +=" and in_date  <= '"+cp.getEndTime()+"'";
				}
				if(ydmEi.getPurc_order_no()!=null&&!"".equals(ydmEi.getPurc_order_no().trim())){
					swhere += " and purc_order_no like '%" + ydmEi.getPurc_order_no() + "%'";
					ydmEi.setPurc_order_no(null);
				}
				if(ydmEi.getStorage_code()!= null&&!"".equals(ydmEi.getStorage_code().trim())){
					swhere += " and storage_code = '"+ydmEi.getStorage_code()+"'";
				}
				if (StringUtils.isEmpty(ydmEi.getSupplier_no())) {
					swhere += " and supplier_no <> 'P00039'";
				}
				if (StringUtils.isNotEmpty(ydmEi.getSupplier_no())) {
					swhere += " and supplier_no = '"+ydmEi.getSupplier_no()+"'";
				}
				List<YdmEquipmentInlist> list = this.getMapper(YdmEquipmentInlistMapper.class).findWithCondition(ydmEi, swhere, "opr_time desc", 0, 0);
				rm.setData(list);
				rm.setState("200");
				rm.setMsgInfo("查询成功!");
				}
					
			/*} else {
				rm.setState("500");
				rm.setMsgInfo("传入参数错误！");
			}*/
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败！"+ex.getMessage());
		}
		return rm;
	}
	/**
	 * 入库管理--入库撤销
	 * @param[{"object":{"in_bill_no":"入库单号","quantity":"数量","up_flag":"上传标志(0未上传 1已上传)"}}]
	 * @return
	 */
	@Transactional(value="tm",rollbackFor=Exception.class)
    public ResultModel doRevoke(CommonPage<YdmEquipmentInlist> cp) throws Exception{
    	ResultModel rm=new ResultModel();
    	if (cp!=null && cp.getObject()!=null && cp.getObject().getIn_bill_no()!=null && !"".equals(cp.getObject().getIn_bill_no())) {
			/*判断是否允许撤销
			对应入库记录上传标志(UP_FLAG)为1不允许撤销；
			在库存信息表（YDM_EQUIPMENT_DETAIL)对应库存编号&&在库的数量(QUANTITY)<撤销数量，则不允许撤销；*/
			//获取对象
			YdmEquipmentInlist ydm=cp.getObject();
		    YdmEquipmentInlist ydmEi=this.getMapper(YdmEquipmentInlistMapper.class).findById(ydm.getIn_bill_no());
		    if (ydmEi!=null) {
		    	//获取库存编号
		    	String objectNo=ydmEi.getObject_no();
		    	String state="0";
		    	//根据库存编号，查询库存数量 在库存信息表（YDM_EQUIPMENT_DETAIL)对应库存编号&&在库的数量(QUANTITY)<撤销数量，则不允许撤销；
		    	double quantity=this.getMapper(YdmEquipmentDetailMapper.class).doQueryQuantity(objectNo, state);
		    	if ("1".equals(ydmEi.getUp_flag()) || quantity<ydm.getQuantity()) {
					//不允许撤销
		    		rm.setState("500");
		    		rm.setMsgInfo("不允许撤销！");
				}else{
					YdmEquipmentDetail ydmEd=new YdmEquipmentDetail();
					ydmEd.setObject_no(objectNo);
					ydmEd.setState(state);
					//7.18改动  数量没相减就进行判断
					quantity = quantity - ydm.getQuantity();
					if (quantity==0) {
						this.getMapper(YdmEquipmentDetailMapper.class).doDelete(ydmEd);
					}else{
						//更新数据
						  this.getMapper(YdmEquipmentDetailMapper.class).doUpdateYdmEde(cp.getObject(), objectNo, state);;
					}
					//删除入库信息表（YDM_EQUIPMENT_INLIST）中对应入库编号的数据
			    	this.getMapper(YdmEquipmentInlistMapper.class).delete(ydmEi.getIn_bill_no());
			    	rm.setState("200");
			    	rm.setMsgInfo("撤销成功！");
				}  	
			} else {
				rm.setState("500");
				rm.setMsgInfo("没有该入库单号！");
			}
		} else {
			rm.setState("500");
			rm.setMsgInfo("参数错误！");
		}
    	return rm;
    }
	
	public ResultModel doExportExcel(CommonPage<YdmEquipmentInlist> cp){
		ResultModel rm = new ResultModel();
		try{
			String swhere = "1=1";
			YdmEquipmentInlist ydmEi=cp.getObject();
			if(cp.getStartTime()!=null&&!"".equals(cp.getStartTime())){
				swhere +=" and in_date  >= '"+cp.getStartTime()+"'";
			}
			if(cp.getEndTime()!=null&&!"".equals(cp.getEndTime())){
				swhere +=" and in_date  <= '"+cp.getEndTime()+"'";
			}
			if(ydmEi.getPurc_order_no()!=null&&!"".equals(ydmEi.getPurc_order_no().trim())){
				swhere += "and purc_order_no like '%" + ydmEi.getPurc_order_no() + "%'";
				ydmEi.setPurc_order_no(null);
			}
			if (ydmEi.getStorage_code() != null && !"".equals(ydmEi.getStorage_code())) {//t.storage_code='v_storage'
				swhere += " and storage_code = '"+ydmEi.getStorage_code()+"'";
			}
			List<YdmEquipmentInlist> list = this.getMapper(YdmEquipmentInlistMapper.class).findWithCondition(ydmEi, swhere, "opr_time desc", 0, 0);
			// 1，创建一个webbook，对应一个Excel文件
			//WritableWorkbook workbook;
			//2,设置用户下载路径
			String path = this.getRequest().getServletContext().getRealPath("/")+ "excel" + File.separator;  //临时保存路径
			File dir = new File(path);
			if(!dir.exists()) {
				new File(path).mkdir();
			}
		    generateExcel(rm, list, path,cp);
						
			rm.setState("200");
		}
		catch(Exception ex)
		{
			rm.setState("500");
			rm.setMsgInfo("导出失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	private void generateExcel(ResultModel rm, List<YdmEquipmentInlist> list, String path,CommonPage<YdmEquipmentInlist> cp)
			throws IOException, WriteException, RowsExceededException {
		
//    	Calendar cal = Calendar.getInstance();
//		String year=cal.get(Calendar.YEAR)+"年";
//		String month=(cal.get(Calendar.MONTH)+1)+"月";
//		String dept=cal.get(Calendar.DATE)+"日";
		String year1 = cp.getStartTime();
		String year2 = cp.getEndTime();
		String storage_name = "";
		if(cp.getObject().getStorage_code().equals("500207")){
			storage_name = "生产";
		}
		if(cp.getObject().getStorage_code().equals("500206")){
			storage_name = "工程";
		}
		String filename = year1+"至"+year2+"资材备件"+storage_name+"库入库查询报表";
//		String filename = year + month + dept + "资材备件库入库查询报表";
    	WritableWorkbook workbook;
		String file=filename+".xls";  //文件名
		//3. 操作EXCEL文件
		workbook = Workbook.createWorkbook(new File(path+file));
		WritableSheet sheet = workbook.createSheet("资材备件库入库查询报表", 1);
		//行高
		sheet.getSettings().setDefaultRowHeight(300);
		//字体  参数可自行配置
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
		cellFormat1.setAlignment(Alignment.CENTRE);
		cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		//表头
		sheet.mergeCells(0, 0, 0, 1);
		sheet.addCell(new Label(0,0,"序号",cellFormat1));
		
		sheet.mergeCells(1, 0, 1, 1);
		sheet.addCell(new Label(1,0,"入库日期",cellFormat1));
		
		sheet.mergeCells(2, 0, 2, 1);
		sheet.addCell(new Label(2,0,"入库类型",cellFormat1));
		
		sheet.mergeCells(3, 0, 3, 1);
		sheet.addCell(new Label(3,0,"产品分类",cellFormat1));
		
		sheet.mergeCells(4, 0, 4, 1);
		sheet.addCell(new Label(4,0,"产品名称",cellFormat1));
		
		sheet.mergeCells(5, 0, 5, 1);
		sheet.addCell(new Label(5,0,"规格",cellFormat1));
		
		sheet.mergeCells(6, 0, 6, 1);
		sheet.addCell(new Label(6,0,"供应商",cellFormat1));
		
		sheet.mergeCells(7, 0, 7, 1);
		sheet.addCell(new Label(7,0,"采购订单号",cellFormat1));
		
		sheet.mergeCells(8, 0, 8, 1);
		sheet.addCell(new Label(8,0,"数量",cellFormat1));
		
		sheet.mergeCells(9, 0, 9, 1);
		sheet.addCell(new Label(9,0,"单位",cellFormat1));
		
		sheet.mergeCells(10, 0, 10, 1);
		sheet.addCell(new Label(10,0,"单价",cellFormat1));
		
		sheet.mergeCells(11, 0, 11, 1);
		sheet.addCell(new Label(11,0,"金额",cellFormat1));
		
		sheet.mergeCells(12, 0, 12, 1);
		sheet.addCell(new Label(12,0,"堆放区域",cellFormat1));
		
		sheet.mergeCells(13, 0, 13, 1);
		sheet.addCell(new Label(13,0,"入库操作人",cellFormat1));		
		
		WritableFont font = new WritableFont(WritableFont.ARIAL,11,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat = new WritableCellFormat(font); 
		cellFormat.setAlignment(Alignment.CENTRE);
		cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		 //时间转字符串的格式
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		DecimalFormat df=new DecimalFormat("0.00");
		double totalMoney = 0;
		for(int i = 0; i < list.size(); i++) {
			//序号
			sheet.addCell(new Label(0,i+2,""+(i+1),cellFormat));
			//入库日期
			if(list.get(i).getIn_date() != null) {
				sheet.addCell(new Label(1,i+2,list.get(i).getIn_date(),cellFormat));
			}
			//入库类型
			if(list.get(i).getIn_type() != null && !"".equals(list.get(i).getIn_type())) {
				String intype = "";
				if(list.get(i).getIn_type().equals("500401")) {
					intype = "正常入库";
				} else if(list.get(i).getIn_type().equals("500402")) {
					intype = "盘库入库";
				} else if(list.get(i).getIn_type().equals("500403")) {
					intype = "退库接收";
				} else if(list.get(i).getIn_type().equals("500404")) {
					intype = "移送接收";
				} else if(list.get(i).getIn_type().equals("500405")) {
					intype = "吊销接收";
				}else if(list.get(i).getIn_type().equals("500406")) {
					intype = "外购入库";
				}else if(list.get(i).getIn_type().equals("500407")) {
					intype = "接收入库";
				}else if(list.get(i).getIn_type().equals("500408")) {
					intype = "采购入库";
				}else if(list.get(i).getIn_type().equals("500409")) {
					intype = "维修入库";
				}else if(list.get(i).getIn_type().equals("500410")) {
					intype = "归还入库";
				}
				sheet.addCell(new Label(2,i+2,intype,cellFormat));
			}
			//产品分类
			if(list.get(i).getSrot_name() != null && !"".equals(list.get(i).getSrot_name())) {
				sheet.addCell(new Label(3,i+2,list.get(i).getSrot_name(),cellFormat));
			}
			//产品名称
			if(list.get(i).getMat_name() != null && !"".equals(list.get(i).getMat_name())) {
				sheet.addCell(new Label(4,i+2,list.get(i).getMat_name(),cellFormat));
			}
			//规格
			if(list.get(i).getSpec() != null && !"".equals(list.get(i).getSpec())) {
				sheet.addCell(new Label(5,i+2,list.get(i).getSpec(),cellFormat));
			}
			//供应商
			if(list.get(i).getSupplier_name() != null && !"".equals(list.get(i).getSupplier_name())) {
				sheet.addCell(new Label(6,i+2,""+list.get(i).getSupplier_name(),cellFormat));
			}
			//采购订单号
			if(list.get(i).getPurc_order_no() != null && !"".equals(list.get(i).getPurc_order_no())){
				sheet.addCell(new Label(7,i+2,""+list.get(i).getPurc_order_no(),cellFormat));
			}
			//数量
			if(list.get(i).getQuantity() != null) {
				sheet.addCell(new Label(8,i+2,""+list.get(i).getQuantity(),cellFormat));
			}
			//单位
			if(list.get(i).getUnit() != null && !"".equals(list.get(i).getUnit())) {
				sheet.addCell(new Label(9,i+2,list.get(i).getUnit(),cellFormat));
			}
			//单价
			if(list.get(i).getPrice() != null) {
				sheet.addCell(new Label(10,i+2,list.get(i).getPrice().toString(),cellFormat));
			}
			//金额
			if(list.get(i).getPrice() != null && list.get(i).getQuantity() != null) {
				sheet.addCell(new Label(11,i+2,df.format(list.get(i).getPrice() * list.get(i).getQuantity()),cellFormat));
				totalMoney += Double.parseDouble(df.format(list.get(i).getPrice() * list.get(i).getQuantity()));
			}
			//堆放区域
			if(list.get(i).getArea() != null && !"".equals(list.get(i).getArea())) {
				sheet.addCell(new Label(12,i+2,list.get(i).getArea(),cellFormat));
			}
			//入库操作人
			if(list.get(i).getOpr_man() != null && !"".equals(list.get(i).getOpr_man())) {
				sheet.addCell(new Label(13,i+2,list.get(i).getOpr_man(),cellFormat));
			}
		}
		sheet.addCell(new Label(0,list.size()+2,"总计",cellFormat));
		WritableCellFormat cellFormat2 = new WritableCellFormat(font); 
		cellFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
		sheet.addCell(new Label(1,list.size()+2,"数量: "+list.size(),cellFormat2));
		sheet.addCell(new Label(11,list.size()+2,""+df.format(totalMoney),cellFormat));
		
		sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
		sheet.getSettings().setVerticalFreeze(2);
		//关闭
		workbook.write();
		workbook.close();
		
		rm.setData("/download?filename="+file);
	}
}
