/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-05-08
 * 描述            ：物料属性配置表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Mes.Report.impl;
import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseMachineMapper;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.ComBaseMachine;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Mes.Report.mapper.ReportEnergyBasePriceMapper;
import market.Mes.Report.service.ReportEnergyBasePriceService;
import market.Mes.Report.vo.ReportEnergyBasePrice;
import market.Pms.Util.ImportUtil;
import market.Qms.qcm.service.impl.QcmChemExamServiceImpl;
import market.Qms.qcm.vo.QcmChemExam;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
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;


@RemoteService(path="ReportEnergyBasePriceService")
public class ReportEnergyBasePriceServiceImpl extends BaseServiceImpl<ReportEnergyBasePrice,Object> implements ReportEnergyBasePriceService {

	/**
	 * 查询
	 * @param cp
	 * @return
	 */
	 public ResultModel doQuaryReportEnergyBasePrice(CommonPage<ReportEnergyBasePrice> cp){
		 ResultModel rm = new ResultModel();
		 ReportEnergyBasePrice rbp = cp.getObject();
		 String condition = "";
		 if (StringUtils.isNotEmpty(rbp.getWrk_month())) {
			condition += " and wrk_month = '"+rbp.getWrk_month()+"'";
		 }
		 if (StringUtils.isNotEmpty(rbp.getMachine_code())) {
			condition += " and machine_code = '"+rbp.getMachine_code()+"'";
		}
		 List<ReportEnergyBasePrice> rbpList = this.getMapper(ReportEnergyBasePriceMapper.class).findWithCondition(null, condition, "wrk_month,machine_code,item_code", 0, 0);
		 rm.setState("200");
		 rm.setData(rbpList);
		 rm.setMsgInfo("查询成功");
		 return rm;
	 }
	 
	 /**
	  * 新增
	  * @param cp
	  * @return
	  */
	 public ResultModel doInsertReportEnergyBasePrice(CommonPage<ReportEnergyBasePrice> cp){
		 String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		 Date now = new Date();
		 ResultModel rm = new ResultModel();
		 ReportEnergyBasePrice rbp = cp.getObject();
		 //项目名称
		 ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById(rbp.getItem_code());
		 if (cbi!=null) {
			rbp.setItem_name(cbi.getBase_name());
		 }
		 //机组
		 ComBaseMachine cbm = this.getMapper(ComBaseMachineMapper.class).findById(rbp.getMachine_code());
		 if (cbm!=null) {
			 rbp.setMachine_name(cbm.getMachine_name());
			 if (cbm.getMachine_name().contains("退火")) {
				 rbp.setMachine_name("退火机组");
			 }
		 }
		 String condition = "wrk_month = '"+rbp.getWrk_month()+"' and machine_code = '"+rbp.getMachine_code()+"' and item_code = '"+rbp.getItem_code()+"'";
		 int count = this.getMapper(ReportEnergyBasePriceMapper.class).countWithCondition(null, condition);
		 if (count > 0) {
			 rm.setState("500");
			 rm.setMsgInfo("月份【"+rbp.getWrk_month()+"】【"+rbp.getMachine_name()+"】【"+rbp.getItem_name()+"】已经基价信息，无法继续新增");
			 return rm;
		 }
		 rbp.setCreate_man(userName);
		 rbp.setCreate_time(now);
		 this.getMapper(ReportEnergyBasePriceMapper.class).insert(rbp);
		 rm.setState("200");
		 rm.setMsgInfo("新增成功");
		 return rm;
	 }
	 
	 /**
	  * 修改基价
	  * @param cp  
	  * @return
	  */
	 @Transactional(value = "tm", rollbackFor = Exception.class)
	 public ResultModel doUpdateReportEnergyBasePrice(CommonPage<ReportEnergyBasePrice> cp){
		 String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		 String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		 ResultModel rm = new ResultModel();
		 List<ReportEnergyBasePrice> rbpList = cp.getObjectList();
		 if (CollectionUtils.isNotEmpty(rbpList)) {
			for (ReportEnergyBasePrice rbp : rbpList) {
				String sql = "update report_energy_base_price t "
						+ "set t.base_prcie = "+rbp.getBase_prcie()+","
						+ "t.base_money = "+rbp.getBase_money()+","
						+ "t.update_man = '"+userName+"',"
						+ "t.update_time = to_date('"+now+"','yyyy-MM-dd hh24:mi:ss')"
						+ "where t.wrk_month = '"+rbp.getWrk_month()+"' "
						+ "and t.item_code = '"+rbp.getItem_code()+"' "
						+ "and t.machine_code = '"+rbp.getMachine_code()+"'";
				this.getMapper(ReportEnergyBasePriceMapper.class).doUpdateReportEnergyBasePrice(sql);
			}
		 }
		 rm.setState("200");
		 rm.setMsgInfo("修改成功");
		 return rm;
	 }
	 
