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

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.List;

import market.Com.mapper.ComBaseInfoMapper;
import market.Com.vo.ComBaseInfo;
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.mapper.YdmEquipmentOutlistMapper;
import market.Lms.Equipment.service.YdmEquipmentDetailService;
import market.Lms.Equipment.vo.YdmEquipmentDetail;
import market.Lms.Equipment.vo.YdmEquipmentInlist;
import market.Lms.Equipment.vo.YdmEquipmentOutlist;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Pms.Mat.mapper.PurMatClassMapper;
import market.Pms.Mat.mapper.PurMatMMapper;
import market.Pms.Mat.vo.PurMatClass;
import market.Pms.Mat.vo.PurMatM;
import market.Pms.Order.vo.PurOrderC;
import market.Pms.Util.ImportUtil;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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;
import com.ibm.icu.text.SimpleDateFormat;

@RemoteService(path = "YdmEquipmentDetailService")
public class YdmEquipmentDetailServiceImpl extends BaseServiceImpl<YdmEquipmentDetail, Object> implements YdmEquipmentDetailService {

	/**
	 * 查询数据
	 * 
	 * @return
	 */
	public ResultModel doQueryWeb(CommonPage<YdmEquipmentDetail> sum) {
		ResultModel rm = new ResultModel();		
		try {			
			if (sum.getObject() != null) {
				rm.setData(this.getMapper(YdmEquipmentDetailMapper.class)
						.doquery(sum.getStartTime(), sum.getEndTime(),
								sum.getObject().getSrot_code(),
								sum.getObject().getMat_code(),
								sum.getObject().getPurc_order_no(),
								sum.getObject().getSupplier_no(),
								sum.getObject().getState(),
								sum.getObject().getStorage_code(),
								sum.getObject().getSet_reg()));
				rm.setState("200");
				rm.setMsgInfo("查询成功！");
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 新增库存
	 * 
	 * @return
	 */
	public ResultModel doAdd(CommonPage<YdmEquipmentDetail> sum) {
		ResultModel rm = new ResultModel();
		// PageModel<YdmEquipmentDetail> pm = new
		// PageModel<YdmEquipmentDetail>(pageIndex,pageSize);
		try {
			if (sum == null || sum.getObject() == null) {
				throw new Exception("参数格式错误!");
			}
			if (sum.getObject().getQuantity() == null) {
				throw new Exception("请传入要盘入的数量。");
			}
			//YdmEquipmentDetail detail2 = sum.getObject();
			String object_no = sum.getObject().getObject_no();
			//String state = sum.getObject().getState();
			
			YdmEquipmentDetail ydm = new YdmEquipmentDetail();
			ydm.setObject_no(object_no);
			
			List<YdmEquipmentDetail> list = this.getMapper(
					YdmEquipmentDetailMapper.class).find(ydm, 0, 0);
			
			ydm.setState("0");
			List<YdmEquipmentDetail> li = this.getMapper(
					YdmEquipmentDetailMapper.class).find(ydm, 0, 0);
			if (object_no != null && list != null && list.size() > 0) {
				if (li != null && li.size() > 0) {
					YdmEquipmentDetail detail = li.get(0);
					detail.setQuantity(detail.getQuantity()
							+ sum.getObject().getQuantity());
					this.getMapper(YdmEquipmentDetailMapper.class).update(
							detail);
				} else {
					this.getMapper(YdmEquipmentDetailMapper.class).insert(
							sum.getObject());
				}
			} else {
				String code = this.getMapper(YdmEquipmentDetailMapper.class).getCode("KC"+ new SimpleDateFormat("yyyyMMdd").format(new Date()));
				YdmEquipmentDetail object = sum.getObject();
				object.setObject_no(code);
				this.getMapper(YdmEquipmentDetailMapper.class).insert(object);
			}
			// rm.setData(pm);
			rm.setState("200");
			rm.setMsgInfo("新增成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 新增入库信息
	 * 
	 * @return
	 */
	public ResultModel doAddIn(CommonPage<YdmEquipmentInlist> sum) {
		ResultModel rm = new ResultModel();
		//int pageIndex = sum.getPageIndex();
		//int pageSize = sum.getPageSize();
		try {
			String v_man = (String) this.getSession().getAttribute(
					HomeService.SESSION_USER_NAME);
			String v_group = (String) this.getSession().getAttribute(
					HomeService.SESSION_WORK_GRP);
			String v_ord = (String) this.getSession().getAttribute(
					HomeService.SESSION_WORK_ORD);
			YdmEquipmentInlist object = sum.getObject();
			object.setIn_grp(v_group);
			object.setIn_ord(v_ord);
			object.setOpr_man(v_man);
			String max = this.getMapper(YdmEquipmentDetailMapper.class)
					.GetMax();
			object.setIn_bill_no(max);
			object.setIn_type("500402"); // 盘库入库
			this.getMapper(YdmEquipmentInlistMapper.class).insert(object);
			rm.setState("200");
			rm.setMsgInfo("新增成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 盘出库存
	 * 
	 * @return
	 */
	public ResultModel doAddOut(CommonPage<YdmEquipmentDetail> sum) {
		ResultModel rm = new ResultModel();
		// PageModel<YdmEquipmentDetail> pm = new
		// PageModel<YdmEquipmentDetail>(pageIndex,pageSize);
		try {
			YdmEquipmentDetail object = sum.getObject();
			String object_no = object.getObject_no();
			YdmEquipmentDetail ydm = new YdmEquipmentDetail();
			ydm.setObject_no(object_no);
			ydm.setState("0");
			List<YdmEquipmentDetail> list = this.getMapper(
					YdmEquipmentDetailMapper.class).find(ydm, 0, 0);
			if (list != null && list.size() > 0) {
				YdmEquipmentDetail equipmentDetail = list.get(0);
				if (object.getQuantity() > equipmentDetail.getQuantity()) {
					rm.setState("500");
					rm.setMsgInfo("盘出数量大于库存数量!");
					return rm;
				}
				if (equipmentDetail.getQuantity() == 0) {
					this.getMapper(YdmEquipmentDetailMapper.class).delete(
							equipmentDetail);
				}
				equipmentDetail.setQuantity(equipmentDetail.getQuantity()
						- object.getQuantity());
				this.getMapper(YdmEquipmentDetailMapper.class).update(
						equipmentDetail);
			}
			ydm.setState("5");
			List<YdmEquipmentDetail> li = this.getMapper(
					YdmEquipmentDetailMapper.class).find(ydm, 0, 0);
			if (li != null && li.size() > 0) {
				YdmEquipmentDetail equipmentDetail = li.get(0);
				equipmentDetail.setQuantity(equipmentDetail.getQuantity()
						+ object.getQuantity());
				this.getMapper(YdmEquipmentDetailMapper.class).update(
						equipmentDetail);
			} else {
				this.getMapper(YdmEquipmentDetailMapper.class).insert(object);
			}

			rm.setState("200");
			rm.setMsgInfo("盘出成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 盘出出库信息
	 * 
	 * @return
	 */
	public ResultModel doAddOutl(CommonPage<YdmEquipmentOutlist> sum) {
		ResultModel rm = new ResultModel();
		//int pageIndex = sum.getPageIndex();
		//int pageSize = sum.getPageSize();
		try {
			String v_man = (String) this.getSession().getAttribute(
					HomeService.SESSION_USER_NAME);
			String v_group = (String) this.getSession().getAttribute(
					HomeService.SESSION_WORK_GRP);
			String v_ord = (String) this.getSession().getAttribute(
					HomeService.SESSION_WORK_ORD);
			YdmEquipmentOutlist object = sum.getObject();
			object.setOut_grp(v_group);
			object.setOut_ord(v_ord);
			object.setOpr_man(v_man);
			String max = this.getMapper(YdmEquipmentDetailMapper.class)
					.GetOut();
			object.setOut_bill_no(max);
			ComBaseInfo c = new ComBaseInfo();
			c.setBase_name("出库类型");
			List<ComBaseInfo> list = this.getMapper(ComBaseInfoMapper.class)
					.find(c, 0, 0);
			object.setOut_type(list.get(0).getBase_code());
			this.getMapper(YdmEquipmentOutlistMapper.class).insert(object);
			rm.setState("200");
			rm.setMsgInfo("盘出成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("盘出失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 备件库库存查询
	 * 
	 * @return
	 */
	public ResultModel doQueryEquipmentWeb(CommonPage<YdmEquipmentDetail> sum) {		
		ResultModel rm = new ResultModel();		
		try {			
			if (sum.getObject() != null) {
				rm.setData(this.getMapper(YdmEquipmentDetailMapper.class)
						.doquery(sum.getStartTime(), sum.getEndTime(),
								sum.getObject().getSrot_code(),
								sum.getObject().getMat_code(),
								sum.getObject().getPurc_order_no(),
								sum.getObject().getSupplier_no(),
								sum.getObject().getState(),
								sum.getObject().getStorage_code(),
								sum.getObject().getSet_reg()));
				rm.setState("200");
				rm.setMsgInfo("查询成功！");
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 资材备件库--堆放区域调整
	 * 
	 * @param "memo1":"数量","memo2":"库存编码"
	 * @rerutn
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doChangeWeb(CommonPage<YdmEquipmentDetail> sum)
			throws Exception {
		ResultModel rm = new ResultModel();
		if (sum.getObject() == null) {
			throw new Exception("请传入参数！");
		}
		YdmEquipmentDetail yed = sum.getObject();
		String quantity = sum.getMemo1();
		if (quantity == null || quantity.equals("")) {
			throw new Exception("请传入数量！");
		}
		String object_no = sum.getMemo2(); // 获取原来库存编码
		// 判断原库存编码对应的产品是否在库
		YdmEquipmentDetail t = new YdmEquipmentDetail();
		t.setObject_no(object_no);
		t.setState("0");
		int ct = this.getMapper(YdmEquipmentDetailMapper.class).count(t);
		if (ct == 0) {
			throw new Exception("请选择在库状态的数据进行操作！");
		}
		if (object_no == null || object_no.equals("")) {
			throw new Exception("请传入库存编码！");
		}
		Double count = Double.valueOf(quantity);
		// 判断是否存在相同的产品的库存编码
		List<YdmEquipmentDetail> list = this.getMapper(
				YdmEquipmentDetailMapper.class).findWithCondition(yed, null,
				null, 0, 0);

		if (list.size() > 0) {

			YdmEquipmentDetail yed1 = new YdmEquipmentDetail();
			yed1.setObject_no(list.get(0).getObject_no());
			yed1.setState("0");
			list = this.getMapper(YdmEquipmentDetailMapper.class).find(yed1, 0,
					0); // 判断是否存在该库存编码在库的数据
			if (list.size() > 0) {
				YdmEquipmentDetail tmp = list.get(0);
				System.out.println(tmp);
				tmp.setQuantity(count + tmp.getQuantity());
				this.getMapper(YdmEquipmentDetailMapper.class)
						.doUpdateQuantity(tmp); // 更新该库存编码在库数据数量
			} else {
				String ymd = new SimpleDateFormat("yyyyMMdd")
						.format(new Date()); // 开始计算库存编号
				int lsh = this.getMapper(YdmEquipmentDetailMapper.class)
						.findMaxObject_no(); // 流水号生产
				yed.setObject_no("KC" + ymd + String.format("%04d", lsh)); // 库存编号
				yed.setState("0");
				yed.setQuantity(count);
				this.getMapper(YdmEquipmentDetailMapper.class).insert(yed); // 库存表新增记录
			}
		} else {
			String ymd = new SimpleDateFormat("yyyyMMdd").format(new Date()); // 开始计算库存编号
			int lsh = this.getMapper(YdmEquipmentDetailMapper.class)
					.findMaxObject_no(); // 流水号生产
			yed.setObject_no("KC" + ymd + String.format("%04d", lsh)); // 库存编号
			yed.setState("0");
			yed.setQuantity(count);
			this.getMapper(YdmEquipmentDetailMapper.class).insert(yed); // 库存表新增记录
		}
		YdmEquipmentDetail yed2 = new YdmEquipmentDetail();
		yed2.setObject_no(object_no);
		yed2.setState("0");
		list = this.getMapper(YdmEquipmentDetailMapper.class).find(yed2, 0, 0);
		yed2 = list.get(0);
		yed2.setQuantity(yed2.getQuantity() - count);
		if (yed2.getQuantity() < 0) {
			throw new Exception("调整数量超过该库存编号库存在库数量！");
		} else if (yed2.getQuantity() == 0) {
			this.getMapper(YdmEquipmentDetailMapper.class).doDelete(yed2); // 删除原来库存信息
		} else {
			this.getMapper(YdmEquipmentDetailMapper.class).doUpdateQuantity(
					yed2); // 更新原来库存信息
		}
		rm.setState("200");
		rm.setMsgInfo("区域调整成功！");
		return rm;
	}

	/**
	 * 资材备件-区域调整-库存查询（不分页）
	 * 
	 * @param
	 * @return
	 */
	public ResultModel doQueryChangeWeb(CommonPage<YdmEquipmentDetail> sum) {
		ResultModel rm = new ResultModel();
		YdmEquipmentDetail yed = sum.getObject() != null ? sum.getObject()
				: new YdmEquipmentDetail();
		String swhere = "1=1";
		try {
			if (sum.getStartTime() != null && !"".equals(sum.getStartTime())) {
				swhere += " and in_date  >= '" + sum.getStartTime() + "'";
			}
			if (sum.getEndTime() != null && !"".equals(sum.getEndTime())) {
				swhere += " and in_date  <= '" + sum.getEndTime() + "'";
			}
			if (yed.getPurc_order_no() != null
					&& !"".equals(yed.getPurc_order_no().trim())) {
				swhere += "and purc_order_no like '%" + yed.getPurc_order_no()
						+ "%'";
			}
			if(yed.getStorage_code() != null && !"".equals(yed.getStorage_code())){
				swhere += "and storage_code = '"+yed.getStorage_code()+"'";
			}
			yed.setPurc_order_no(null);
			rm.setData(this.getMapper(YdmEquipmentDetailMapper.class)
					.findWithCondition(yed, swhere, null, 0, 0));
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			e.getStackTrace();
			rm.setMsgInfo("查询失败！" + e.getMessage());
		}
		return rm;
	}

	/**
	 * 入库管理--入库确认 1.判断库存中是否存在相同产品的库存编码
	 * 
	 * @param[{"object":{"mat_code":"产品编码","mat_name":"产品名称","srot_name":"产品分类名称","srot_code":"产品分类编码","supplier_no":"供应商代码","supplier_name":"供应商名称","quantity":"数量","spec":"规格","purc_order_no":"采购订单号","purc_order_pk":"采购订单PK","unit":"单位","price":"单价","in_date":"入库日期","area":"库存区域","storage_code":"v_storage" 
	 *                                                                                                                                                                                                                                                                                                               ]
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddYdmEi(CommonPage<YdmEquipmentDetail> cp) throws Exception {
		ResultModel rm = new ResultModel();
		if (cp != null && cp.getObject() != null
				&& cp.getObject().getMat_code() != null
				&& !"".equals(cp.getObject().getMat_code())
				&& cp.getObject().getSrot_code() != null
				&& !"".equals(cp.getObject().getSrot_code())
				&& cp.getObject().getSpec() != null
				&& !"".equals(cp.getObject().getSpec())
				&& cp.getObject().getSupplier_no() != null
				&& !"".equals(cp.getObject().getSupplier_no())
				&& cp.getObject().getUnit() != null
				&& !"".equals(cp.getObject().getUnit())
				&& cp.getObject().getPrice() != null
				&& !"".equals(cp.getObject().getPrice())
				&& cp.getObject().getIn_date() != null
				&& !"".equals(cp.getObject().getIn_date())
				&& cp.getObject().getArea() != null
				&& !"".equals(cp.getObject().getArea())
				&& cp.getObject().getStorage_code() != null
				&& !"".equals(cp.getObject().getStorage_code())) {
			if(cp.getObject().getPurc_order_no() != null && !"".equals(cp.getObject().getPurc_order_no())){
				List<PurOrderC> list = this.getMapper(YdmEquipmentDetailMapper.class).doQuerypur(cp.getObject().getPurc_order_no(),cp.getObject().getMat_code());
				if(list.size()>0){
					if(cp.getObject().getQuantity()>(Integer.parseInt(list.get(0).getUse_qty()))){
						rm.setState("500");
						rm.setMsgInfo("该采购单可入库数量小于"+cp.getObject().getQuantity()+",不能入库");
						return rm;
					}
				}
			}
			// 获取对象
			YdmEquipmentDetail yed = cp.getObject();
			List<YdmEquipmentDetail> ydmEiList = this.getMapper(YdmEquipmentDetailMapper.class).doQueryYdmEd(yed);
			// 定义库存编号
			String objectNo = null;

			if (ydmEiList != null && ydmEiList.size() > 0) {
				// 获得该库存对象
				YdmEquipmentDetail ydm = ydmEiList.get(0);
				// 获取库存编号
				objectNo = ydm.getObject_no();
				if (objectNo != null && !"".equals(objectNo)) {
					// 存在库存编号
					// 获取在库状态
					String state = ydm.getState();
					if ("0".equals(state)) {
						// 修改库存信息表（YDM_EQUIPMENT_DETAIL）中对应库存编号&&在库的数据，数量(QUANTITY)
						// += 数量;
						this.getMapper(YdmEquipmentDetailMapper.class).doUpdateYdmEd(yed, objectNo, state);
					} else {
						yed.setState("0");
						yed.setObject_no(objectNo);
						// 在库存信息表（YDM_EQUIPMENT_DETAIL）中，新增对应库存编号&&在库的数据
						this.getMapper(YdmEquipmentDetailMapper.class).insert(yed);
					}
				}

			} else {
				// 没有需要新增 新增库存编号，库存编号生成规则 KC+'yyyyMMdd'+4位流水
				// 在库存信息表（YDM_EQUIPMENT_DETAIL）中，新增对应库存编号&&在库的数据
				String code = this.getMapper(YdmEquipmentDetailMapper.class).getCode("KC"+ new SimpleDateFormat("yyyyMMdd").format(new Date()));
				objectNo = code;
				yed.setObject_no(objectNo);
				yed.setState("0");
				this.getMapper(YdmEquipmentDetailMapper.class).insert(yed);
			}
			// 获取入库编号
			String in_bill_no = this.getMapper(YdmEquipmentInlistMapper.class).getCode("IN"+ new SimpleDateFormat("yyyyMMdd").format(new Date()));
			String v_man = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			String v_group = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
			String v_ord = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
			// 库存编号
			/*
			 * String code = this.getMapper(YdmEquipmentDetailMapper.class)
			 * .getCode();
			 */
			YdmEquipmentInlist ydmEi = new YdmEquipmentInlist();
			ydmEi.setIn_grp(v_group);
			ydmEi.setIn_ord(v_ord);
			ydmEi.setOpr_man(v_man);			
			ydmEi.setIn_bill_no(in_bill_no);// 设置入库编号			
			ydmEi.setObject_no(objectNo);// 设置库存编号
			ydmEi.setOpr_time(new Date());// 设置入库操作时间
			ydmEi.setStorage_code(yed.getStorage_code());// 设置所属仓库编码
			ydmEi.setUp_flag("0");// 设置上传标志		
			ydmEi.setSrot_code(yed.getSrot_code());// 设置产品分类
			ydmEi.setSrot_name(yed.getSrot_name());			
			ydmEi.setMat_code(yed.getMat_code());// 设置产品名称
			ydmEi.setMat_name(yed.getMat_name());			
			ydmEi.setSpec(yed.getSpec());// 设置规格			
			ydmEi.setQuantity(yed.getQuantity());// 设置数量			
			ydmEi.setUnit(yed.getUnit());// 设置单位			
			ydmEi.setPrice(yed.getPrice());// 设置单价			
			ydmEi.setPurc_order_no(yed.getPurc_order_no());// 采购订单号			
			ydmEi.setSupplier_name(yed.getSupplier_name());// 供应商
			ydmEi.setSupplier_no(yed.getSupplier_no());			
			ydmEi.setArea(yed.getArea());// 堆放区域			
			ydmEi.setIn_date(yed.getIn_date());// 入库日期			
			ydmEi.setIn_type("500408");// 入库类型编码			
			ydmEi.setPurc_order_pk(yed.getPurc_order_pk());// 采购订单PK
			this.getMapper(YdmEquipmentInlistMapper.class).insert(ydmEi);
			rm.setState("200");
			rm.setMsgInfo("插入数据成功！");
		} else {
			rm.setState("500");
			rm.setMsgInfo("参数错误！");
		}
		return rm;
	}
	
	/**
	 * 结算按钮——查询
	 * @param cp [{"object":{"set_reg":""}}]
	 * @return
	 */
	public ResultModel selectSetReg(CommonPage<YdmEquipmentDetail> cp){
		ResultModel rm = new ResultModel();
		try {
			if (cp.getObject() != null && cp.getObject().getSet_reg() != null) {
				List<YdmEquipmentDetail> findSetReg = this.getMapper(YdmEquipmentDetailMapper.class).findWithCondition(cp.getObject(), "".equals(cp.getObject().getSet_reg().trim())?null:"set_reg = "+cp.getObject().getSet_reg().trim(), "in_date desc", 0, 0);
				if ((findSetReg == null || findSetReg.isEmpty()) && "0".equals(cp.getObject().getSet_reg().trim())) {
					rm.setMsgInfo("当前已没有未结算的库存数据 !");
					rm.setState("200");
				}else if((findSetReg == null || findSetReg.isEmpty()) && "1".equals(cp.getObject().getSet_reg().trim())){
					rm.setMsgInfo("当前已没有已结算的库存数据 !");
					rm.setState("200");
				}else if(findSetReg == null || findSetReg.isEmpty()){
					rm.setMsgInfo("没有数据 !");
					rm.setState("200");
				}
				for (YdmEquipmentDetail y : findSetReg) {
					y.setSet_reg("0".equals(y.getSet_reg().trim()) ? "未结算" : "已结算"); // 0未结算 1已结算
				}
				rm.setData(findSetReg);
			}else{
				rm.setMsgInfo("参数错误。");
				rm.setState("500");
			}
		} catch (Exception e) {
			rm.setMsgInfo(e.getMessage());
			rm.setState("500");
		}
		return rm;
	}
	
	/**
	 * 结算按钮——修改
	 * @param cp 
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel updateSetReg(CommonPage<YdmEquipmentDetail> cp) throws Exception{
		ResultModel rm = new ResultModel();
		
		if (cp.getObjectList() == null) {
			throw new Exception("参数错误");
		}
		List<YdmEquipmentDetail> objectList = cp.getObjectList();
		if (objectList.isEmpty()) {
			throw new Exception("请选择至少一条数据进行操作");
		}
		
		for (YdmEquipmentDetail y : objectList) {
			if (y.getSet_reg() == null || "".equals(y.getSet_reg().trim())) {
				throw new Exception("请求数据异常  Set_reg is null");
			}else if("1".equals(y.getSet_reg().trim())){
				throw new Exception("请选择未结算的数据进行操作");
			}else if("0".equals(y.getSet_reg().trim())){
				if (y.getObject_no() != null && !"".equals(y.getObject_no().trim())) {
					List<YdmEquipmentDetail> temp = this.getMapper(YdmEquipmentDetailMapper.class).find(y, 0, 0);
					if (temp == null || temp.isEmpty()) {
						throw new Exception("数据已更改，请重新查询再操作");
					}
					y.setSet_reg("1");
					this.getMapper(YdmEquipmentDetailMapper.class).updateSetReg(y);
				}else{
					throw new Exception("请求数据异常  Object_no is null");
				}
			}else {
				throw new Exception("请传入正确的结算状态");
			}
		}
		
		rm.setMsgInfo("操作成功");
		rm.setState("200");
		return rm;
	}
	/**
	 * 结算按钮——撤销
	 * @param cp 
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel updateSetRegRevoke(CommonPage<YdmEquipmentDetail> cp) throws Exception{
		ResultModel rm = new ResultModel();
		
		if (cp.getObjectList() == null) {
			throw new Exception("参数错误");
		}
		List<YdmEquipmentDetail> objectList = cp.getObjectList();
		if (objectList.isEmpty()) {
			throw new Exception("请选择至少一条数据进行操作");
		}
		
		for (YdmEquipmentDetail y : objectList) {
			if (y.getSet_reg() == null || "".equals(y.getSet_reg().trim())) {
				throw new Exception("请求数据异常  Set_reg is null");
			}else if("0".equals(y.getSet_reg().trim())){
				throw new Exception("请选择已结算的数据进行操作");
			}else if("1".equals(y.getSet_reg().trim())){
				if (y.getObject_no() != null && !"".equals(y.getObject_no().trim())) {
					List<YdmEquipmentDetail> temp = this.getMapper(YdmEquipmentDetailMapper.class).find(y, 0, 0);
					if (temp == null || temp.isEmpty()) {
						throw new Exception("数据已更改，请重新查询再操作");
					}
					y.setSet_reg("0");
					this.getMapper(YdmEquipmentDetailMapper.class).updateSetReg(y);
				}else{
					throw new Exception("请求数据异常  Object_no is null");
				}
			}else {
				throw new Exception("请传入正确的结算状态");
			}
		}
		
		rm.setMsgInfo("操作成功");
		rm.setState("200");
		return rm;
	}


	/**
	 * 资材备件--生产--库存查询(财务) 查询
	 * @return
	 */
	public ResultModel doQueryWebStock(CommonPage<YdmEquipmentDetail> sum) {
		ResultModel rm = new ResultModel();		
		try {			
			if (sum.getObject() != null) {
				rm.setData(this.getMapper(YdmEquipmentDetailMapper.class)
						.doqueryStock(sum.getStartTime(), sum.getObject().getSrot_code(),
								sum.getObject().getMat_code(),
								sum.getObject().getSupplier_no(),
								sum.getObject().getStorage_code()));
				rm.setState("200");
				rm.setMsgInfo("查询成功！");
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}



	/**
	 * 资材备件导入文件进行入库
	 * @return
	 * @throws Exception
	 */
	public ResultModel doImportYdmEquipmentDetail() throws Exception{
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		synchronized (this) {
			ResultModel rm = new ResultModel();
			Workbook wb = null;
			URL url = this.getClass().getClassLoader().getResource("/");
	        // 替换路径中的空格
	        String filePath = url.getPath().replaceAll("%20", " ");
	        File file = new File(filePath);
	        
	        //1.导入excel
	        try {
				List<FileItem> items = ImportUtil.getUpload(YdmEquipmentDetailServiceImpl.this,file,getRequest());
				for (FileItem item : items) {
					// 若是文件域则读取文件流
					if (!item.isFormField()) {
						wb = ImportUtil.getWB(item, file.length());
					}
				}
				rm.setState("200");
				rm.setMsgInfo("文件读取成功！");
			} catch (FileUploadException e) {
				rm.setState("500");
				rm.setMsgInfo("文件读取失败！");
			}
	        System.out.println("文件读取成功！");
	        
	        // 2.读取Excel数据
			try {
				//第一个表单
				Sheet sheet = wb.getSheetAt(0);
				//行数
				int numRow = sheet.getLastRowNum();//最后的行数
				if (numRow >= 1) {
					String order = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
					String team = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
					String work_date =  (String) this.getSession().getAttribute(HomeService.SESSION_WORK_TIME);
					work_date = work_date.substring(0, 10);//2020-04-27
					String supplier_no = "P00001";//供应商
					String supplier_name = "新余钢铁股份有限公司";
					
					//从第2行开始读取
					StringBuffer sb = new StringBuffer();
					for (int i = 1; i <= numRow; i++) {
						Row row = sheet.getRow(i);
						String spec = ImportUtil.getCellValue(row.getCell(7));			//规格
						String unit = String.valueOf(row.getCell(8).getStringCellValue());//单位 
						Double num = row.getCell(10).getNumericCellValue();//数量
						if (num <= 0) {
							continue;//实发数量不超0，直接读取下一条
						}
						Double price = row.getCell(12).getNumericCellValue();//单价
						String mat_class_name = ImportUtil.getCellValue(row.getCell(16));//产品分类
						mat_class_name = mat_class_name.substring(mat_class_name.indexOf("】")+1);// 【2126】油漆试剂
						String condition = "mat_class_name = '"+mat_class_name+"'";
						List<PurMatClass> pmcList = this.getMapper(PurMatClassMapper.class).findWithCondition(null, condition, null, 0, 0);
						if (pmcList==null || pmcList.size()<=0) {
							sb.append("第【"+(i+1)+"】行导入失败，产品分类【"+mat_class_name+"】不存在\r\n");
							continue;
						}
						String mat_class_code = pmcList.get(0).getMat_class_code();//产品分类的编码
						
						String item_name = ImportUtil.getCellValue(row.getCell(6));//产品名称
						item_name = item_name.substring(item_name.indexOf("】")+1);// 【10850280040】碳带
						condition = "mat_class_name = '"+mat_class_name+"' and item_name = '"+item_name+"'";
						List<PurMatM> pmmList = this.getMapper(PurMatMMapper.class).findWithCondition(null, condition, null, 0, 0);
						if (pmmList==null || pmmList.size()<=0) {
							sb.append("第【"+(i+1)+"】行导入失败，产品名称【"+item_name+"】不存在\r\n");
							continue;
						}
						String item_code = pmmList.get(0).getItem_code();
						
						//2. 判断是否库存里面是否存在物料
						YdmEquipmentDetail yed = new YdmEquipmentDetail();
						String kcCode = this.getMapper(YdmEquipmentDetailMapper.class).getCode("KC"+ new SimpleDateFormat("yyyyMMdd").format(now));
						yed.setObject_no(kcCode);
						yed.setMat_code(item_code);
						yed.setMat_name(item_name);
						yed.setSrot_code(mat_class_code);
						yed.setSrot_name(mat_class_name);
						yed.setSpec(spec);
						yed.setSupplier_no(supplier_no);
						yed.setSupplier_name(supplier_name);
						yed.setQuantity(num);
						yed.setUnit(unit);
						yed.setPrice(price);
						yed.setIn_date(work_date);
						yed.setArea("现场");//入库区域
						yed.setState("0");
						yed.setStorage_code("500207");//资材备件生产库   500206资材备件工程库
						this.getMapper(YdmEquipmentDetailMapper.class).insert(yed);
						
						//2.新增入库记录
						String in_bill_no = this.getMapper(YdmEquipmentInlistMapper.class).getCode("IN"+ new SimpleDateFormat("yyyyMMdd").format(now));
						// 库存编号
						YdmEquipmentInlist ydmEi = new YdmEquipmentInlist();
						ydmEi.setIn_grp(team);
						ydmEi.setIn_ord(order);
						ydmEi.setOpr_man(username);			
						ydmEi.setIn_bill_no(in_bill_no);// 设置入库编号			
						ydmEi.setObject_no(kcCode);// 设置库存编号
						ydmEi.setOpr_time(now);// 设置入库操作时间
						ydmEi.setStorage_code(yed.getStorage_code());// 设置所属仓库编码
						ydmEi.setUp_flag("0");// 设置上传标志		
						ydmEi.setSrot_code(yed.getSrot_code());// 设置产品分类
						ydmEi.setSrot_name(yed.getSrot_name());			
						ydmEi.setMat_code(yed.getMat_code());// 设置产品名称
						ydmEi.setMat_name(yed.getMat_name());			
						ydmEi.setSpec(yed.getSpec());// 设置规格			
						ydmEi.setQuantity(yed.getQuantity());// 设置数量			
						ydmEi.setUnit(yed.getUnit());// 设置单位			
						ydmEi.setPrice(yed.getPrice());// 设置单价			
						ydmEi.setPurc_order_no(yed.getPurc_order_no());// 采购订单号			
						ydmEi.setSupplier_name(yed.getSupplier_name());// 供应商
						ydmEi.setSupplier_no(yed.getSupplier_no());			
						ydmEi.setArea(yed.getArea());// 堆放区域			
						ydmEi.setIn_date(yed.getIn_date());// 入库日期			
						ydmEi.setIn_type("500408");// 采购入库		
						ydmEi.setPurc_order_pk(yed.getPurc_order_pk());// 采购订单PK
						this.getMapper(YdmEquipmentInlistMapper.class).insert(ydmEi);	
						//日志
						MesOprLog mol = new MesOprLog("资材备件", "入库管理", "导入", username, opr_time, kcCode, null, null, null, "产品分类:"+mat_class_name+"; 产品名称:"+item_name+"; 数量:"+num+"; 单价:"+price);
						this.getMapper(MesOprLogMapper.class).insert(mol);
					}					
					rm.setState("200");
					rm.setMsgInfo("导入成功");
					rm.setErrorInfo(sb.toString());
				}						
			}catch (Exception e) {
				rm.setState("500");
				rm.setMsgInfo("导入失败！");
			}
			return rm; 			 
		} 	
	}
	
	/**
	 * 资材备件导入文件进行入库
	 * @return
	 * @throws Exception
	 */
	public ResultModel doImportYdmEquipmentInlist() throws Exception{
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		synchronized (this) {
			ResultModel rm = new ResultModel();
			Workbook wb = null;
			URL url = this.getClass().getClassLoader().getResource("/");
	        // 替换路径中的空格
	        String filePath = url.getPath().replaceAll("%20", " ");
	        File file = new File(filePath);
	        
	        //1.导入excel
	        try {
				List<FileItem> items = ImportUtil.getUpload(YdmEquipmentDetailServiceImpl.this,file,getRequest());
				System.out.println("读取文件的大小:"+items.size());
				for (FileItem item : items) {
					// 若是文件域则读取文件流
					if (!item.isFormField()) {
						wb = ImportUtil.getWB(item, file.length());
					}
				}
				rm.setState("200");
				rm.setMsgInfo("文件读取成功！");
			} catch (FileUploadException e) {
				rm.setState("500");
				rm.setMsgInfo("文件读取失败！");
			}
	        
	        // 2.读取Excel数据
	        Sheet sheet = wb.getSheetAt(0);
	        int numRow = sheet.getLastRowNum();//最后的行数
			try {
				//第一个表单
				//行数
				if (numRow >= 2) {
					String order = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
					String team = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
					String work_date =  (String) this.getSession().getAttribute(HomeService.SESSION_WORK_TIME);
					work_date = work_date.substring(0, 10);//2020-04-27
					String supplier_no = "P00039";//供应商
					String supplier_name = "YTGD";
					
					//从第3行开始读取
					StringBuffer sb = new StringBuffer();
					for (int i = 2; i <= numRow; i++) {
						Row row = sheet.getRow(i);
						String spec = ImportUtil.getCellValue(row.getCell(4));			//规格
						String unit = String.valueOf(row.getCell(8).getStringCellValue());//单位 
						Double num = Double.parseDouble(ImportUtil.getCellValue(row.getCell(7)));;//数量
						if (num <= 0) {
							continue;//实发数量不超0，直接读取下一条
						}
						Double price = Double.parseDouble(ImportUtil.getCellValue(row.getCell(9)));//单价
						String mat_class_name = ImportUtil.getCellValue(row.getCell(2));//产品分类
						mat_class_name = mat_class_name.substring(mat_class_name.indexOf("】")+1);// 【2126】油漆试剂
						String condition = "mat_class_name = '"+mat_class_name+"'";
						List<PurMatClass> pmcList = this.getMapper(PurMatClassMapper.class).findWithCondition(null, condition, null, 0, 0);
						if (pmcList==null || pmcList.size()<=0) {
							sb.append("第【"+(i+1)+"】行导入失败，产品分类【"+mat_class_name+"】不存在\r\n");
							continue;
						}
						String mat_class_code = pmcList.get(0).getMat_class_code();//产品分类的编码
						
						String item_name = ImportUtil.getCellValue(row.getCell(3));//产品名称
						item_name = item_name.substring(item_name.indexOf("】")+1);// 【10850280040】碳带
						condition = "mat_class_name = '"+mat_class_name+"' and item_name = '"+item_name+"'";
						List<PurMatM> pmmList = this.getMapper(PurMatMMapper.class).findWithCondition(null, condition, null, 0, 0);
						if (pmmList==null || pmmList.size()<=0) {
							sb.append("第【"+(i+1)+"】行导入失败，产品名称【"+item_name+"】不存在\r\n");
							continue;
						}
						String item_code = pmmList.get(0).getItem_code();
						
						//2. 判断是否库存里面是否存在物料
						YdmEquipmentDetail yed = new YdmEquipmentDetail();
						String kcCode = this.getMapper(YdmEquipmentDetailMapper.class).getCode("KC"+ new SimpleDateFormat("yyyyMMdd").format(now));
						yed.setObject_no(kcCode);
						yed.setMat_code(item_code);
						yed.setMat_name(item_name);
						yed.setSrot_code(mat_class_code);
						yed.setSrot_name(mat_class_name);
						yed.setSpec(spec);
						yed.setSupplier_no(supplier_no);
						yed.setSupplier_name(supplier_name);
						yed.setQuantity(num);
						yed.setUnit(unit);
						yed.setPrice(price);
						yed.setIn_date(work_date);
						yed.setArea("现场");//入库区域
						yed.setState("0");
						yed.setStorage_code("500207");//资材备件生产库   500206资材备件工程库
						this.getMapper(YdmEquipmentDetailMapper.class).insert(yed);
						
						//2.新增入库记录
						String in_bill_no = this.getMapper(YdmEquipmentInlistMapper.class).getCode("IN"+ new SimpleDateFormat("yyyyMMdd").format(now));
						// 库存编号
						YdmEquipmentInlist ydmEi = new YdmEquipmentInlist();
						ydmEi.setIn_grp(team);
						ydmEi.setIn_ord(order);
						ydmEi.setOpr_man(username);			
						ydmEi.setIn_bill_no(in_bill_no);// 设置入库编号			
						ydmEi.setObject_no(kcCode);// 设置库存编号
						ydmEi.setOpr_time(now);// 设置入库操作时间
						ydmEi.setStorage_code(yed.getStorage_code());// 设置所属仓库编码
						ydmEi.setUp_flag("0");// 设置上传标志		
						ydmEi.setSrot_code(yed.getSrot_code());// 设置产品分类
						ydmEi.setSrot_name(yed.getSrot_name());			
						ydmEi.setMat_code(yed.getMat_code());// 设置产品名称
						ydmEi.setMat_name(yed.getMat_name());			
						ydmEi.setSpec(yed.getSpec());// 设置规格			
						ydmEi.setQuantity(yed.getQuantity());// 设置数量			
						ydmEi.setUnit(yed.getUnit());// 设置单位			
						ydmEi.setPrice(yed.getPrice());// 设置单价			
						ydmEi.setPurc_order_no(yed.getPurc_order_no());// 采购订单号			
						ydmEi.setSupplier_name(yed.getSupplier_name());// 供应商
						ydmEi.setSupplier_no(yed.getSupplier_no());			
						ydmEi.setArea(yed.getArea());// 堆放区域			
						ydmEi.setIn_date(yed.getIn_date());// 入库日期			
						ydmEi.setIn_type("500408");// 采购入库		
						ydmEi.setPurc_order_pk(yed.getPurc_order_pk());// 采购订单PK
						this.getMapper(YdmEquipmentInlistMapper.class).insert(ydmEi);						
						//日志
						MesOprLog mol = new MesOprLog("资材备件", "入库管理", "二次导入", username, opr_time, kcCode, null, null, null, "产品分类:"+mat_class_name+"; 产品名称:"+item_name+"; 数量:"+num+"; 单价:"+price);
						this.getMapper(MesOprLogMapper.class).insert(mol);
					}					
					rm.setState("200");
					rm.setMsgInfo("导入成功");
					rm.setErrorInfo(sb.toString());
				}						
			}catch (Exception e) {
				rm.setState("500");
				rm.setMsgInfo("导入失败！");
			}
			return rm; 			 
		} 	
	}
	
}
