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


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import market.Com.mapper.TreeNodeMapper;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Com.vo.TreeNode;
import market.Lms.Equipment.mapper.YdmEquipmentDetailMapper;
import market.Lms.Equipment.mapper.YdmEquipmentInlistMapper;
import market.Lms.Equipment.mapper.YdmEquipmentOutlistMapper;
import market.Lms.Equipment.mapper.YdmEquipmentStocklistMapper;
import market.Lms.Equipment.service.YdmEquipmentStocklistService;
import market.Lms.Equipment.vo.YdmEquipmentDetail;
import market.Lms.Equipment.vo.YdmEquipmentInlist;
import market.Lms.Equipment.vo.YdmEquipmentOutlist;
import market.Lms.Equipment.vo.YdmEquipmentStocklist;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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 = "YdmEquipmentStocklistService")
public class YdmEquipmentStocklistServiceImpl extends
		BaseServiceImpl<YdmEquipmentStocklist, Object> implements
		YdmEquipmentStocklistService {
	/**
	 * 查询数据
	 * 
	 * @return
	 */
	public ResultModel doQueryWeb(CommonPage<YdmEquipmentStocklist> sum) {
		ResultModel rm = new ResultModel();
		// int pageIndex = sum.getPageIndex();
		// int pageSize = sum.getPageSize();
		// PageModel<YdmEquipmentStocklist> pm = new
		// PageModel<YdmEquipmentStocklist>(
		// pageIndex, pageSize);
		try {
			// pm.setRows(this.getMapper(YdmEquipmentStocklistMapper.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().getStock_type());
			// pm.setTotal(this.getMapper(YdmEquipmentStocklistMapper.class)
			// .doquerycount(sum.getStartTime(), sum.getEndTime(),
			// sum.getObject().getSrot_code(),
			// sum.getObject().getMat_code(),
			// sum.getObject().getPurc_order_no(),
			// sum.getObject().getSupplier_no(),
			// sum.getObject().getStock_type()));
			if (sum.getObject() != null) {
				rm.setData(this.getMapper(YdmEquipmentStocklistMapper.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().getStock_type(),
								sum.getObject().getStorage_code()));
				rm.setState("200");
				rm.setMsgInfo("查询成功！");
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 新增盘库信息
	 * 
	 * @return
	 */
	public ResultModel doAddIn(CommonPage<YdmEquipmentStocklist> sum) {
		ResultModel rm = new ResultModel();

		try {
			YdmEquipmentStocklist object = sum.getObject();
			String max = this.getMapper(YdmEquipmentStocklistMapper.class)
					.getCode();
			object.setStock_bill_no(max);
			object.setStock_type("0");
			object.setStock_date(new SimpleDateFormat("yyyy-MM-dd")
					.format(new Date()));
			object.setStorage_code("500206");
			object.setOpr_time(new Timestamp(new Date().getTime()));
			this.getMapper(YdmEquipmentStocklistMapper.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<YdmEquipmentStocklist> sum) {
		ResultModel rm = new ResultModel();
		try {
			YdmEquipmentStocklist object = sum.getObject();
			String max = this.getMapper(YdmEquipmentStocklistMapper.class)
					.getCode();
			object.setStock_bill_no(max);
			object.setStock_type("1");
			this.getMapper(YdmEquipmentStocklistMapper.class).insert(object);
			rm.setState("200");
			rm.setMsgInfo("新增成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("新增失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 盘入操作
	 * 
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDiscIN(CommonPage<YdmEquipmentDetail> sum)
			throws Exception {
		ResultModel rm = new ResultModel();

		String v_man = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);

		String mat_name = sum.getObject().getMat_name();
		if (mat_name == null || "".equals(mat_name)) {
			throw new Exception("选择库存数据时，请进行盘出操作 !");
		}

		if (v_man == null || "".equals(v_man)) {
			throw new Exception("登录信息过期,请重新登录 !");
		}

		String v_group = (String) this.getSession().getAttribute(
				HomeService.SESSION_WORK_GRP);
		String v_ord = (String) this.getSession().getAttribute(
				HomeService.SESSION_WORK_ORD);

		try {
			if (sum == null || sum.getObject() == null) {
				throw new Exception("参数格式错误!");
			}
			if (sum.getObject().getQuantity() == null) {
				throw new Exception("请传入要盘入的数量。");
			}

			List<YdmEquipmentDetail> compare = this.getMapper(
					YdmEquipmentDetailMapper.class).doQueryYdmEd(
					sum.getObject());

			String object_no = "";

			if (compare != null && compare.size() > 0) {
				YdmEquipmentDetail detail = compare.get(0);
				detail.setIn_date(sum.getObject().getIn_date());
				YdmEquipmentDetail tem = new YdmEquipmentDetail();
				tem.setObject_no(detail.getObject_no());
				tem.setState("0");
				object_no = detail.getObject_no();
				List<YdmEquipmentDetail> list = this.getMapper(
						YdmEquipmentDetailMapper.class).find(tem, 0, 0);
				if (list != null && list.size() > 0) { // 存在库存编号存在在库状态的数据，修改
					Double l = detail.getQuantity() == null ? 0d : detail
							.getQuantity();
					detail.setQuantity(l + sum.getObject().getQuantity());
					this.getMapper(YdmEquipmentDetailMapper.class).update(
							detail);
				} else { // 不存在库存编号存在在库状态的数据，要新增
					detail.setState("0");
					detail.setQuantity(sum.getObject().getQuantity());
					this.getMapper(YdmEquipmentDetailMapper.class).insert(
							detail);
				}
			} else {
				String code = this.getMapper(YdmEquipmentDetailMapper.class)
						.getCode("KC"+ new SimpleDateFormat("yyyyMMdd").format(new Date()));
				object_no = code;
				YdmEquipmentDetail object = sum.getObject();
				object.setObject_no(code);
				object.setState("0");
				this.getMapper(YdmEquipmentDetailMapper.class).insert(object);
			}

			YdmEquipmentDetail yed = sum.getObject();
			// 在入库信息表(YDM_EQUIPMENT_INLIST)中新增一条入库记录
			YdmEquipmentInlist object = new YdmEquipmentInlist();
			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"); // 盘库入库
			object.setObject_no(object_no);
			object.setMat_code(yed.getMat_code());
			object.setMat_name(yed.getMat_name());
			object.setSrot_code(yed.getSrot_code());
			object.setSrot_name(yed.getSrot_name());
			object.setSpec(yed.getSpec());
			object.setPurc_order_no(yed.getPurc_order_no());
			object.setPurc_order_pk(yed.getPurc_order_pk());
			object.setSupplier_no(yed.getSupplier_no());
			object.setSupplier_name(yed.getSupplier_name());
			object.setUnit(yed.getUnit());
			object.setPrice(yed.getPrice());
			object.setIn_date(yed.getIn_date());
			object.setArea(yed.getArea());
			object.setStorage_code(yed.getStorage_code());
			object.setQuantity(sum.getObject().getQuantity());
			object.setOpr_time(new Date());

			this.getMapper(YdmEquipmentInlistMapper.class).insert(object);

			// 在盘库信息表(YDM_EQUIPMENT_STOCKLIST)中新增一条盘库记录
			YdmEquipmentStocklist stock = new YdmEquipmentStocklist();
			String stock_max = this
					.getMapper(YdmEquipmentStocklistMapper.class).getCode();
			stock.setStock_bill_no(stock_max);
			stock.setStock_type("0");
			stock.setStock_date(new SimpleDateFormat("yyyy-MM-dd")
					.format(new Date()));
			stock.setOpr_time(new Timestamp(new Date().getTime()));
			stock.setOpr_man(v_man);
			stock.setObject_no(object_no);
			// [{"object":{"mat_code":"产品编码","srot_code":"产品分类编码","spec":"规格","purc_order_no":"采购订单号","purc_order_pk":"采购订单PK","supplier_no":"供应商代码","unit":"单位","price":"单价","in_date":"入库日期","area":"区域":"","storage_code":"所属仓库编码"}}]
			stock.setMat_code(yed.getMat_code());
			stock.setMat_name(yed.getMat_name());
			stock.setSrot_code(yed.getSrot_code());
			stock.setSrot_name(yed.getSrot_name());
			stock.setSpec(yed.getSpec());
			stock.setPurc_order_no(yed.getPurc_order_no());
			stock.setPurc_order_pk(yed.getPurc_order_pk());
			stock.setSupplier_no(yed.getSupplier_no());
			stock.setSupplier_name(yed.getSupplier_name());
			stock.setUnit(yed.getUnit());
			stock.setPrice(yed.getPrice());
			stock.setIn_date(yed.getIn_date());
			stock.setArea(yed.getArea());
			stock.setStorage_code(yed.getStorage_code());
			stock.setQuantity(sum.getObject().getQuantity());

			this.getMapper(YdmEquipmentStocklistMapper.class).insert(stock);

			rm.setData("200");
			rm.setMsgInfo("盘入成功 !");

		} catch (Exception ex) {
			if (rm.getMsgInfo() == null || "".equals(rm.getMsgInfo())) {
				rm.setState("500");
				rm.setMsgInfo(ex.getMessage());
			}
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 资材备件——盘入导入操作
	 * 
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDiscExcel(CommonPage<YdmEquipmentDetail> sum)
			throws Exception {
	
		ResultModel rm = new ResultModel();
		String filepath = sum.getMemo1();
		String STORAGE_CODE=sum.getMemo2();
		String ftpHost = "172.16.4.170";  
        String ftpUserName = "ftpuser";  
        String ftpPassword = "123456";  
        int ftpPort = 21;  
        String ftpPath = "test/";  
        String localPath = "D:\\download";
        File f=new File(localPath);
        if(!f.exists()){
        	f.mkdirs();
        }
        String fileName = " "; 
        fileName=filepath.substring(5, filepath.length());
        FTPClient ftpClient = null;         
        try {  
        	
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);  
            ftpClient.setControlEncoding("UTF-8"); // 中文支持  
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
            ftpClient.enterLocalPassiveMode();  
            ftpClient.changeWorkingDirectory(ftpPath); 
            File localFile = new File(localPath + File.separatorChar + fileName);  
            OutputStream os = new FileOutputStream(localFile);  
            ftpClient.retrieveFile(fileName, os);        
            os.close();  
            ftpClient.logout();           
            String filename=localFile.getName();
           //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）验证文件名是否合格
           if(filename==null || ("").equals(filename)  && !WDWUtil.validateExcel(filename)){
           	rm.setState("500");
   			rm.setMsgInfo("上传文件格式错误，请使用.xls或.xlsx后缀文档。！");
   			return rm;
           }
           String excel2003L =".xls";    //2003- 版本的excel  
           String excel2007U =".xlsx";   //2007+ 版本的excel  
           FileInputStream in=new FileInputStream(localFile);
               Workbook wb = null;  
               String fileType = filename.substring(filename.lastIndexOf("."));  
               if(excel2003L.equals(fileType)){  
                   wb = new HSSFWorkbook(in);  //2003-  
               }else if(excel2007U.equals(fileType)){  
                   wb = new XSSFWorkbook(in);  //2007+  
               } 
//               Workbook wb=WorkbookFactory.create(localFile);
               List<YdmEquipmentDetail> yepdlist = readExcelData(wb,STORAGE_CODE);
               for (YdmEquipmentDetail yeds : yepdlist) {
				if (yeds == null) {
					throw new Exception("参数格式错误!");
				}
				if (yeds.getQuantity() == null) {
					throw new Exception("请传入要盘入的数量。");
				}
				List<YdmEquipmentDetail> compare = this.getMapper(
						YdmEquipmentDetailMapper.class).doQueryYdmEd(yeds);

				String object_no = "";

				if (compare != null && compare.size() > 0) {
					YdmEquipmentDetail detail = compare.get(0);
					detail.setIn_date(yeds.getIn_date());
					YdmEquipmentDetail tem = new YdmEquipmentDetail();
					tem.setObject_no(detail.getObject_no());
					tem.setState("0");
					object_no = detail.getObject_no();
					List<YdmEquipmentDetail> list = this.getMapper(
							YdmEquipmentDetailMapper.class).find(tem, 0, 0);
					if (list != null && list.size() > 0) { // 存在库存编号存在在库状态的数据，修改
						Double l = detail.getQuantity() == null ? 0d : detail
								.getQuantity();
						detail.setQuantity(l + yeds.getQuantity());
						this.getMapper(YdmEquipmentDetailMapper.class).update(
								detail);
					} else { // 不存在库存编号存在在库状态的数据，要新增
						detail.setState("0");
						detail.setQuantity(yeds.getQuantity());
						this.getMapper(YdmEquipmentDetailMapper.class).insert(
								detail);
					}
				} else {
					String code = this
							.getMapper(YdmEquipmentDetailMapper.class)
							.getCode("KC"+ new SimpleDateFormat("yyyyMMdd").format(new Date()));
					object_no = code;
					YdmEquipmentDetail object = yeds;
					object.setObject_no(code);
					object.setState("0");
					this.getMapper(YdmEquipmentDetailMapper.class).insert(
							object);
				}

				YdmEquipmentDetail yed = yeds;
				String v_man = (String) this.getSession().getAttribute(
						HomeService.SESSION_USER_NAME);
				if (v_man == null || "".equals(v_man)) {
					throw new Exception("登录信息过期,请重新登录 !");
				}
				String v_group = (String) this.getSession().getAttribute(
						HomeService.SESSION_WORK_GRP);
				String v_ord = (String) this.getSession().getAttribute(
						HomeService.SESSION_WORK_ORD);
				// 在入库信息表(YDM_EQUIPMENT_INLIST)中新增一条入库记录
				YdmEquipmentInlist object = new YdmEquipmentInlist();
				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"); // 盘库入库
				object.setObject_no(object_no);
				object.setMat_code(yed.getMat_code());
				object.setMat_name(yed.getMat_name());
				object.setSrot_code(yed.getSrot_code());
				object.setSrot_name(yed.getSrot_name());
				object.setSpec(yed.getSpec());
				object.setPurc_order_no(yed.getPurc_order_no());
				object.setPurc_order_pk(yed.getPurc_order_pk());
				object.setSupplier_no(yed.getSupplier_no());
				object.setSupplier_name(yed.getSupplier_name());
				object.setUnit(yed.getUnit());
				object.setPrice(yed.getPrice());
				object.setIn_date(yed.getIn_date());
				object.setArea(yed.getArea());
				object.setStorage_code(yed.getStorage_code());
				object.setQuantity(yeds.getQuantity());
				object.setOpr_time(new Date());

				this.getMapper(YdmEquipmentInlistMapper.class).insert(object);

				// 在盘库信息表(YDM_EQUIPMENT_STOCKLIST)中新增一条盘库记录
				YdmEquipmentStocklist stock = new YdmEquipmentStocklist();
				String stock_max = this.getMapper(
						YdmEquipmentStocklistMapper.class).getCode();
				stock.setStock_bill_no(stock_max);
				stock.setStock_type("0");
				stock.setStock_date(new SimpleDateFormat("yyyy-MM-dd")
						.format(new Date()));
				stock.setOpr_time(new Timestamp(new Date().getTime()));
				stock.setOpr_man(v_man);
				stock.setObject_no(object_no);
				// [{"object":{"mat_code":"产品编码","srot_code":"产品分类编码","spec":"规格","purc_order_no":"采购订单号","purc_order_pk":"采购订单PK","supplier_no":"供应商代码","unit":"单位","price":"单价","in_date":"入库日期","area":"区域":"","storage_code":"所属仓库编码"}}]
				stock.setMat_code(yed.getMat_code());
				stock.setMat_name(yed.getMat_name());
				stock.setSrot_code(yed.getSrot_code());
				stock.setSrot_name(yed.getSrot_name());
				stock.setSpec(yed.getSpec());
				stock.setPurc_order_no(yed.getPurc_order_no());
				stock.setPurc_order_pk(yed.getPurc_order_pk());
				stock.setSupplier_no(yed.getSupplier_no());
				stock.setSupplier_name(yed.getSupplier_name());
				stock.setUnit(yed.getUnit());
				stock.setPrice(yed.getPrice());
				stock.setIn_date(yed.getIn_date());
				stock.setArea(yed.getArea());
				stock.setStorage_code(yed.getStorage_code());
				stock.setQuantity(yeds.getQuantity());

				this.getMapper(YdmEquipmentStocklistMapper.class).insert(stock);
               }
			rm.setData(yepdlist);
        } catch (FileNotFoundException e) {  
            logger.error("没有找到" + ftpPath + "文件");  
            e.printStackTrace();  
        } catch (SocketException e) {  
            logger.error("连接FTP失败.");  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
            logger.error("文件读取错误。");
            rm.setState("500");
            return rm;
            
        } catch (Exception e) {
   			// TODO: handle exception
   			rm.setState("500");
   			rm.setMsgInfo("操作失败，请联系管理员！");
   			e.printStackTrace(); 
   			return rm;
   		} 
		
		rm.setState("200");
		return rm;


	}
  
	/**
	 * 盘出操作 [{"object":{"object_no":"库存编码","quantity":"数量"}}]
	 * 
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDiscOUT(CommonPage<YdmEquipmentDetail> sum)
			throws Exception {
		ResultModel rm = new ResultModel();

		String v_man = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);

		if (v_man == null || "".equals(v_man)) {
			throw new Exception("登录信息过期,请重新登录 !");
		}

		String v_group = (String) this.getSession().getAttribute(
				HomeService.SESSION_WORK_GRP);
		String v_ord = (String) this.getSession().getAttribute(
				HomeService.SESSION_WORK_ORD);

		try {
			if (sum == null || sum.getObject() == null) {
				throw new Exception("参数格式错误!");
			}
			if (sum.getObject().getObject_no() == null
					|| "".equals(sum.getObject().getObject_no())) {
				throw new Exception("请选择一条库存数据再操作。");
			}
			if (sum.getObject().getQuantity() == null) {
				throw new Exception("请传入要盘出的数量。");
			}

			YdmEquipmentDetail detail = new YdmEquipmentDetail();
			detail.setObject_no(sum.getObject().getObject_no());
			detail.setState("0");

			List<YdmEquipmentDetail> list = this.getMapper(
					YdmEquipmentDetailMapper.class).find(detail, 0, 0);

			if (list == null || list.size() <= 0) {
				throw new Exception("未找的所选数据，库存数据已更改，请重新查询再操作。");
			}
			YdmEquipmentDetail detail2 = list.get(0);
			if (detail2.getQuantity() == null || detail2.getQuantity() == 0) {
				this.getMapper(YdmEquipmentDetailMapper.class).doDelete(detail);
				throw new Exception("数据已更改,请重新操作。");
			}

			if (detail2.getQuantity() < sum.getObject().getQuantity()) {
				throw new Exception("盘出数量不能大于库存数量。");
			}

			// 修改库存信息表（YDM_EQUIPMENT_DETAIL）对应库存编号&&在库的数据
			detail2.setQuantity(detail2.getQuantity()
					- sum.getObject().getQuantity());

			if (detail2.getQuantity() == 0) {
				this.getMapper(YdmEquipmentDetailMapper.class).doDelete(detail);
			} else {
				this.getMapper(YdmEquipmentDetailMapper.class).update(detail2);
			}

			// 查询出库数据
			detail.setState("5");
			List<YdmEquipmentDetail> listOut = this.getMapper(
					YdmEquipmentDetailMapper.class).find(detail, 0, 0);
			if (listOut != null && listOut.size() > 0) { // 修改库存信息表（YDM_EQUIPMENT_DETAIL）对应库存编号&&出库的数据
				YdmEquipmentDetail temp = listOut.get(0);
				if (temp.getQuantity() == null) {
					temp.setQuantity(0d);
				}
				temp.setQuantity(temp.getQuantity()
						+ sum.getObject().getQuantity());
				this.getMapper(YdmEquipmentDetailMapper.class).update(temp);
			} else { // 在库存信息表（YDM_EQUIPMENT_DETAIL）新增对应库存编号&&出库的数据
				this.getMapper(YdmEquipmentDetailMapper.class).insert(detail);
			}

			// 在出库信息表(YDM_EQUIPMENT_INLIST)中新增一条出库记录
			YdmEquipmentOutlist object = new YdmEquipmentOutlist();
			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);
			object.setOut_type("500503"); // 盘库出库
			object.setObject_no(detail.getObject_no());
			object.setMat_code(detail2.getMat_code());
			object.setMat_name(detail2.getMat_name());
			object.setSrot_code(detail2.getSrot_code());
			object.setSrot_name(detail2.getSrot_name());
			object.setSpec(detail2.getSpec());
			object.setPurc_order_no(detail2.getPurc_order_no());
			object.setPurc_order_pk(detail2.getPurc_order_pk());
			object.setSupplier_no(detail2.getSupplier_no());
			object.setSupplier_name(detail2.getSupplier_name());
			object.setUnit(detail2.getUnit());
			object.setPrice(detail2.getPrice());
			object.setOut_date(new SimpleDateFormat("yyyy-MM-dd")
					.format(new Date()));
			object.setArea(detail2.getArea());
			object.setStorage_code(detail2.getStorage_code());
			object.setQuantity(sum.getObject().getQuantity());
			object.setOpr_time(new Date());

			this.getMapper(YdmEquipmentOutlistMapper.class).insert(object);

			// 在盘库信息表(YDM_EQUIPMENT_STOCKLIST)中新增一条盘库记录
			YdmEquipmentStocklist stock = new YdmEquipmentStocklist();
			String stock_max = this
					.getMapper(YdmEquipmentStocklistMapper.class).getCode();
			stock.setStock_bill_no(stock_max);
			stock.setStock_type("1");
			stock.setStock_date(new SimpleDateFormat("yyyy-MM-dd")
					.format(new Date()));
			stock.setOpr_time(new Timestamp(new Date().getTime()));
			stock.setOpr_man(v_man);
			stock.setObject_no(detail.getObject_no());
			// [{"object":{"mat_code":"产品编码","srot_code":"产品分类编码","spec":"规格","purc_order_no":"采购订单号","purc_order_pk":"采购订单PK","supplier_no":"供应商代码","unit":"单位","price":"单价","in_date":"入库日期","area":"区域":"","storage_code":"所属仓库编码"}}]
			stock.setMat_code(detail2.getMat_code());
			stock.setMat_name(detail2.getMat_name());
			stock.setSrot_code(detail2.getSrot_code());
			stock.setSrot_name(detail2.getSrot_name());
			stock.setSpec(detail2.getSpec());
			stock.setPurc_order_no(detail2.getPurc_order_no());
			stock.setPurc_order_pk(detail2.getPurc_order_pk());
			stock.setSupplier_no(detail2.getSupplier_no());
			stock.setSupplier_name(detail2.getSupplier_name());
			stock.setUnit(detail2.getUnit());
			stock.setPrice(detail2.getPrice());
			stock.setIn_date(detail2.getIn_date());
			stock.setArea(detail2.getArea());
			stock.setStorage_code(detail2.getStorage_code());
			stock.setQuantity(sum.getObject().getQuantity());

			this.getMapper(YdmEquipmentStocklistMapper.class).insert(stock);

			rm.setData("200");
			rm.setMsgInfo("盘出成功 !");

		} catch (Exception ex) {
			if (rm.getMsgInfo() == null || "".equals(rm.getMsgInfo())) {
				rm.setState("500");
				rm.setMsgInfo(ex.getMessage());
			}
			ex.printStackTrace();
		}
		return rm;
	}


	/**
	 * 资材备件-入库管理-导入
	 * 
	 * @param
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doExcel(CommonPage<YdmEquipmentDetail> sum)
			throws Exception {
		ResultModel rm = new ResultModel();
		String filepath = sum.getMemo1();
		String STORAGE_CODE=sum.getMemo2();
		String ftpHost = "172.16.4.170";  
        String ftpUserName = "ftpuser";  
        String ftpPassword = "123456";  
        int ftpPort = 21;  
        String ftpPath = "test/";  
        String localPath = "D:\\download";
        File f=new File(localPath);
        if(!f.exists()){
        	f.mkdirs();
        }
        String fileName = " "; 
        fileName=filepath.substring(5, filepath.length());
        FTPClient ftpClient = null;         
        try {  
        	
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);  
            ftpClient.setControlEncoding("UTF-8"); // 中文支持  
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
            ftpClient.enterLocalPassiveMode();  
            ftpClient.changeWorkingDirectory(ftpPath); 
            File localFile = new File(localPath + File.separatorChar + fileName);  
            OutputStream os = new FileOutputStream(localFile);  
            ftpClient.retrieveFile(fileName, os);        
            os.close();  
            ftpClient.logout();           
            String filename=localFile.getName();
           //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）验证文件名是否合格
           if(filename==null || ("").equals(filename)  && !WDWUtil.validateExcel(filename)){
           	rm.setState("500");
   			rm.setMsgInfo("上传文件格式错误，请使用.xls或.xlsx后缀文档。！");
   			return rm;
           }
           String excel2003L =".xls";    //2003- 版本的excel  
           String excel2007U =".xlsx";   //2007+ 版本的excel  
           FileInputStream in=new FileInputStream(localFile);
               Workbook wb = null;  
               String fileType = filename.substring(filename.lastIndexOf("."));  
               if(excel2003L.equals(fileType)){  
                   wb = new HSSFWorkbook(in);  //2003-  
               }else if(excel2007U.equals(fileType)){  
                   wb = new XSSFWorkbook(in);  //2007+  
               } 
//               Workbook wb=WorkbookFactory.create(localFile);
               List<YdmEquipmentDetail> yepds = readExcelData(wb,STORAGE_CODE);
               for (YdmEquipmentDetail yed : yepds) {
					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);
					// 库存编号
					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");
					// 采购订单PK
					ydmEi.setPurc_order_pk(yed.getPurc_order_pk());
					this.getMapper(YdmEquipmentInlistMapper.class).insert(ydmEi);
					}
			rm.setData(yepds);
        } catch (FileNotFoundException e) {  
            logger.error("没有找到" + ftpPath + "文件");  
            e.printStackTrace();  
        } catch (SocketException e) {  
            logger.error("连接FTP失败.");  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
            logger.error("文件读取错误。");
            rm.setState("500");
            return rm;
            
        } catch (Exception e) {
   			// TODO: handle exception
   			rm.setState("500");
   			rm.setMsgInfo("操作失败，请联系管理员！");
   			e.printStackTrace(); 
   			return rm;
   		} 
		
		rm.setState("200");
		return rm;


	}
	/**
	 * 处理EXCEL
	 * 
	 * @author
	 * @throws Exception
	 * **/
	public List<YdmEquipmentDetail> readExcelData(Workbook wb,String STORAGE_CODE2) throws Exception {
		YdmEquipmentDetail yed = null;
		List<YdmEquipmentDetail> yeds = new ArrayList<YdmEquipmentDetail>();
		Row row = null;
		int numSheet = wb.getNumberOfSheets();
		if (numSheet > 0) {
			for (int i = 0; i < numSheet; i++) {
				Sheet sheet = wb.getSheetAt(i);
				int numRow = sheet.getLastRowNum();
				if (numRow >= 2) {
					for (int j = 1; j <= numRow; j++) {
						row = sheet.getRow(j);
						yed = new YdmEquipmentDetail();
						String SUPPLIER_NAME = manageCell(row.getCell(0));// 供应商
						String SUPPLIER_NO = this.getBean(
								YdmEquipmentOutlistMapper.class)
								.findBySuppName(SUPPLIER_NAME);// 供应商编号
						String SPEC = manageCell(row.getCell(1));// 规格
						String UNIT = manageCell(row.getCell(2));// 单位
						String MAT_NAME = manageCell(row.getCell(3));// 产品名称
						String MAT_CODE = this.getBean(
								YdmEquipmentOutlistMapper.class)
								.findProNameByItemName(MAT_NAME);// 产品名称吗
						String SROT_NAME = manageCell(row.getCell(4));// 产品分类
						TreeNode treeNode = this.getBean(TreeNodeMapper.class)
								.findPurMatClassName(SROT_NAME);
						String SROT_CODE = treeNode.getId();// 产品分类码
						String QUANTITY = manageCell(row.getCell(5));// 数量
						String PRICE = manageCell(row.getCell(6));// 单价
						String IN_DATE = manageCell(row.getCell(7));// 入库时间//4
						Date day = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						// SimpleDateFormat df2 = new SimpleDateFormat(
						// "yyyy-MM-dd");
						// Calendar calendar = new
						// GregorianCalendar(1900,0,-1);//得到1900年的日期
						// Date d = calendar.getTime();
						try {
							if (IN_DATE == null && "".equals(IN_DATE)) {
								IN_DATE = df.format(day);
							}
							Double QUANTITY2 = Double.parseDouble(QUANTITY);
							Double price2 = Double.parseDouble(PRICE);
							String STATE = "0";
							String AREA = manageCell(row.getCell(8));// 堆放区域
							String STORAGE_CODE =STORAGE_CODE2;//工程500206   生产 500207
							String PURC_ORDER_NO = manageCell(row.getCell(9));// 采购订单号
							yed.setSupplier_name(SUPPLIER_NAME);
							yed.setSupplier_no(SUPPLIER_NO);
							yed.setSpec(SPEC);
							yed.setUnit(UNIT);
							yed.setMat_name(MAT_NAME);
							yed.setMat_code(MAT_CODE);
							yed.setSrot_name(SROT_NAME);
							yed.setSrot_code(SROT_CODE);
							yed.setQuantity(QUANTITY2);
							yed.setPrice(price2);
							yed.setIn_date(IN_DATE);
							yed.setState(STATE);
							yed.setArea(AREA);
							yed.setStorage_code(STORAGE_CODE);
							yed.setPurc_order_no(PURC_ORDER_NO);
							yeds.add(yed);
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
							throw new Exception("处理数据，未知异常！");
						}

					}
				}
			}
		}
		return yeds;

	}

	/**
	 * 处理从EXCEL读取到的单元格数据
	 * 
	 * @author
	 * @throws Exception
	 * **/
	public static String manageCell(Cell cell)
			throws Exception {
		// DecimalFormat decimalFormatZero = new DecimalFormat("0");
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
		NumberFormat nf = NumberFormat.getInstance();
		String value = "";
		CellType cellType = cell.getCellTypeEnum();
		if (CellType.STRING.equals(cellType)) {
			value = cell.getStringCellValue();
		} else if (DateUtil.isCellDateFormatted(cell)) {// 处理日期格式转换
			Date d = cell.getDateCellValue();
			value = sdf.format(d);
		} else if (CellType.NUMERIC.equals(cellType)) {
			if ("General".equals(cell.getCellStyle().getDataFormatString())) {
				value = String.valueOf(cell.getNumericCellValue());
				long longVal = Math.round(cell.getNumericCellValue());
				if (Double.parseDouble(longVal + ".0") == cell
						.getNumericCellValue())
					value = String.valueOf(longVal);// 处理数值DOUBLE转变为.0操作
			} else if ("m/d/yy".equals(cell.getCellStyle()
					.getDataFormatString())) {
				value = sdf.format(cell.getDateCellValue());
			} else if ("yyyy/m/d".equals(cell.getCellStyle()
					.getDataFormatString())) {
				value = sdf.format(cell.getDateCellValue());
			} else {
				value = nf.format(cell.getNumericCellValue());
				if (value.indexOf(",") > 0) {
					value = value.replace(",", "");
				}// 处理数值变为科学计数法转变为正常
			}
		} else if (CellType.BOOLEAN.equals(cellType)) {
			value = String.valueOf(cell.getBooleanCellValue());
		} else if (CellType.BLANK.equals(cellType)) {
			value = "";
		}
		return value;
	}
	
	/**
	 * 资材备件-导入 预览传输数据
	 * 
	 * @param
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doExcelLookfor(CommonPage<YdmEquipmentDetail> sum)
			throws Exception {
		ResultModel rm = new ResultModel();
		String filepath = sum.getMemo1();		
		String ftpHost = "172.16.4.170";  
        String ftpUserName = "ftpuser";  
        String ftpPassword = "123456";  
        int ftpPort = 21;  
        String ftpPath = "test/";  
        String localPath = "D:\\download";
        File f=new File(localPath);
        if(!f.exists()){
        	f.mkdirs();
        }
        String fileName = " "; 
        fileName=filepath.substring(5, filepath.length());
        FTPClient ftpClient = null;         
        try {  
        	
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);  
            ftpClient.setControlEncoding("UTF-8"); // 中文支持  
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
            ftpClient.enterLocalPassiveMode();  
            ftpClient.changeWorkingDirectory(ftpPath); 
            File localFile = new File(localPath + File.separatorChar + fileName);  
            OutputStream os = new FileOutputStream(localFile);  
            ftpClient.retrieveFile(fileName, os);        
            os.close();  
            ftpClient.logout();           
            String filename=localFile.getName();
           //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）验证文件名是否合格
           if(filename==null || ("").equals(filename)  && !WDWUtil.validateExcel(filename)){
           	rm.setState("500");
   			rm.setMsgInfo("上传文件格式错误，请使用.xls或.xlsx后缀文档。！");
   			return rm;
           }
           String excel2003L =".xls";    //2003- 版本的excel  
           String excel2007U =".xlsx";   //2007+ 版本的excel  
           FileInputStream in=new FileInputStream(localFile);
               Workbook wb = null;  
               String fileType = filename.substring(filename.lastIndexOf("."));  
               if(excel2003L.equals(fileType)){  
                   wb = new HSSFWorkbook(in);  //2003-  
               }else if(excel2007U.equals(fileType)){  
                   wb = new XSSFWorkbook(in);  //2007+  
               } 
//               Workbook wb=WorkbookFactory.create(localFile);
               List<YdmEquipmentDetail> yepds = readExcelData(wb,"500206");
			rm.setData(yepds);
        } catch (FileNotFoundException e) {  
            logger.error("没有找到" + ftpPath + "文件");  
            e.printStackTrace();  
        } catch (SocketException e) {  
            logger.error("连接FTP失败.");  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
            logger.error("文件读取错误。");
            rm.setState("500");
            return rm;
            
        } catch (Exception e) {
   			// TODO: handle exception
   			rm.setState("500");
   			rm.setMsgInfo("操作失败，请联系管理员！");
   			e.printStackTrace(); 
   			return rm;
   		} 
		
		rm.setState("200");
		return rm;


	}
	 /** 
	    * 获取FTPClient对象 
	    * 
	    * @param ftpHost 
	    *            FTP主机服务器 
	    * @param ftpPassword 
	    *            FTP 登录密码 
	    * @param ftpUserName 
	    *            FTP登录用户名 
	    * @param ftpPort 
	    *            FTP端口 默认为21 
	    * @return 
	    */  
	   public static FTPClient getFTPClient(String ftpHost, String ftpUserName,  
	           String ftpPassword, int ftpPort) {  
	       FTPClient ftpClient = new FTPClient();  
	       try {  
	           ftpClient = new FTPClient();  
	           ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器  
	           ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器  
	           if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {  
	               logger.info("未连接到FTP，用户名或密码错误。");  
	               ftpClient.disconnect();  
	           } else {  
	               logger.info("FTP连接成功。");  
	           }  
	       } catch (SocketException e) {  
	           e.printStackTrace();  
	           logger.info("FTP的IP地址可能错误，请正确配置。");  
	       } catch (IOException e) {  
	           e.printStackTrace();  
	           logger.info("FTP的端口错误,请正确配置。");  
	       }  
	       return ftpClient;  
	   }
	   private final static Log logger = LogFactory.getLog(YdmEquipmentStocklistServiceImpl.class); 
}
