/***文档注释***********************************************
 * 作者            ：谢卫龙
 * 创建日期     ：2018-07-04
 * 描述            ：资材备件库-出库信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Lms.Equipment.impl;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
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.YdmEquipmentLendlistMapper;
import market.Lms.Equipment.mapper.YdmEquipmentOutlistMapper;
import market.Lms.Equipment.service.YdmEquipmentOutlistService;
import market.Lms.Equipment.vo.YdmEquipmentApplylist;
import market.Lms.Equipment.vo.YdmEquipmentDetail;
import market.Lms.Equipment.vo.YdmEquipmentLendlist;
import market.Lms.Equipment.vo.YdmEquipmentOutlist;

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;
import com.hnshituo.core.auth.service.HomeService;

@SuppressWarnings("rawtypes")
@RemoteService(path="YdmEquipmentOutlistService")
public class YdmEquipmentOutlistServiceImpl extends BaseServiceImpl<YdmEquipmentOutlist,Object> implements YdmEquipmentOutlistService {
	/**
	 * 从度量单位配置表(PUR_BS_UOMS)中获取度量单位在单位下拉列表中
	 * @param sum
	 * @return
	 */
	public ResultModel findPurbsuoms(CommonPage<YdmEquipmentOutlist> sum){
		ResultModel rm = new ResultModel();
		try {
			List<HashMap> listMap = this.getMapper(YdmEquipmentOutlistMapper.class).findPurbsuoms();
			rm.setData(listMap);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("产品名称列表获取失败。");
		}
		return rm;
	}
	/**
	 * 产品名称表(PUR_MAT_M)：根据产品类型获取相应的产品名称
	 * @param sum
	 * @return
	 */
	public ResultModel findProNameByMatclasscode(CommonPage<YdmEquipmentOutlist> sum){
		ResultModel rm = new ResultModel();
		try {
			String memo = sum.getMemo1();
			if (memo==null||"".equals(memo)) {
				rm.setState("500");
				rm.setMsgInfo("请传入产品分类编码");
				return rm;
			}
			List<HashMap> listMap = this.getMapper(YdmEquipmentOutlistMapper.class).findProNameByMatclasscode(sum.getMemo1());
			rm.setData(listMap);
			rm.setState("200");
		} catch (Exception e) {
			
			rm.setState("500");
			rm.setMsgInfo("产品名称列表获取失败。");
		}
		return rm;
	}
	/**
	 * 供应商基础信息表(PUR_SUPP_M)中获取资材备件供应商
	 * @return
	 */
	public ResultModel findSupp(CommonPage<YdmEquipmentOutlist> sum){
		ResultModel rm = new ResultModel();
		try {
			List<HashMap> findSupp = this.getMapper(YdmEquipmentOutlistMapper.class).findSupp();
			rm.setData(findSupp);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("供应商列表获取失败。");
		}
		return rm;
	}
	/**
	 * 仓库垛位配置表(YDM_BASE_BUTTRESSCONFIG)中获取资材备件库对应的所有区域信息
	 */
	public ResultModel findButtressBy1006(CommonPage<YdmEquipmentOutlist> sum){
		ResultModel rm = new ResultModel();
		try {
			List<HashMap> by1006 = this.getMapper(YdmEquipmentOutlistMapper.class).findButtressBy1006();
			rm.setData(by1006);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("区域信息列表获取失败。");
		}
		return rm;
	}
	/**
	 * 从度量单位配置表(PUR_BS_UOMS)中获取度量单位在单位下拉列表中
	 * @return
	 */
	public ResultModel findPurBsUoms(CommonPage<YdmEquipmentOutlist> sum){
		ResultModel rm = new ResultModel();
		try {
			List<HashMap> bsUoms = this.getMapper(YdmEquipmentOutlistMapper.class).findPurBsUoms();
			rm.setData(bsUoms);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("度量单位列表获取失败。");
		}
		return rm;
	}
	
	/**
	 * 出库查询
	 * [{"object":{"srot_code":"产品分类编码","mat_code":"产品编码","purc_order_no":"采购订单号","supplier_no":"供应商代码","out_type":"出库类型"},"startTime":"2018-07-02","endTime":"2018-07-07"}]
	 * @return
	 */
	public ResultModel selectForOutlist(CommonPage<YdmEquipmentOutlist> sum){
		ResultModel rm = new ResultModel();
		try {
			YdmEquipmentOutlist ydm_out = sum.getObject();
			if (ydm_out==null) {
				rm.setState("500");
				rm.setMsgInfo("请传入正确参数。");
				return rm;
			}
			StringBuffer whereStr = new StringBuffer(" where 1=1");
			if (sum.getStartTime()!=null&&!"".equals(sum.getStartTime())&&sum.getEndTime()!=null&&!"".equals(sum.getEndTime())) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date startDate = sdf.parse(sum.getStartTime());
				Date endDate = sdf.parse(sum.getEndTime());
				if (startDate.after(endDate)) {//startDate>endDate
					rm.setState("500");
					rm.setMsgInfo("开始时间不能大于结束时间");
					return rm;
				}
				if((int) ((startDate.getTime() - startDate.getTime())/(1000*3600*24))>30){
					rm.setState("500");
					rm.setMsgInfo("开始时间与结束时间差不能大于30天。");
					return rm;
				}else{
					whereStr.append(" and to_date(t.OUT_DATE,'yyyy-MM-dd HH24:MI:SS') between to_date('");
					whereStr.append(sum.getStartTime());
					whereStr.append("','yyyy-MM-dd HH24:MI:SS') and to_date('");
					whereStr.append(sum.getEndTime());
					whereStr.append("','yyyy-MM-dd HH24:MI:SS')");
					whereStr.append(" and storage_code = '"+ydm_out.getStorage_code()+"'");
				};
			}
			if (ydm_out.getSrot_code()!=null&&!"".equals(ydm_out.getSrot_code())) {
				whereStr.append(" and t.Srot_Code = '"+ydm_out.getSrot_code()+"'");
			}
			if (ydm_out.getMat_code()!=null&&!"".equals(ydm_out.getMat_code())) {
				whereStr.append(" and t.Mat_Code = '"+ydm_out.getMat_code()+"'");
			}
			if (ydm_out.getPurc_order_no()!=null&&!"".equals(ydm_out.getPurc_order_no())) {
				whereStr.append(" and t.Purc_Order_No like '%"+ydm_out.getPurc_order_no()+"%'");
			}
			if (StringUtils.isEmpty(ydm_out.getSupplier_no())) {
				whereStr.append(" and t.supplier_no <> 'P00039'");
			}
			if (ydm_out.getSupplier_no()!=null&&!"".equals(ydm_out.getSupplier_no())) {
				whereStr.append(" and t.Supplier_No = '"+ydm_out.getSupplier_no()+"'");
			}
			if (ydm_out.getOut_type()!=null&&!"".equals(ydm_out.getOut_type())) {
				whereStr.append(" and t.Out_Type = '"+ydm_out.getOut_type()+"'");
			}
			if (ydm_out.getStorage_code() != null && !"".equals(ydm_out.getStorage_code())) {//t.storage_code='v_storage'
				whereStr.append(" and t.storage_code = '"+ydm_out.getStorage_code()+"'");
			}
			List<YdmEquipmentOutlist> outlist = this.getMapper(YdmEquipmentOutlistMapper.class).selectForOutlist(whereStr.toString());
			rm.setData(outlist);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败。");
			e.printStackTrace();
		}
		return rm;
	}
	/**
	 * 计划
	 * 审批查询（基础条件： 状态 in (1审批、2执行、3完成);所属仓库代码(STORAGE_CODE) = "v_storage"）
	 * [{"object":{"srot_code":"产品分类编码","mat_code":"产品编码","state":"状态"},"startTime":"2018-07-02","endTime":"2018-07-07"}]
	 * @param sum
	 * @return
	 */
	public ResultModel selectForApplylist(CommonPage<YdmEquipmentApplylist> sum){
		ResultModel rm = new ResultModel();
		try {
			YdmEquipmentApplylist apply = sum.getObject();
			if (apply==null) {
				rm.setState("500");
				rm.setMsgInfo("请传入正确参数。");
				return rm;
			}
			StringBuffer whereStr = new StringBuffer();
			if (sum.getStartTime()!=null&&!"".equals(sum.getStartTime())&&sum.getEndTime()!=null&&!"".equals(sum.getEndTime())) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date startDate = sdf.parse(sum.getStartTime());
				Date endDate = sdf.parse(sum.getEndTime());
				if (startDate.after(endDate)) {//startDate>endDate
					rm.setState("500");
					rm.setMsgInfo("开始时间不能大于结束时间");
					return rm;
				}
				whereStr.append(" and t.Apply_Time between to_date('");
				whereStr.append(sum.getStartTime());
				whereStr.append("','yyyy-MM-dd HH24:MI:SS') and to_date('");
				whereStr.append(sum.getEndTime());
				whereStr.append("','yyyy-MM-dd HH24:MI:SS')");
			}
			if (apply.getSrot_code()!=null&&!"".equals(apply.getSrot_code())) {
				whereStr.append(" and t.Srot_Code = '"+apply.getSrot_code() +"'");
			}
			if (apply.getMat_code()!=null&&!"".equals(apply.getMat_code())) {
				whereStr.append(" and t.Mat_Code = '"+apply.getMat_code() +"'");
			}
			if (apply.getState()!=null&&!"".equals(apply.getState())) {
				whereStr.append(" and t.state = '"+apply.getState() +"'");
			}
			if (apply.getStorage_code()!=null&&!"".equals(apply.getStorage_code())) {
				whereStr.append(" and t.STORAGE_CODE = '"+apply.getStorage_code() +"'");
			}
			List<YdmEquipmentApplylist> applylist = this.getMapper(YdmEquipmentOutlistMapper.class).selectForApplylist(whereStr.toString());
			rm.setData(applylist);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败。");
			e.printStackTrace();
		}
		return rm;
	}
	/**
	 * 计划
	 * 单击选择审批信息，根据审批信息查询库存信息
	 * [{"object":{"srot_code":"产品分类编码","mat_code":"产品编码","state":"状态","apply_bill_no":"申报单号","spec":"规格"}}]
	 * @param sum
	 * @return
	 */
	public ResultModel selectDetail(CommonPage<YdmEquipmentApplylist> sum){
		ResultModel rm = new ResultModel();
		try {
			YdmEquipmentApplylist apply = sum.getObject();
			if (apply==null) {
				rm.setState("500");
				rm.setMsgInfo("请传入正确参数。");
				return rm;
			}
			if (apply.getSrot_code()==null||"".equals(apply.getSrot_code())) {
				rm.setState("500");
				rm.setMsgInfo("参数没有 产品分类编码。");
				return rm;
			}
			if (apply.getMat_code()==null||"".equals(apply.getMat_code())) {
				rm.setState("500");
				rm.setMsgInfo("参数没有 产品编码。");
				return rm;
			}
			if (apply.getSpec()==null||"".equals(apply.getSpec())) {
				rm.setState("500");
				rm.setMsgInfo("参数没有 产品规格。");
				return rm;
			}
			if (apply.getStorage_code()==null||"".equals(apply.getStorage_code())) {
				rm.setState("500");
				rm.setMsgInfo("参数没有 库存编码。");
				return rm;
			}
			List<YdmEquipmentDetail> Details = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetail(apply);
			rm.setData(Details);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败。");
			e.printStackTrace();
		}
		return rm;
	}
	/**
	 * 计划
	 * 单击选择审批信息，根据审批信息查询出库信息
	 * [{"object":{"srot_code":"产品分类编码","mat_code":"产品编码","state":"状态","apply_bill_no":"申报单号","spec":"规格"}}]
	 * @param sum
	 * @return
	 */
	public ResultModel selectOutlist(CommonPage<YdmEquipmentApplylist> sum){
		ResultModel rm = new ResultModel();
		try {
			YdmEquipmentApplylist apply = sum.getObject();
			if (apply==null) {
				rm.setState("500");
				rm.setMsgInfo("请传入正确参数。");
				return rm;
			}
			if (apply.getApply_bill_no()==null||"".equals(apply.getApply_bill_no())) {
				rm.setState("500");
				rm.setMsgInfo("参数没有 申报单号。");
				return rm;
			}
			List<YdmEquipmentOutlist> Outlist = this.getMapper(YdmEquipmentOutlistMapper.class).selectOutlist(apply);
			rm.setData(Outlist);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败。");
			e.printStackTrace();
		}
		return rm;
	}
	//TODO 资材备件出库撤销(计划)
	/**
	 * 出库撤销
	 * [{"object":{"out_bill_no":"IN201807050002","object_no":"KC201807050001","out_type":"借用出库","quantity":"0","apply_bill_no":"1"}}]
	 * @param sum
	 * @return
	 * @throws Exception 
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel updateDoOutRevoke(CommonPage<YdmEquipmentOutlist> sum) throws Exception {
		ResultModel rm = new ResultModel();
		
			YdmEquipmentOutlist outlist = sum.getObject();
			if (outlist==null) {
				throw new Exception("请传入正确参数。");
			}
			if (outlist.getOut_bill_no()==null||"".equals(outlist.getOut_bill_no())) {
				throw new Exception("缺失出库单号。");
			}
			if (outlist.getApply_bill_no()==null||"".equals(outlist.getApply_bill_no())) {
				throw new Exception("缺失申报编号。");
			}
			if (outlist.getQuantity()==null) {
				outlist.setQuantity(0d);
			}
			
			// 查询对应的申报信息
			YdmEquipmentApplylist apply = this.getMapper(YdmEquipmentOutlistMapper.class).selectOneApply(outlist.getApply_bill_no());
			if (apply==null) {
				throw new Exception("没有找到相关的申报信息。");
			}
			
			if (apply.getGrant_quantity() == null) {
				apply.setGrant_quantity(0d);
			}
			
			if (apply.getGrant_quantity()==0) {
				throw new Exception("申报已发放数量等于0 ! 请重新操作!");
			}
			
			// 更新申报信息
			if (apply.getGrant_quantity()-outlist.getQuantity()>0) {
				apply.setGrant_quantity(apply.getGrant_quantity()-outlist.getQuantity());
				apply.setState("2");
				this.getMapper(YdmEquipmentOutlistMapper.class).updateApplylist(apply);
			}else if(apply.getGrant_quantity()-outlist.getQuantity()==0){
				// 1.状态设置为1审批;2.发放操作时间、发放部门、发放操作人设置为null (三者置为null，sql已写死)
				apply.setGrant_quantity(apply.getGrant_quantity()-outlist.getQuantity());
				apply.setState("1");
				this.getMapper(YdmEquipmentOutlistMapper.class).updateApplynull(apply);
			}else{
				throw new Exception("申报已发放数量小于撤销的出库数量。请联系数据库管理员。");
			}
			
			// 修改库存信息
			if (outlist.getObject_no()==null||"".equals(outlist.getObject_no())) {
				throw new Exception("出库信息的 库存编号 为空。");
			}
			
			YdmEquipmentDetail detail = new YdmEquipmentDetail();
			detail.setObject_no(outlist.getObject_no());
			
			if (outlist.getOut_type()!=null&&!"".equals(outlist.getOut_type())) {
				if ("500509".equals(outlist.getOut_type())) {
					detail.setState("5");
					List<YdmEquipmentDetail> details = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(detail);
					if (details==null||details.isEmpty()) {
						throw new Exception("数据已更改，没有相关出库记录。");
					}
					details.get(0).setQuantity(details.get(0).getQuantity()==null?0d:details.get(0).getQuantity());
					if (details.get(0).getQuantity()<=0) {
						throw new Exception("库存出库数据异常-5。请联系数据库管理员。");
					}
					Double ql = details.get(0).getQuantity()-outlist.getQuantity();
					if (ql.doubleValue()>0) {
						// 修改出库数据
						detail.setQuantity(ql);
						this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(detail);
					}else if (ql.doubleValue()==0) {
						// 删除出库数据
						this.getMapper(YdmEquipmentOutlistMapper.class).deleteDetail(detail);
					}else{
						throw new Exception("库存出库数据数量小于撤销出库数量。请重新操作 !");
					}
					detail=details.get(0);
				}else if("500510".equals(outlist.getOut_type())){
					detail.setState("1");
					List<YdmEquipmentDetail> details = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(detail);
					if (details==null||details.isEmpty()) {
						throw new Exception("数据已更改，没有相关借出记录。");
					}
					details.get(0).setQuantity(details.get(0).getQuantity()==null?0d:details.get(0).getQuantity());
					if (details.get(0).getQuantity()<=0) {
						throw new Exception("库存借出数据异常-5。请联系数据库管理员。");
					}
					Double ql = details.get(0).getQuantity()-outlist.getQuantity();
					if (ql.doubleValue()>0) {
						// 修改借出数据
						detail.setQuantity(ql);
						this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(detail);
					}else if (ql.doubleValue()==0) {
						// 删除借出数据
						this.getMapper(YdmEquipmentOutlistMapper.class).deleteDetail(detail);
					}else{
						throw new Exception("库存借出数据数量小于撤销出库数量。请重新操作 !");
					}
					detail=details.get(0);
					
					YdmEquipmentLendlist lendlist = this.getMapper(YdmEquipmentOutlistMapper.class).selectLendlist(outlist.getOut_bill_no());
					if (lendlist == null) {
						throw new Exception("无法查到对应的借出信息。");
					}else{
						if (lendlist.getState() != null && "1".equals(lendlist.getState())) {
							throw new Exception("改资材已归还。");
						}
					}
					// 删除对应出库编号的借出记录
					this.getMapper(YdmEquipmentOutlistMapper.class).deleteLendlist(outlist.getOut_bill_no());
				}
			}else{
				throw new Exception("出库信息的出库类型为空。");
			}
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			// 维护在库数据
			detail.setState("0");
			List<YdmEquipmentDetail> details = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(detail);
			if (details==null||details.isEmpty()) {
				// 新增对应库存编号&&在库的数据
				// 数量
				detail.setQuantity(outlist.getQuantity());
				// 入库日期
				detail.setIn_date(sdf.format(new Date()));
				this.getMapper(YdmEquipmentDetailMapper.class).insert(detail);
			}else{
				// 修改对应库存编号&&在库的数据
				detail.setQuantity(details.get(0).getQuantity()+outlist.getQuantity());
				this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(detail);
			}
			// 删除对应出库编号的出库记录
			this.getMapper(YdmEquipmentOutlistMapper.class).deleteOutlist(outlist.getOut_bill_no());
			
			rm.setMsgInfo("撤销成功 ! ! !");
			rm.setState("200");
		
		return rm;
	}

	/**
	 * 出库确认
	 * [{"object":{"object_no":"KC201807050001","out_type":"借用出库","quantity":"1","apply_bill_no":"1","out_date":"2018-07-05","apply_type":"申报类型","apply_dept":"申报部门","apply_man":"申报人"}}]
	 * @param sum
	 * @return
	 * @throws Exception 
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel updateDoOutConfirm(CommonPage<YdmEquipmentDetail> sum) throws Exception{
		ResultModel rm = new ResultModel();
		
			String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			if (username==null || "".equals(username)) {
				throw new Exception("登录信息过期,请重新登录 !");
			}
			String userid = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
			if (userid==null || "".equals(userid)) {
				throw new Exception("登录信息过期,请重新登录 !");
			}
			String order = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
			if (order==null || "".equals(order)) {
				order="0";
			}
			String team = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
			if (team==null || "".equals(team)) {
				team="0";
			}
			String dept = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_NAME);
			if (dept==null || "".equals(dept)) {
				dept="0";
			}
			YdmEquipmentDetail detail = sum.getObject();
			if (detail==null) {
				throw new Exception("请传入正确参数!");
			}
			if (detail.getQuantity()==null) {
				throw new Exception("请传入 出库数量 !");
			}
			if (detail.getQuantity()<=0) {
				throw new Exception("出库数量 必须大于 0 !");
			}
			if (detail.getOut_date()==null || "".equals(detail.getOut_date())) {
				throw new Exception("请传入出库日期 !");
			}
			if (detail.getMachine_name()==null || "".equals(detail.getMachine_name().trim()))
			{
				throw new Exception("请传入机台信息 !");
			}
			//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if (detail.getObject_no()==null || "".equals(detail.getObject_no())) {
				throw new Exception("参数缺失 库存编号 !");
			}
			String apply_bill_no = detail.getApply_bill_no();
			if (apply_bill_no==null || "".equals(apply_bill_no)) {
				throw new Exception("参数缺失 申报单号 !");
			}
			YdmEquipmentApplylist oneApply = this.getMapper(YdmEquipmentOutlistMapper.class).selectOneApply(apply_bill_no);
			if (oneApply==null) {
				throw new Exception("未找到申报信息，请重新操作!");
			}
			if (oneApply.getGrant_quantity() == null) {
				oneApply.setGrant_quantity(0d);
			}
			if (oneApply.getApproval_quantity()!=null && oneApply.getGrant_quantity() != null) {
				if (oneApply.getApproval_quantity()==oneApply.getGrant_quantity()) {
					oneApply.setState("3");
					this.getMapper(YdmEquipmentOutlistMapper.class).updateApply(oneApply);
				}
			}else{
				throw new Exception("申报信息没有审批数量或发放数量!");
			}
			if ("3".equals(oneApply.getState())) {
				throw new Exception("该审批报告已完成!");
			}
			if (oneApply.getGrant_quantity()+detail.getQuantity()>oneApply.getApproval_quantity()) {
				throw new Exception("出库数量 已大于需发数量!");
			}
			YdmEquipmentDetail Timp_detail = new YdmEquipmentDetail();
			Timp_detail.setObject_no(detail.getObject_no());
			Timp_detail.setState("0");
			List<YdmEquipmentDetail> selectDetailOne = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(Timp_detail);
			if (selectDetailOne==null || selectDetailOne.isEmpty()) {
				throw new Exception("未找到库存信息，库存信息已更改，请重新查询!");
			}
			Timp_detail=selectDetailOne.get(0);
			Double quantity = Timp_detail.getQuantity();//库存数量
			if (quantity == null || quantity.doubleValue()==0) {
				throw new Exception("当前资材 【 "+detail.getObject_no()+" 】 库存为 0 ,请重新操作!");
			}else if(quantity.doubleValue()<0){
				throw new Exception("库存数量数据异常 -1  请联系数据库管理员。");
			}
			if (detail.getQuantity().doubleValue()>quantity.doubleValue()) {//detail.getQuantity():出库数量
				throw new Exception("库存数量不足，请重新出库 !  库存:【 "+quantity+" 】");
			}
			// 修改库存在库数量
			if (quantity.doubleValue()-detail.getQuantity().doubleValue()>0) {
				Timp_detail.setQuantity(quantity-detail.getQuantity());
				this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(Timp_detail);
			}else if(quantity.doubleValue()-detail.getQuantity().doubleValue()==0){
				// 删除库存编号&&在库的数据
				this.getMapper(YdmEquipmentOutlistMapper.class).deleteDetail(Timp_detail);
			}
			
			if (detail.getApply_type()!=null && "500509".equals(detail.getApply_type())) {
				Timp_detail.setState("5");
				List<YdmEquipmentDetail> detailOut = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(Timp_detail);
				if (detailOut==null || detailOut.isEmpty()) {
					// 新增库存出库数据
					Timp_detail.setQuantity(detail.getQuantity());
					this.getMapper(YdmEquipmentDetailMapper.class).insert(Timp_detail);
				}else{
					Timp_detail=detailOut.get(0);
					// 修改库存出库数量
					if (Timp_detail.getQuantity() == null) {
						Timp_detail.setQuantity(0d);
					}
					Timp_detail.setQuantity(Timp_detail.getQuantity()+detail.getQuantity());
					this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(Timp_detail);
				}
			}else if(detail.getApply_type()!=null && "500510".equals(detail.getApply_type())){
				Timp_detail.setState("1");
				List<YdmEquipmentDetail> detailOut = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(Timp_detail);
				if (detailOut==null || detailOut.isEmpty()) {
					// 新增库存借出数据
					Timp_detail.setQuantity(detail.getQuantity());
					this.getMapper(YdmEquipmentDetailMapper.class).insert(Timp_detail);
				}else{
					Timp_detail=detailOut.get(0);
					// 修改库存借出数据
					if (Timp_detail.getQuantity() == null) {
						Timp_detail.setQuantity(0d);
					}
					Timp_detail.setQuantity(Timp_detail.getQuantity()+detail.getQuantity());
					this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(Timp_detail);
				}
			}else{
				throw new Exception("请传入有效的申报类型!");
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat sdff = new SimpleDateFormat("yyyy-MM-dd");
			// 新增出库信息表
			String out_bill_no = "OT";
			out_bill_no+=sdf.format(new Date());
			String maxOutbillno = this.getMapper(YdmEquipmentOutlistMapper.class).selectMaxOutbillno(out_bill_no);
			if (maxOutbillno==null || "".equals(maxOutbillno)) {
				out_bill_no+="0001";
			}else if(maxOutbillno.length()==14){
				String str = maxOutbillno.substring(10);
				int i = Integer.parseInt(str)+1;
				str = String.format("%04d",i);
				out_bill_no+=str;
			}else{
				throw new Exception("出库编号异常 :"+maxOutbillno);
			}
			detail.getApply_type();
			YdmEquipmentOutlist outlist = new YdmEquipmentOutlist();
			outlist.setOut_bill_no(out_bill_no);
			outlist.setApply_bill_no(apply_bill_no);
			outlist.setQuantity(detail.getQuantity());
			outlist.setOut_type(detail.getApply_type());
			outlist.setOut_ord(order);
			outlist.setOut_grp(team);
			outlist.setOut_date(detail.getOut_date());
			outlist.setOpr_time(new Date());
			outlist.setOpr_man(username);
			outlist.setApply_dept(oneApply.getApply_dept());
			outlist.setApply_man(detail.getApply_man());
			outlist.setObject_no(detail.getObject_no());
			outlist.setMat_code(Timp_detail.getMat_code()); // 产品编码
			outlist.setMat_name(Timp_detail.getMat_name()); // 产品名称
			outlist.setSrot_code(Timp_detail.getSrot_code()); // 产品分类编码
			outlist.setSrot_name(Timp_detail.getSrot_name()); // 产品分类名称
			outlist.setSpec(Timp_detail.getSpec()); // 规格
			outlist.setPurc_order_pk(Timp_detail.getPurc_order_pk()); 
			outlist.setPurc_order_no(Timp_detail.getPurc_order_no()); //采购订单号
			outlist.setSupplier_no(Timp_detail.getSupplier_no()); // 供应商代码
			outlist.setSupplier_name(Timp_detail.getSupplier_name()); // 供应商名称
			outlist.setUnit(Timp_detail.getUnit()); // 单位
			outlist.setPrice(Timp_detail.getPrice()); // 单价
			outlist.setArea(Timp_detail.getArea());// 区域
			outlist.setDept_code(Timp_detail.getDept_code());
			outlist.setStorage_code(Timp_detail.getStorage_code());
			outlist.setCreate_man_no(userid);
			outlist.setCreate_man_name(username);
			outlist.setCreate_time(new Date());
			outlist.setStorage_code(Timp_detail.getStorage_code());
			outlist.setMaintain_bill_no("-");
			outlist.setApply_man(oneApply.getOpr_man());
			outlist.setMachine_code(detail.getMachine_code());//机台代码
			outlist.setMachine_name(detail.getMachine_name());//机台名称
			this.getMapper(YdmEquipmentOutlistMapper.class).insert(outlist);
			
			if ("500510".equals(detail.getApply_type())) {
				// 新增借出信息表
				String lend_bill_no = "LD";// 借出编号
				lend_bill_no+=sdf.format(new Date());
				// 查询库存里最大编号数据
				String maxLendbillno = this.getMapper(YdmEquipmentOutlistMapper.class).selectMaxLendbillno(lend_bill_no);
				if (maxLendbillno==null || "".equals(maxLendbillno)) {
					lend_bill_no+="0001";
				}else if(maxLendbillno.length()==14){
					String str = maxLendbillno.substring(10);
					int i =Integer.parseInt(str)+1;
					str = String.format("%04d", i);
					lend_bill_no+=str;
				}else{
					throw new Exception("借出编号异常 :"+maxOutbillno);
				}
				System.out.println(lend_bill_no);
				YdmEquipmentLendlist lendlist = new YdmEquipmentLendlist();
				lendlist.setLend_bill_no(lend_bill_no);
				lendlist.setState("0");
				lendlist.setLend_quantity(detail.getQuantity());
				lendlist.setOut_bill_no(out_bill_no);
				lendlist.setApply_bill_no(apply_bill_no);
				lendlist.setPlan_return_date(oneApply.getPlan_return_date()); // 计划归还日期
				lendlist.setLend_date(sdff.format(new Date()));
				lendlist.setLend_time(new Date());
				lendlist.setLend_dept(oneApply.getApply_dept());
				lendlist.setPlan_return_date(oneApply.getPlan_return_date());
				lendlist.setLend_man(username);// 借出操作人
				lendlist.setObject_no(detail.getObject_no());
				lendlist.setMat_code(Timp_detail.getMat_code());
				lendlist.setMat_name(Timp_detail.getMat_name());
				lendlist.setSrot_code(Timp_detail.getSrot_code());
				lendlist.setSrot_name(Timp_detail.getSrot_name());
				lendlist.setSpec(Timp_detail.getSpec());
				lendlist.setPurc_order_pk(Timp_detail.getPurc_order_pk());
				lendlist.setPurc_order_no(Timp_detail.getPurc_order_no());
				lendlist.setSupplier_no(Timp_detail.getSupplier_no());
				lendlist.setSupplier_name(Timp_detail.getSupplier_name());
				lendlist.setUnit(Timp_detail.getUnit());
				lendlist.setPrice(Timp_detail.getPrice());
				lendlist.setDept_code(Timp_detail.getDept_code());
				lendlist.setStorage_code(Timp_detail.getStorage_code());
				lendlist.setArea(Timp_detail.getArea());
				lendlist.setCreate_man_no(userid);
				lendlist.setCreate_man_name(username);
				lendlist.setCreate_time(new Date());
				this.getMapper(YdmEquipmentLendlistMapper.class).insert(lendlist);
			}
			YdmEquipmentApplylist apply = new YdmEquipmentApplylist();
			apply.setState("2");
			apply.setApply_bill_no(oneApply.getApply_bill_no());
			apply.setGrant_quantity(oneApply.getGrant_quantity()+detail.getQuantity());
			apply.setGrant_dept(dept);
			apply.setGrant_time(new Date());
			apply.setGrant_man(username);
			if (oneApply.getApproval_quantity()==oneApply.getGrant_quantity()+detail.getQuantity()) {
				apply.setState("3");
			}
			this.getMapper(YdmEquipmentOutlistMapper.class).updateApply(apply);
			
			rm.setMsgInfo("出库确认成功!");
			rm.setState("200");
		
		return rm;
	}
	/**
	 * 非计划
	 * 库存查询按钮
	 * [{"object":{"sort_code":"产品分类编码","mat_code":"产品编码","purc_order_no":"采购订单号","supplier_no":"供应商代码"},"startTime":"入库时间","endTime":""}]
	 * @param sum
	 * @return
	 */
	public ResultModel selectDetailUnplan(CommonPage<YdmEquipmentDetail> sum){
		ResultModel rm = new ResultModel();
		try {
			YdmEquipmentDetail detail = sum.getObject();
			if (detail==null) {
				throw new Exception("请传入正确参数。");
			}
			if (detail.getState()==null || "".equals(detail.getState())) {
				detail.setState("0");
			}
			StringBuffer strWhere = new StringBuffer(" where t.state= "+detail.getState());
			
			if (sum.getStartTime()!=null&&!"".equals(sum.getStartTime())&&sum.getEndTime()!=null&&!"".equals(sum.getEndTime())) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date startDate = sdf.parse(sum.getStartTime());
				Date endDate = sdf.parse(sum.getEndTime());
				if (startDate.after(endDate)) {//startDate>endDate
					throw new Exception("开始时间不能大于结束时间。");
				}
				//and to_date(t.OUT_DATE,'yyyy-MM-dd HH24:MI:SS') between to_date('2018-07-02 08:12:33','yyyy-MM-dd HH24:MI:SS') and to_date('2018-07-05 08:12:33','yyyy-MM-dd HH24:MI:SS')
				strWhere.append(" and to_date(t.IN_DATE,'yyyy-MM-dd') between to_date('");
				strWhere.append(sum.getStartTime());
				strWhere.append("','yyyy-MM-dd') and to_date('");
				strWhere.append(sum.getEndTime());
				strWhere.append("','yyyy-MM-dd')");
				
			}
			if (detail.getSrot_code() != null && !"".equals(detail.getSrot_code())) {
				strWhere.append(" and t.srot_code = '" + detail.getSrot_code() +"'");
			}
			if (detail.getMat_code() != null && !"".equals(detail.getMat_code())) {
				strWhere.append(" and t.mat_code = '" + detail.getMat_code() +"'");
			}
			if (detail.getPurc_order_no() != null && !"".equals(detail.getPurc_order_no())) {
				strWhere.append(" and t.purc_order_no like '%" + detail.getPurc_order_no() +"%'");
			}
			if (detail.getSupplier_no() != null && !"".equals(detail.getSupplier_no())) {
				strWhere.append(" and t.supplier_no = '" + detail.getSupplier_no() +"'");
			}
			if (detail.getStorage_code() != null && !"".equals(detail.getStorage_code())) {
				strWhere.append(" and t.STORAGE_CODE = '" + detail.getStorage_code() +"'");
			}

			List<YdmEquipmentDetail> Details = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOneChuKu(strWhere.toString());

			rm.setData(Details);	
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败。");
			e.printStackTrace();
		}
		return rm;
	}
	/**
	 * 非计划
	 * 出库查询按钮
	 * [{"object":{"sort_code":"产品分类编码","mat_code":"产品编码","purc_order_no":"采购订单号","supplier_no":"供应商代码"},"startTime":"出库时间","endTime":""}]
	 * @param sum
	 * @return
	 */
	public ResultModel selectOutlistUnplan(CommonPage<YdmEquipmentOutlist> sum){
		ResultModel rm = new ResultModel();
		try {
			YdmEquipmentOutlist outlist = sum.getObject();
			if (outlist==null) {
				throw new Exception("请传入正确参数。");
			}
			StringBuffer whereStr = new StringBuffer();
			if (sum.getStartTime()!=null&&!"".equals(sum.getStartTime())&&sum.getEndTime()!=null&&!"".equals(sum.getEndTime())) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date startDate = sdf.parse(sum.getStartTime());	
				Date endDate = sdf.parse(sum.getEndTime());
				if (startDate.after(endDate)) {//startDate>endDate
					throw new Exception("开始时间不能大于结束时间。");
				}
				if((int) ((endDate.getTime() - startDate.getTime())/(1000*3600*24))>30){
					throw new Exception("开始时间与结束时间差不能大于30天。");
				}else{
					//and to_date(t.OUT_DATE,'yyyy-MM-dd HH24:MI:SS') between to_date('2018-07-02 08:12:33','yyyy-MM-dd HH24:MI:SS') and to_date('2018-07-05 08:12:33','yyyy-MM-dd HH24:MI:SS')
					whereStr.append(" and to_date(t.OUT_DATE,'yyyy-MM-dd HH24:MI:SS') between to_date('");
					whereStr.append(sum.getStartTime());
					whereStr.append("','yyyy-MM-dd HH24:MI:SS') and to_date('");
					whereStr.append(sum.getEndTime());
					whereStr.append("','yyyy-MM-dd HH24:MI:SS')");
				};
			}
			if (outlist.getSrot_code() != null && !"".equals(outlist.getSrot_code())) {
				whereStr.append(" and t.srot_code = '" + outlist.getSrot_code() +"'");
			}
			if (outlist.getMat_code() != null && !"".equals(outlist.getMat_code())) {
				whereStr.append(" and t.mat_code = '" + outlist.getMat_code() +"'");
			}
			if (outlist.getPurc_order_no() != null && !"".equals(outlist.getPurc_order_no())) {
				whereStr.append(" and t.purc_order_no like '%" + outlist.getPurc_order_no() +"%'");
			}
			if (outlist.getSupplier_no() != null && !"".equals(outlist.getSupplier_no())) {
				whereStr.append(" and t.supplier_no = '" + outlist.getSupplier_no() +"'");
			}
			if (outlist.getStorage_code() != null && !"".equals(outlist.getStorage_code())) {
				whereStr.append(" and t.STORAGE_CODE = '" + outlist.getStorage_code() +"'");
			}
			List<YdmEquipmentOutlist> Outlist = this.getMapper(YdmEquipmentOutlistMapper.class).selectOutlistUnplan(whereStr.toString());
			rm.setData(Outlist);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}
	//TODO 资材备件出库撤销(非计划)
		/**
		 * 出库撤销
		 * [{"object":{"out_bill_no":"出库编号","object_no":"库存编号","out_type":"借用出库","quantity":"1","out_date":"出库时间"}}]
		 * @param sum
		 * @return
		 * @throws Exception 
		 */
		@Transactional(value="tm", rollbackFor=Exception.class)
		public ResultModel updateDoOutRevokeUnplan(CommonPage<YdmEquipmentOutlist> sum) throws Exception{
			ResultModel rm = new ResultModel();
			
				YdmEquipmentOutlist outlist = sum.getObject();
				if (outlist==null) {
					throw new Exception("请传入正确参数。");
				}
				if (outlist.getOut_bill_no()==null||"".equals(outlist.getOut_bill_no())) {
					throw new Exception("缺失出库单号。");
				}
				if (outlist.getQuantity()==null) {
					outlist.setQuantity(0d);
				}
				
				// 修改库存信息
				if (outlist.getObject_no()==null||"".equals(outlist.getObject_no())) {
					throw new Exception("出库信息的 库存编号 为空。");
				}
				
				YdmEquipmentDetail detail = new YdmEquipmentDetail();
				detail.setObject_no(outlist.getObject_no());
				
				if (outlist.getOut_type()!=null&&!"".equals(outlist.getOut_type())) {
					if ("500509".equals(outlist.getOut_type())) {
						detail.setState("5");
						List<YdmEquipmentDetail> details = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(detail);
						if (details==null||details.isEmpty()) {
							throw new Exception("数据已更改，没有相关出库记录。");
						}
						details.get(0).setQuantity(details.get(0).getQuantity()==null?0d:details.get(0).getQuantity());
						Double ql = details.get(0).getQuantity()-outlist.getQuantity();
						if (ql.doubleValue()>0) {
							// 修改出库数据
							detail.setQuantity(ql);
							this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(detail);
						}else if (ql.doubleValue()==0) {
							// 删除出库数据
							this.getMapper(YdmEquipmentOutlistMapper.class).deleteDetail(detail);
						}else{
							throw new Exception("库存出库数据异常-5。请联系数据库管理员。");
						}
						detail=details.get(0);
					}else if("500510".equals(outlist.getOut_type())){
						detail.setState("1");
						List<YdmEquipmentDetail> details = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(detail);
						if (details==null||details.isEmpty()) {
							throw new Exception("数据已更改，没有相关借出记录。");
						}
						details.get(0).setQuantity(details.get(0).getQuantity()==null?0d:details.get(0).getQuantity());
						Double ql = details.get(0).getQuantity()-outlist.getQuantity();
						if (ql.doubleValue()>0) {
							// 修改借出数据
							detail.setQuantity(ql);
							this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(detail);
						}else if (ql.doubleValue()==0) {
							// 删除借出数据
							this.getMapper(YdmEquipmentOutlistMapper.class).deleteDetail(detail);
						}else{
							throw new Exception("库存借出数据异常-1。请联系数据库管理员。");
						}
						detail=details.get(0);
						
						YdmEquipmentLendlist lendlist = this.getMapper(YdmEquipmentOutlistMapper.class).selectLendlist(outlist.getOut_bill_no());
						if (lendlist == null) {
							throw new Exception("无法查到对应的借出信息。");
						}else{
							if (lendlist.getState() != null && "1".equals(lendlist.getState())) {
								throw new Exception("改资材已归还。");
							}
						}
						// 删除对应出库编号的借出记录
						this.getMapper(YdmEquipmentOutlistMapper.class).deleteLendlist(outlist.getOut_bill_no());
					}
				}else{
					throw new Exception("出库信息的出库类型为空。");
				}
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				// 维护在库数据
				detail.setState("0");
				List<YdmEquipmentDetail> details = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(detail);
				if (details==null||details.isEmpty()) {
					// 新增对应库存编号&&在库的数据
					// 数量
					detail.setQuantity(outlist.getQuantity());
					// 入库日期
					detail.setIn_date(sdf.format(new Date()));
					this.getMapper(YdmEquipmentDetailMapper.class).insert(detail);
				}else{
					// 修改对应库存编号&&在库的数据
					detail.setQuantity(details.get(0).getQuantity()+outlist.getQuantity());
					this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(detail);
				}
				// 删除对应出库编号的出库记录
				this.getMapper(YdmEquipmentOutlistMapper.class).deleteOutlist(outlist.getOut_bill_no());
				
				rm.setMsgInfo("撤销成功 ! ! !");
				rm.setState("200");
			
			return rm;
		}
		//TODO 资材备件出库确认(非计划)
		/**
		 * 出库确认
		 * [{"object":{"object_no":"KC201807090002","out_type":"借用/领用","quantity":"1","out_date":"2018-07-05","apply_dept":"领用部门","apply_man":"领用人"}}]
		 * @param sum
		 * @return
		 * @throws Exception 
		 */
		@Transactional(value="tm", rollbackFor=Exception.class)
		public ResultModel updateDoOutConfirmUnplan(CommonPage<YdmEquipmentOutlist> sum) throws Exception{
			ResultModel rm = new ResultModel();
			
				String username = (String) this.getSession().getAttribute(
						HomeService.SESSION_USER_NAME);
				if (username==null || "".equals(username.trim())) {
					throw new Exception("登录信息过期,请重新登录!");
				}
				String userid = (String) this.getSession().getAttribute(
					HomeService.SESSION_USER_ID);
				if (userid==null || "".equals(userid)) {
					throw new Exception("登录信息过期,请重新登录!");
				}
				String order = (String) this.getSession().getAttribute(
						HomeService.SESSION_WORK_ORD);
				if (order==null || "".equals(order)) {
					order="0";
				}
				String team = (String) this.getSession().getAttribute(
						HomeService.SESSION_WORK_GRP);
				if (team==null || "".equals(team)) {
					team="0";
				}
				String dept = (String) this.getSession().getAttribute(
						HomeService.SESSION_DEPT_NAME);
				if (dept==null || "".equals(dept)) {
					dept="0";
				}
				YdmEquipmentOutlist detail = sum.getObject();
				if (detail==null) {
					throw new Exception("请传入正确参数!");
				}
				if (detail.getQuantity()==null) {
					throw new Exception("请传入 出库数量 !");
				}
				if (detail.getQuantity()<=0) {
					throw new Exception("出库数量 必须大于 0 !");
				}
				if (detail.getOut_date()==null || "".equals(detail.getOut_date())) {
					throw new Exception("请传入出库日期 !");
				}
				//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				if (detail.getOut_type()==null || "".equals(detail.getOut_type())) {
					throw new Exception("请传入出库类型 !");
				}
				if (detail.getApply_dept() == null || "".equals(detail.getApply_dept())) {
					throw new Exception("请传入领用部门 !");
				}
				if (detail.getApply_man() == null || "".equals(detail.getApply_man())) {
					throw new Exception("请传入领用人 !");
				}
				
				if (detail.getObject_no()==null || "".equals(detail.getObject_no())) {
					throw new Exception("参数缺失 库存编号 !");
				}
				
				
				YdmEquipmentDetail Timp_detail = new YdmEquipmentDetail();
				Timp_detail.setObject_no(detail.getObject_no());
				Timp_detail.setState("0");
				List<YdmEquipmentDetail> selectDetailOne = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(Timp_detail);
				if (selectDetailOne==null || selectDetailOne.isEmpty()) {
					throw new Exception("未找到库存信息，库存信息已更改，请重新查询!");
				}
				Timp_detail=selectDetailOne.get(0);
				Double quantity = Timp_detail.getQuantity();//库存数量
				if (quantity.doubleValue()==0) {
					throw new Exception("当前资材 【 "+detail.getObject_no()+" 】 库存为 0 ,请重新操作!");
				}else if(quantity.doubleValue()<0){
					throw new Exception("库存数量数据异常 -1  请联系数据库管理员。");
				}
				if (detail.getQuantity().doubleValue()>quantity.doubleValue()) {//detail.getQuantity():出库数量
					throw new Exception("库存数量不足，请重新出库 !  库存:【 "+quantity+" 】");
				}
				// 修改库存在库数量
				if (quantity.doubleValue()-detail.getQuantity().doubleValue()>0) {
					Timp_detail.setQuantity(quantity-detail.getQuantity());
					this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(Timp_detail);
				}else if(quantity.doubleValue()-detail.getQuantity().doubleValue()==0){
					// 删除库存编号&&在库的数据
					this.getMapper(YdmEquipmentOutlistMapper.class).deleteDetail(Timp_detail);
				}
				
				if ("500509".equals(detail.getOut_type())) {
					Timp_detail.setState("5");
					List<YdmEquipmentDetail> detailOut = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(Timp_detail);
					if (detailOut==null || detailOut.isEmpty()) {
						// 新增库存出库数据
						Timp_detail.setQuantity(detail.getQuantity());
						this.getMapper(YdmEquipmentDetailMapper.class).insert(Timp_detail);
					}else{
						Timp_detail=detailOut.get(0);
						// 修改库存出库数量
						if (Timp_detail.getQuantity() == null) {
							Timp_detail.setQuantity(0d);
						}
						Timp_detail.setQuantity(Timp_detail.getQuantity()+detail.getQuantity());
						this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(Timp_detail);
					}
				}else if("500510".equals(detail.getOut_type())){
					Timp_detail.setState("1");
					List<YdmEquipmentDetail> detailOut = this.getMapper(YdmEquipmentOutlistMapper.class).selectDetailOne(Timp_detail);
					if (detailOut==null || detailOut.isEmpty()) {
						// 新增库存借出数据
						Timp_detail.setQuantity(detail.getQuantity());
						this.getMapper(YdmEquipmentDetailMapper.class).insert(Timp_detail);
					}else{
						Timp_detail=detailOut.get(0);
						// 修改库存借出数据
						if (Timp_detail.getQuantity() == null) {
							Timp_detail.setQuantity(0d);
						}
						Timp_detail.setQuantity(Timp_detail.getQuantity()+detail.getQuantity());
						this.getMapper(YdmEquipmentOutlistMapper.class).updateDetail(Timp_detail);
					}
				}else{
					throw new Exception("请传入有效的出库类型!");
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				SimpleDateFormat sdff = new SimpleDateFormat("yyyy-MM-dd");
				// 新增出库信息表
				String out_bill_no = "OT";
				out_bill_no+=sdf.format(new Date());
				String maxOutbillno = this.getMapper(YdmEquipmentOutlistMapper.class).selectMaxOutbillno(out_bill_no);
				if (maxOutbillno==null || "".equals(maxOutbillno)) {
					out_bill_no+="0001";
				}else if(maxOutbillno.length()==14){
					String str = maxOutbillno.substring(10);
					int i = Integer.parseInt(str)+1;
					str = String.format("%04d",i);
					out_bill_no+=str;
				}else{
					throw new Exception("出库编号异常 :"+maxOutbillno);
				}
				detail.getOut_type();
				YdmEquipmentOutlist outlist = new YdmEquipmentOutlist();
				outlist.setQuantity(detail.getQuantity());
				outlist.setOut_bill_no(out_bill_no);
				outlist.setApply_bill_no(null);
				outlist.setOut_type(detail.getOut_type());
				outlist.setOut_ord(order);
				outlist.setOut_grp(team);
				outlist.setOut_date(detail.getOut_date());
				outlist.setOpr_time(new Date());
				outlist.setOpr_man(username);
				outlist.setApply_dept(detail.getApply_dept()); // 领用部门
				outlist.setApply_man(detail.getApply_man()); // 领用部门apply_man
				outlist.setObject_no(detail.getObject_no());
				outlist.setMat_code(Timp_detail.getMat_code());
				outlist.setMat_name(Timp_detail.getMat_name());
				outlist.setSrot_code(Timp_detail.getSrot_code());
				outlist.setSrot_name(Timp_detail.getSrot_name());
				outlist.setSpec(Timp_detail.getSpec());
				outlist.setPurc_order_pk(Timp_detail.getPurc_order_pk());
				outlist.setPurc_order_no(Timp_detail.getPurc_order_no());
				outlist.setSupplier_no(Timp_detail.getSupplier_no());
				outlist.setSupplier_name(Timp_detail.getSupplier_name());
				outlist.setUnit(Timp_detail.getUnit());
				outlist.setPrice(Timp_detail.getPrice());
				outlist.setDept_code(Timp_detail.getDept_code());
				outlist.setArea(Timp_detail.getArea());
				outlist.setStorage_code("500206");
				outlist.setCreate_man_no(userid);
				outlist.setCreate_man_name(username);
				outlist.setCreate_time(new Date());
				outlist.setMaintain_bill_no("-");
				this.getMapper(YdmEquipmentOutlistMapper.class).insert(outlist);
				
				if ("500510".equals(detail.getOut_type())) {
					// 新增借出信息表
					String lend_bill_no = "LD";// 借出编号
					lend_bill_no+=sdf.format(new Date());
					// 查询库存里最大编号数据
					String maxLendbillno = this.getMapper(YdmEquipmentOutlistMapper.class).selectMaxLendbillno(lend_bill_no);
					if (maxLendbillno==null || "".equals(maxLendbillno)) {
						lend_bill_no+="0001";
					}else if(maxLendbillno.length()==14){
						String str = maxLendbillno.substring(10);
						int i =Integer.parseInt(str)+1;
						str = String.format("%04d", i);
						lend_bill_no+=str;
					}else{
						throw new Exception("借出编号异常 :"+maxOutbillno);
					}
					YdmEquipmentLendlist lendlist = new YdmEquipmentLendlist();
					lendlist.setLend_bill_no(lend_bill_no);
					lendlist.setLend_quantity(detail.getQuantity());
					lendlist.setState("0");
					lendlist.setOut_bill_no(out_bill_no);
					lendlist.setApply_bill_no(null);
					lendlist.setLend_date(sdff.format(new Date()));
					lendlist.setLend_time(new Date());
					lendlist.setLend_dept(detail.getApply_dept()); // 借出部门
					lendlist.setLend_man(username); // 借出操作人
					lendlist.setLend_quantity(detail.getQuantity());
					lendlist.setObject_no(detail.getObject_no());
					lendlist.setMat_code(Timp_detail.getMat_code()); // 产品编码
					lendlist.setMat_name(Timp_detail.getMat_name()); // 产品名称
					lendlist.setSrot_code(Timp_detail.getSrot_code()); // 产品分类编码
					lendlist.setSrot_name(Timp_detail.getSrot_name()); // 产品分类名称
					lendlist.setSpec(Timp_detail.getSpec()); // 规格
					lendlist.setPurc_order_pk(Timp_detail.getPurc_order_pk());
					lendlist.setPurc_order_no(Timp_detail.getPurc_order_no()); //采购订单号
					lendlist.setSupplier_no(Timp_detail.getSupplier_no()); // 供应商代码
					lendlist.setSupplier_name(Timp_detail.getSupplier_name()); // 供应商名称
					lendlist.setUnit(Timp_detail.getUnit()); // 单位
					lendlist.setPrice(Timp_detail.getPrice()); // 单价
					lendlist.setArea(Timp_detail.getArea()); // 区域
					lendlist.setDept_code(Timp_detail.getDept_code());
					lendlist.setStorage_code(Timp_detail.getStorage_code());
					lendlist.setCreate_man_no(userid);
					lendlist.setCreate_man_name(username);
					lendlist.setCreate_time(new Date());
					this.getMapper(YdmEquipmentLendlistMapper.class).insert(lendlist);
				}
				
				rm.setMsgInfo("出库确认成功。");
				rm.setState("200");
			
			return rm;
		}
		public ResultModel doExportExcel(CommonPage<YdmEquipmentOutlist> cp){
			ResultModel rm = new ResultModel();
			try{
				YdmEquipmentOutlist ydm_out = cp.getObject();
				if (ydm_out==null) {
					rm.setState("500");
					rm.setMsgInfo("请传入正确参数。");
					return rm;
				}
				StringBuffer whereStr = new StringBuffer(" where 1=1");
				if (cp.getStartTime()!=null&&!"".equals(cp.getStartTime())&&cp.getEndTime()!=null&&!"".equals(cp.getEndTime())) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date startDate = sdf.parse(cp.getStartTime());
					Date endDate = sdf.parse(cp.getEndTime());
					if (startDate.after(endDate)) {//startDate>endDate
						rm.setState("500");
						rm.setMsgInfo("开始时间不能大于结束时间");
						return rm;
					}
					else{
						whereStr.append(" and to_date(t.OUT_DATE,'yyyy-MM-dd HH24:MI:SS') between to_date('");
						whereStr.append(cp.getStartTime());
						whereStr.append("','yyyy-MM-dd HH24:MI:SS') and to_date('");
						whereStr.append(cp.getEndTime());
						whereStr.append("','yyyy-MM-dd HH24:MI:SS')");
					};
				}
				if (ydm_out.getSrot_code()!=null&&!"".equals(ydm_out.getSrot_code())) {
					whereStr.append(" and t.Srot_Code = '"+ydm_out.getSrot_code()+"'");
				}
				if (ydm_out.getMat_code()!=null&&!"".equals(ydm_out.getMat_code())) {
					whereStr.append(" and t.Mat_Code = '"+ydm_out.getMat_code()+"'");
				}
				if (ydm_out.getPurc_order_no()!=null&&!"".equals(ydm_out.getPurc_order_no())) {
					whereStr.append(" and t.Purc_Order_No like '%"+ydm_out.getPurc_order_no()+"%'");
				}
				if (ydm_out.getSupplier_no()!=null&&!"".equals(ydm_out.getSupplier_no())) {
					whereStr.append(" and t.Supplier_No = '"+ydm_out.getSupplier_no()+"'");
				}
				if (ydm_out.getOut_type()!=null&&!"".equals(ydm_out.getOut_type())) {
					whereStr.append(" and t.Out_Type = '"+ydm_out.getOut_type()+"'");
				}
				if (ydm_out.getStorage_code() != null && !"".equals(ydm_out.getStorage_code())) {//t.storage_code='v_storage'
					whereStr.append(" and t.storage_code = '"+ydm_out.getStorage_code()+"'");
				}
				List<YdmEquipmentOutlist> list = this.getMapper(YdmEquipmentOutlistMapper.class).selectForOutlist(whereStr.toString());
				//2,设置用户下载路径
				String path = this.getRequest().getServletContext().getRealPath("/")+ "excel" + File.separator;  //临时保存路径
				File dir = new File(path);
				if(!dir.exists()) {
					new File(path).mkdir();
				}
			    generateExcel500206(rm, list, path,cp);
							
				rm.setState("200");
			}
			catch(Exception ex)
			{
				rm.setState("500");
				rm.setMsgInfo("导出失败!");
				ex.printStackTrace();
			}
			return rm;
		}
		private void generateExcel500206(ResultModel rm, List<YdmEquipmentOutlist> list, String path,CommonPage<YdmEquipmentOutlist> cp)
				throws IOException, WriteException, RowsExceededException {
			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+"库出库查询报表";
	    	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));
			
			sheet.mergeCells(14, 0, 14, 1);
			sheet.addCell(new Label(14,0,"出库区域",cellFormat1));	
			
			sheet.mergeCells(15, 0, 15, 1);
			sheet.addCell(new Label(15,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++) {
				//出库日期
				if(list.get(i).getOut_date() != null) {
					sheet.addCell(new Label(0,i+2,list.get(i).getOut_date(),cellFormat));
				}
				//出库类型
				if(list.get(i).getOut_type() != null && !"".equals(list.get(i).getOut_type())) {
					String outtype = "";
					if(list.get(i).getOut_type().equals("500501")) {
						outtype = "生产投料出库";
					} else if(list.get(i).getOut_type().equals("500502")) {
						outtype = "移送出库";
					} else if(list.get(i).getOut_type().equals("500503")) {
						outtype = "盘库出库";
					} else if(list.get(i).getOut_type().equals("500504")) {
						outtype = "退库出库";
					}else if(list.get(i).getOut_type().equals("500505")) {
					    outtype = "发运出库";
				    }else if(list.get(i).getOut_type().equals("500506")) {
					    outtype = "调拨出库";
				    }else if(list.get(i).getOut_type().equals("500507")) {
					    outtype = "包装出库";
				    }else if(list.get(i).getOut_type().equals("500508")) {
					    outtype = "退库出库";
				    }else if(list.get(i).getOut_type().equals("500509")) {
					    outtype = "领用出库";
				    }else if(list.get(i).getOut_type().equals("500510")) {
					    outtype = "借用出库";
				    }else if(list.get(i).getOut_type().equals("500511")) {
					    outtype = "维修出库";
				    }
					sheet.addCell(new Label(1,i+2,outtype,cellFormat));
				}			
				//产品分类
				if(list.get(i).getSrot_name() != null && !"".equals(list.get(i).getSrot_name())) {
					sheet.addCell(new Label(2,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(3,i+2,list.get(i).getMat_name(),cellFormat));
				}		
				//规格
				if(list.get(i).getSpec() != null && !"".equals(list.get(i).getSpec())) {
					sheet.addCell(new Label(4,i+2,list.get(i).getSpec(),cellFormat));
				}
				//供应商
				if(list.get(i).getSupplier_name() != null && !"".equals(list.get(i).getSupplier_name())) {
					sheet.addCell(new Label(5,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(6,i+2,""+list.get(i).getPurc_order_no(),cellFormat));
				}
				//数量
				if(list.get(i).getQuantity() != null) {
					sheet.addCell(new Label(7,i+2,""+list.get(i).getQuantity(),cellFormat));
				}
				//单位
				if(list.get(i).getUnit() != null && !"".equals(list.get(i).getUnit())) {
					sheet.addCell(new Label(8,i+2,list.get(i).getUnit(),cellFormat));
				}
				//单价
				if(list.get(i).getPrice() != null) {
					sheet.addCell(new Label(9,i+2,list.get(i).getPrice().toString(),cellFormat));
				}
				//金额
				if(list.get(i).getPrice() != null && list.get(i).getQuantity() != null) {
					sheet.addCell(new Label(10,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).getApply_dept() != null && !"".equals(list.get(i).getApply_dept())) {
					sheet.addCell(new Label(11,i+2,list.get(i).getApply_dept(),cellFormat));
				}
				//机台
				if(list.get(i).getMachine_name() != null && !"".equals(list.get(i).getMachine_name())) {
					sheet.addCell(new Label(12,i+2,list.get(i).getMachine_name(),cellFormat));
				}
				//领用人
				if(list.get(i).getApply_man() != null && !"".equals(list.get(i).getApply_man())) {
					sheet.addCell(new Label(13,i+2,list.get(i).getApply_man(),cellFormat));
				}
				//出库区域
				if(list.get(i).getArea() != null && !"".equals(list.get(i).getArea())){
					sheet.addCell(new Label(14,i+2,list.get(i).getArea(),cellFormat));
				}
				//出库操作人
				if(list.get(i).getOpr_man() != null && !"".equals(list.get(i).getOpr_man())){
					sheet.addCell(new Label(15,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(10,list.size()+2,""+df.format(totalMoney),cellFormat));
			
			sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
			sheet.getSettings().setVerticalFreeze(2);
			//关闭
			workbook.write();
			workbook.close();
			
			rm.setData("/download?filename="+file);
		}
		
}
