/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-08-23
 * 描述            ：现货信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Slm.ProductManagement.impl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import market.Com.mapper.PbModelDbMapper;
import market.Com.pb.PbMethod;
import market.Com.vo.CommonPage;
import market.Com.vo.PbModelDb;
import market.Com.vo.ResultModel;
import market.Pms.Util.ImportUtil;
import market.Slm.ProductManagement.mapper.SlmProductMapper;
import market.Slm.ProductManagement.service.SlmProductService;
import market.Slm.ProductManagement.vo.SlmProduct;

import org.apache.commons.fileupload.FileItem;
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.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;
import com.ibm.icu.text.SimpleDateFormat;

@RemoteService(path="SlmProductService")
public class SlmProductServiceImpl extends BaseServiceImpl<SlmProduct,Object> implements SlmProductService {
	/**
	 * 查询
	 * memo1：品名1,品名2,品名3   product_second_name
	 * memo2：牌号1,牌号2,牌号3   steel_name
	 * memo3: 厚度 xxx-xxx  若有值则必须传-
	 * memo4：宽度 xxx-xxx  若有值则必须传-
	 * memo5：长度 xxx-xxx  若有值则必须传-
	 * @param oci
	 * @return
	 */
	public ResultModel doQueryWeb(CommonPage<SlmProduct> oci){
		ResultModel rm=new ResultModel();
		int pageIndex=oci.getPageIndex();
		int pageSize=oci.getPageSize();
		try{
			String strWhere="1=1";
			if(oci.getMemo1()!=null&&!"".equals(oci.getMemo1())){
				// xxx,xxx   'xxx','
				strWhere+=" and product_second_name in('"+oci.getMemo1().replace(",", "','")+"')";
			}
			if(oci.getMemo2()!=null&&!"".equals(oci.getMemo2())){
				strWhere+=" and steel_name in('"+oci.getMemo2().replace(",", "','")+"')";
			}
			if(oci.getMemo3()!=null&&!"".equals(oci.getMemo3())){
				String[] str=oci.getMemo3().split("-");
				if(!"".equals(str[0])){
					strWhere+=" and thick>="+str[0];
				}
				if(!"".equals(str[1])){
					strWhere+=" and thick<="+str[1];
				}
			}
			if(oci.getMemo4()!=null&&!"".equals(oci.getMemo4())){
				String[] str=oci.getMemo4().split("-");
				if(!"".equals(str[0])){
					strWhere+=" and width>="+str[0];
				}
				if(!"".equals(str[1])){
					strWhere+=" and width<="+str[1];
				}
			}
			if(oci.getMemo5()!=null&&!"".equals(oci.getMemo5())){
				String[] str=oci.getMemo5().split("-");
				if(!"".equals(str[0])){
					strWhere+=" and length>="+str[0];
				}
				if(!"".equals(str[1])){
					strWhere+=" and length<="+str[1];
				}
			}
			String[] sortField=null;
			String[] sortType=null;
			String strSort="";
			if(oci.getSortField()!=null&&!"".equals(oci.getSortField())){
				sortField=oci.getSortField().split(",");
			}
			if(oci.getSortType()!=null&&!"".equals(oci.getSortType())){
				sortType=oci.getSortType().replace("0", "asc").replace("1", "desc").split(",");
			}
			if(sortField!=null&&sortField.length==sortType.length){
				for(int i=0;i<sortField.length;i++){
					strSort+=sortField[i]+" "+sortType[i]+",";
				}
				strSort=strSort.substring(0,strSort.length()-1);
			}
			
			rm.setState("200");
			List<SlmProduct> list=this.getMapper(SlmProductMapper.class).findWithCondition(oci.getObject(), strWhere, strSort, (pageIndex-1)*pageSize, pageSize);
			int count=this.getMapper(SlmProductMapper.class).countWithCondition(oci.getObject(), strWhere);
			PageModel<SlmProduct> pm=new PageModel<SlmProduct>(pageIndex,pageSize);
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败："+ex.getMessage());
			ex.printStackTrace();
		}
		
		return rm;
	}
	
	/**
	 * 新增
	 * @param oci
	 * @return
	 */
	public ResultModel doAddWeb(CommonPage<SlmProduct> oci){
		ResultModel rm=new ResultModel();
		
		try{
			String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
			String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3);
			
			oci.getObject().setId(id);
			oci.getObject().setCreate_man_no(userId);
			oci.getObject().setCreate_man_name(userName);
			oci.getObject().setCreate_time(new Date());
			oci.getObject().setValid_flag("1");
			
			this.getMapper(SlmProductMapper.class).insert(oci.getObject());
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("新增失败："+ex.getMessage());
			ex.printStackTrace();
		}
		