	 /**
	  * 删除
	  * @param cp
	  * @return
	  */
	 @Transactional(value = "tm", rollbackFor = Exception.class)
	 public ResultModel doDeleteReportEnergyBasePrice(CommonPage<ReportEnergyBasePrice> cp){
		 ResultModel rm = new ResultModel();
		 List<ReportEnergyBasePrice> rbpList = cp.getObjectList();
		 if (CollectionUtils.isNotEmpty(rbpList)) {
			 for (ReportEnergyBasePrice rbp : rbpList) {
				 String sql = "delete from report_energy_base_price t "
						 + "where t.wrk_month = '"+rbp.getWrk_month()+"' "
						 + "and t.item_code = '"+rbp.getItem_code()+"' "
						 + "and t.machine_code = '"+rbp.getMachine_code()+"'";
				 this.getMapper(ReportEnergyBasePriceMapper.class).doDeleteReportEnergyBasePrice(sql);
			}
		 }
		 rm.setState("200");
		 rm.setMsgInfo("删除成功");
		 return rm;
	 }
	 
	 /**
	  * 复制基价
	  * @param cp [{"memo1":"2020-09","memo2":"2020-10"}]  memo1：需要复制的月份  memo2：复制到哪个月份
	  * @return
	 * @throws Exception 
	  */
	 @Transactional(value = "tm", rollbackFor = Exception.class)
	 public ResultModel doCopyReportEnergyBasePrice(CommonPage<ReportEnergyBasePrice> cp) throws Exception{
		 String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		 Date now = new Date();
		 ResultModel rm = new ResultModel();
		 //1.1 判断复制到月份memo2是否存在数据
		 String condition = "wrk_month = '"+cp.getMemo2()+"'";
		 int count = this.getMapper(ReportEnergyBasePriceMapper.class).countWithCondition(null, condition);
		 if (count > 0) {
			throw new Exception("月份【"+cp.getMemo2()+"】已经存在基价数据，无法复制");
		 }
		 //1.2 判断复制来源月份memo1是否存在数据
		 condition = "wrk_month = '"+cp.getMemo1()+"'";
		 count = this.getMapper(ReportEnergyBasePriceMapper.class).countWithCondition(null, condition);
		 if (count <= 0) {
			throw new Exception("未找到月份【"+cp.getMemo1()+"】存在基价数据，无法复制");
		 }
		 ReportEnergyBasePrice r = new ReportEnergyBasePrice();
		 r.setWrk_month(cp.getMemo1());
		 List<ReportEnergyBasePrice> rbpList = this.getMapper(ReportEnergyBasePriceMapper.class).find(r,0,0);
		 if (CollectionUtils.isNotEmpty(rbpList)) {
			for (ReportEnergyBasePrice RBP : rbpList) {
				ReportEnergyBasePrice rbp = new ReportEnergyBasePrice();
				rbp.setWrk_month(cp.getMemo2());
				rbp.setItem_code(RBP.getItem_code());
				rbp.setItem_name(RBP.getItem_name());
				rbp.setBase_prcie(RBP.getBase_prcie());
				rbp.setBase_money(RBP.getBase_money());
				rbp.setMachine_code(RBP.getMachine_code());
				rbp.setMachine_name(RBP.getMachine_name());
				rbp.setCreate_man(userName);
				rbp.setCreate_time(now);
				this.getMapper(ReportEnergyBasePriceMapper.class).insert(rbp);
			}
		 }
		 rm.setState("200");
		 rm.setMsgInfo("复制成功");
		 return rm;
	 }
	 
	 /**
	  * 导入批量新增基价
	  * @param cp [{"memo1":"2020-09","memo2":"2020-10"}]
	  * @return
	 * @throws Exception 
	  */
	 @Transactional(value = "tm", rollbackFor = Exception.class)
	 public ResultModel doAddMultiImport() throws Exception{
		 synchronized (this) {
			 String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			 Date now = new Date();
			 ResultModel rm = new ResultModel();
			 
			 rm.setState("200");
			 rm.setMsgInfo("导入批量新增成功");
			 
			 // 获取需要导入的数据：
			 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(ReportEnergyBasePriceServiceImpl.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("合同模板读取失败！");
				}
		        
		        // 2.读取Excel数据
		        int numRow = 0;//最后的行数
		        Sheet sheet = null;
				try {
					//第一个表单
					sheet = wb.getSheetAt(0);
					//行数
					numRow = sheet.getLastRowNum();//最后的行数
				} catch (Exception e) {
					throw new Exception("Excel表格数据读取失败！" + e.getMessage());
				}
				ArrayList<ReportEnergyBasePrice> list = new ArrayList<>();
				if (numRow >= 1) {
					for (int i = 1; i <= numRow; i++) {
						Row row = sheet.getRow(i);

//						if ("".equals(ImportUtil.getCellValue(row.getCell(1)).trim())) {
//							continue;
//						}
						
						ReportEnergyBasePrice rbp = new ReportEnergyBasePrice();
						// 先将数字转为文本：
						row.getCell(4).setCellType(Cell.CELL_TYPE_STRING); // 项目代码
						row.getCell(6).setCellType(Cell.CELL_TYPE_STRING); // 价格
						row.getCell(7).setCellType(Cell.CELL_TYPE_STRING); // 金额
						
						rbp.setWrk_month(ImportUtil.getCellValue(row.getCell(1)).trim());
						rbp.setMachine_code(ImportUtil.getCellValue(row.getCell(2)).trim());
						rbp.setMachine_name(ImportUtil.getCellValue(row.getCell(3)).trim());
						//机组
						ComBaseMachine cbm = this.getMapper(ComBaseMachineMapper.class).findById(rbp.getMachine_code());
						if (cbm!=null) {
							rbp.setMachine_name(cbm.getMachine_name());
							if (cbm.getMachine_name().contains("退火")) {
								rbp.setMachine_name("退火机组");
							}
						}
						rbp.setItem_code(ImportUtil.getCellValue(row.getCell(4)).trim());
						rbp.setItem_name(ImportUtil.getCellValue(row.getCell(5)).trim());
						//项目名称
						 ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById(rbp.getItem_code());
						 if (cbi!=null) {
							rbp.setItem_name(cbi.getBase_name());
						 }
						rbp.setItem_name(ImportUtil.getCellValue(row.getCell(5)).trim());
//						System.out.println(ImportUtil.getCellValue(row.getCell(6)).trim());
//						System.out.println(ImportUtil.getCellValue(row.getCell(7)).trim());
						rbp.setBase_prcie("".equals(ImportUtil.getCellValue(row.getCell(6)).trim()) ? null : "0".equals(ImportUtil.getCellValue(row.getCell(6)).trim()) ? 0 : Double.parseDouble(ImportUtil.getCellValue(row.getCell(6)).trim()));
						rbp.setBase_money("".equals(ImportUtil.getCellValue(row.getCell(7)).trim()) ? null : "0".equals(ImportUtil.getCellValue(row.getCell(7)).trim()) ? 0 : Double.parseDouble(ImportUtil.getCellValue(row.getCell(7)).trim()));
						rbp.setCreate_man(userName);
						rbp.setCreate_time(now);
						list.add(rbp);
					}
					
					System.out.println(list.size());
					String condition = null;
					int count = 0;
					for(int i = 0; i < list.size(); i++) {
						// 月份，机组，项目名称不能为空：
						if ("".equals(list.get(i).getWrk_month()) || "".equals(list.get(i).getMachine_name()) || "".equals(list.get(i).getItem_name())) {
//							rm.setState("500");
//							rm.setMsgInfo("存在月份为空或者机组为空或者项目名称为空的行，请检查模板文件！！！");
//							break;
							throw new Exception("存在月份为空或者机组为空或者项目名称为空的行，请检查模板文件！！！");
						}
						// 判断是否已经有这条数据：
						condition = "wrk_month = '"+list.get(i).getWrk_month()+"' and machine_code = '"+list.get(i).getMachine_code()+"' and item_code = '"+list.get(i).getItem_code()+"'";
						count = this.getMapper(ReportEnergyBasePriceMapper.class).countWithCondition(null, condition);
						if (count > 0) {
//							rm.setState("500");
//							rm.setMsgInfo("月份【"+list.get(i).getWrk_month()+"】【"+list.get(i).getMachine_name()+"】【"+list.get(i).getItem_name()+"】已经基价信息，无法继续新增");
//							return rm;
							throw new Exception("月份【"+list.get(i).getWrk_month()+"】【"+list.get(i).getMachine_name()+"】【"+list.get(i).getItem_name()+"】已经存在基价信息，无法继续新增");
						}
					}
					// 批量插入：
					this.getMapper(ReportEnergyBasePriceMapper.class).insertBatch(list);
				}
			 
			
			 return rm;
		 }
	 }
	
}