		return rm;
	}
	
	/**
	 * 修改
	 * @param oci
	 * @return
	 */
	public ResultModel doUpdateWeb(CommonPage<SlmProduct> oci){
		ResultModel rm=new ResultModel();
		
		try{
			String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
			String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			
			oci.getObject().setUpdate_man_no(userId);
			oci.getObject().setUpdate_man_name(userName);
			oci.getObject().setUpdate_time(new Date());
			
			this.getMapper(SlmProductMapper.class).update(oci.getObject());
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("修改失败："+ex.getMessage());
			ex.printStackTrace();
		}
		
		return rm;
	}
	
	/**
	 * 删除
	 * @param oci
	 * @return
	 */
	public ResultModel doDeleteWeb(CommonPage<SlmProduct> oci){
		ResultModel rm=new ResultModel();
		
		try{
			for(SlmProduct sp:oci.getObjectList()){
				this.getMapper(SlmProductMapper.class).delete(sp.getId());
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("删除失败："+ex.getMessage());
			ex.printStackTrace();
		}
		
		return rm;
	}
	/**
	 * 现货-导入
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doImportWeb() throws Exception{
//		this.getSession().setAttribute(HomeService.SESSION_USER_ID,"admin");
//		this.getSession().setAttribute(HomeService.SESSION_USER_NAME,"管理员");
		ResultModel rm=new ResultModel();
		String rownum="1";
		Workbook wb=null;
		try{
			URL url = this.getClass().getClassLoader().getResource("/");
			// 替换路径中的空格
			String filePath = url.getPath().replaceAll("%20", " ");
			File file = new File(filePath);
			List<FileItem> items = ImportUtil.getUpload(SlmProductServiceImpl.this,file,getRequest());			
			for (FileItem item : items) {
				// 若是文件域则读取文件流
				if (!item.isFormField()) {
					wb = ImportUtil.getWB(item, file.length());
				}
			}
			String cell0,cell1,cell7,cell8;
			double cell2,cell3,cell4,cell5,cell6;
			Sheet sheet=wb.getSheetAt(0);
			int count = sheet.getLastRowNum();
			//牌号、品名、仓库名称
			HashMap<String, String> steelMap=getSteelMap();
			HashMap<String, String> prodMap=getProdMap();
			HashMap<String, String> warehouseMap=getWarehouseMap();
			int order_num=1;
			while (order_num<=count) {
				Row row = sheet.getRow(order_num);
				order_num++;
				rownum=order_num+"";
//				牌号，品名，厚，宽，长，单价，重量，备注，仓库名称
				cell0=ImportUtil.getCellValue(row.getCell(0));		//牌号
				cell1=ImportUtil.getCellValue(row.getCell(1));		//品名
				cell2=Double.parseDouble(ImportUtil.getCellValue(row.getCell(2)));		//厚
				cell3=Double.parseDouble(ImportUtil.getCellValue(row.getCell(3)));		//宽
				cell4=Double.parseDouble(ImportUtil.getCellValue(row.getCell(4)));		//长
				cell5=Double.parseDouble(ImportUtil.getCellValue(row.getCell(5)));		//单价
				cell6=Double.parseDouble(ImportUtil.getCellValue(row.getCell(6)));		//重量
				cell7=ImportUtil.getCellValue(row.getCell(7));		//备注
				cell8=ImportUtil.getCellValue(row.getCell(8));		//仓库名称
				
				SlmProduct prd=new SlmProduct();
				String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
				String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
				String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3);
				prd.setId(id);
				prd.setCreate_man_no(userId);
				prd.setCreate_man_name(userName);
				prd.setCreate_time(new Date());
				prd.setValid_flag("1");
				
				prd.setSteel_name(cell0);
				if(!steelMap.containsKey(cell0)){
					throw new Exception("未找到牌号【"+cell0+"】对应的编码！");
				}
				prd.setSteel_no(steelMap.get(cell0));
				prd.setProduct_second_name(cell1);
				if(!prodMap.containsKey(cell1)){
					throw new Exception("未找到品名【"+cell1+"】对应的编码！");
				}
				prd.setProduct_second_no(prodMap.get(cell1));
				prd.setThick(cell2);
				prd.setWidth(cell3);
				prd.setLength(cell4);
				prd.setPrice(cell5);
				prd.setWeight(cell6);
				prd.setMemo(cell7);
				prd.setWarehouse_name(cell8);
				if(!warehouseMap.containsKey(cell8)){
					throw new Exception("未找到仓库【"+cell8+"】对应的编码！");
				}
				prd.setWarehouse_no(warehouseMap.get(cell8));
				this.getMapper(SlmProductMapper.class).insert(prd);
			}
			wb.close(); 
			rm.setState("200");
			rm.setMsgInfo("导入成功");
		} catch (FileNotFoundException e) {  
			e.printStackTrace();  
			rm.setState("500");
			rm.setMsgInfo("未找到文件");
		} catch (SocketException e) {  
			logger.error("连接FTP失败");  
			rm.setMsgInfo("连接FTP失败"+e.getMessage());
			rm.setState("500");
		} catch (IOException e) {  
			e.printStackTrace();  
			logger.error("文件读取错误");
			rm.setMsgInfo("文件读取错误"+e.getMessage());
			rm.setState("500");
			return rm;
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("第"+rownum+"条数据新增时出现错误："+e.getMessage());
			e.printStackTrace(); 
			throw new Exception(rm.getMsgInfo());
		} 
		return rm;
	}

	/**
	 * 获取品名集合
	 * @return
	 */
	private HashMap<String, String> getProdMap() {
		HashMap<String, String> map=new HashMap<>();
		List<PbModelDb> lpm=this.getMapper(PbModelDbMapper.class).findPrododeCmdDb();
		for(PbModelDb db:lpm){
			map.put(db.getText(), db.getId());
		}
		return map;
	}

	/**
	 * 获取牌号集合
	 * @return
	 */
	private HashMap<String, String> getSteelMap() {
		HashMap<String, String> map=new HashMap<>();
		List<PbModelDb> lpm=this.getMapper(PbModelDbMapper.class).findSteelInfoCmbDb();
		for(PbModelDb db:lpm){
			map.put(db.getText(), db.getId());
		}
		return map;
	}

	/**
	 * 获取仓库名称集合
	 * @return
	 */
	private HashMap<String, String> getWarehouseMap() {
		HashMap<String, String> map=new HashMap<>();
		map.put("原料库", "1001");
		map.put("成品库", "1003");
		map.put("贸易库", "1005");
		map.put("酸洗成品库", "1009");
		return map;
	}
}
