/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-05-22
 * 描述            ：采购原料明细表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Pms.Mat.impl;
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Mat.mapper.PurMatDMapper;
import market.Pms.Mat.service.PurMatDService;
import market.Pms.Mat.vo.PurMatD;
import market.Pms.Order.mapper.PurOrderCMapper;
import market.Pms.Order.mapper.PurOrderMMapper;
import market.Pms.Order.vo.PurOrderC;
import market.Pms.Order.vo.PurOrderM;
import market.Pms.Util.ImportUtil;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
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.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;

@RemoteService(path="PurMatDService")
public class PurMatDServiceImpl extends BaseServiceImpl<PurMatD,Object> implements PurMatDService {
	
	/**
	 * 查询采购原料明细表
	 * @param cp
	 * @return
	 */
	public ResultModel doQuaryPurMatDWeb(CommonPage<PurMatD> cp){

		ResultModel rm = new ResultModel();
		PurMatD pmd = cp.getObject();
		int pageIndex = cp.getPageIndex();
		int pageSize = cp.getPageSize();
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		PageModel<PurMatD> pm = new PageModel<PurMatD>(pageIndex, pageSize);
		try {			
			pm.setRows(this.getMapper(PurMatDMapper.class).doQuaryPurMatDWeb(pmd, (pageIndex-1)*pageSize,pageIndex*pageSize,startTime,endTime));
			pm.setTotal(this.getMapper(PurMatDMapper.class).doQuaryPurMatDWebCount(pmd,startTime,endTime));
			rm.setState("200");
			rm.setData(pm);
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	
	}
	
	/**
	 * @author zlz
	 * @date   2019年5月23日
	 * @parameter 
	 * @return 
	 * @description 采购原料明细表的导入
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doImportPurMatD() throws Exception{
		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(PurMatDServiceImpl.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();//最后的行数
				//Double addWeight = 20d; //默认一个和同行的重量是20T
				if (numRow >= 1) {
					Date now = new Date();
					
					String pline,pur_contract_no,pur_date,order_unit,steel_name,spec;
					String pur_num,materailcoilno,pur_unload_addr,sal_contract_no,balance_no;
					String sales,incoms,sal_unload_addr,sal_price,sal_freight_price;
					String sal_price_differ,sal_money_differ,sal_differ_reason,sal_subadd_situation,sal_subadd_money;
					String pur_price,pur_freight_price,in_price_differ,in_money_differ,in_differ_reason;
					String in_subadd_situation,in_subadd_money,pur_cycle,pur_price_add,pur_add_money;
					String sal_cycle,sal_price_add,sal_add_money,memo;
					//从第2行开始读取
					//SimpleDateFormat sdf0 = new SimpleDateFormat("yyyyMMdd");
					for (int i = 1; i <= numRow; i++) {
						Row row = sheet.getRow(i);
						row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
						//处理行数据
						pline = ImportUtil.getCellValue(row.getCell(0));				//产线
						pur_contract_no = ImportUtil.getCellValue(row.getCell(1));		//采购合同号
						//处理采购合同号
						pur_contract_no = pur_contract_no.replace("'", "");
						if ("".equals(pur_contract_no)) {//采购合同号位空，直接下一条数据
							continue;
						}	
						//pur_date = String.valueOf(row.getCell(2).getStringCellValue()).substring(0, 8);	//进货日期
						pur_date = ImportUtil.getCellValue(row.getCell(2));	//进货日期
						pur_date = pur_date.replace(".", "").substring(0, 8);
						order_unit = ImportUtil.getCellValue(row.getCell(3));			//订货单位
						steel_name = ImportUtil.getCellValue(row.getCell(4));			//牌号
						spec = ImportUtil.getCellValue(row.getCell(5));					//规格(mm)
						pur_num = ImportUtil.getCellValue(row.getCell(6));				//数量（t）						
						materailcoilno = String.valueOf(row.getCell(7).getStringCellValue());		//钢卷号						
						pur_unload_addr = ImportUtil.getCellValue(row.getCell(8));		//采购合同卸货点
						sal_contract_no = ImportUtil.getCellValue(row.getCell(9));		//销售合同号
						balance_no= ImportUtil.getCellValue(row.getCell(10));			//结算单号
						sales= ImportUtil.getCellValue(row.getCell(11));				//销项
						incoms= ImportUtil.getCellValue(row.getCell(12));				//进项
						sal_unload_addr= ImportUtil.getCellValue(row.getCell(13));		//销售合同卸货地点
						sal_price= ImportUtil.getCellValue(row.getCell(14));			//销售单价
						sal_freight_price= ImportUtil.getCellValue(row.getCell(15));	//销售运费
						sal_price_differ= ImportUtil.getCellValue(row.getCell(17));		//销项单价差额
						//销项金额差额
						sal_money_differ = "";
						if (!"".equals(sal_price_differ) && !"".equals(pur_num)) {							
							sal_money_differ= (Double.parseDouble(sal_price_differ) * Double.parseDouble(pur_num))+"";
							//sal_money_differ= ImportUtil.getCellValue(row.getCell(18));
						}
						sal_differ_reason= ImportUtil.getCellValue(row.getCell(19));	//销项差额原因
						sal_subadd_situation= ImportUtil.getCellValue(row.getCell(20));	//销项冲减或补收情况
						sal_subadd_money= ImportUtil.getCellValue(row.getCell(21));		//销项冲减或补收金额
						pur_price= ImportUtil.getCellValue(row.getCell(22));			//采购单价
						pur_freight_price= ImportUtil.getCellValue(row.getCell(23));	//采购运费
						in_price_differ= ImportUtil.getCellValue(row.getCell(25));		//进项单价差额
						//进项金额差额
						in_money_differ = "";
						if (!"".equals(in_price_differ) && !"".equals(pur_num)) {							
							in_money_differ= (Double.parseDouble(in_price_differ) * Double.parseDouble(pur_num))+"";
							//in_money_differ= ImportUtil.getCellValue(row.getCell(26));
						}
						in_differ_reason= ImportUtil.getCellValue(row.getCell(27));		//进项差额原因
						in_subadd_situation= ImportUtil.getCellValue(row.getCell(28));	//进项冲减或补收情况
						in_subadd_money= ImportUtil.getCellValue(row.getCell(29));		//进项冲减或补收金额
						pur_cycle= ImportUtil.getCellValue(row.getCell(30));			//采购接单周期
						pur_price_add= ImportUtil.getCellValue(row.getCell(31));		//采购价格追补
						//采购追补金额
						pur_add_money = "";
						if (!"".equals(pur_price_add) && !"".equals(pur_num)) {							
							pur_add_money= (Double.parseDouble(pur_price_add) * Double.parseDouble(pur_num))+"";
							//pur_add_money= ImportUtil.getCellValue(row.getCell(32));
						}
						sal_cycle= ImportUtil.getCellValue(row.getCell(33));			//销售接单周期
						sal_price_add= ImportUtil.getCellValue(row.getCell(34));		//销售价格追补
						//销售追补金额
						sal_add_money = "";
						if (!"".equals(sal_price_add) && !"".equals(pur_num)) {							
							sal_add_money= (Double.parseDouble(sal_price_add) * Double.parseDouble(pur_num))+"";
							//sal_add_money= ImportUtil.getCellValue(row.getCell(35));
						}
						memo= ImportUtil.getCellValue(row.getCell(40));					//备注						
						
						PurMatD PMD = this.getMapper(PurMatDMapper.class).findById(materailcoilno);
						if (PMD == null) {						
							//2.插入PUR_MAT_D采购原料明细表
							PurMatD pmd = new PurMatD();
							pmd.setPline(pline);
							pmd.setPur_contract_no(pur_contract_no);
							pmd.setPur_date(pur_date);
							pmd.setOrder_unit(order_unit);
							pmd.setSteel_name(steel_name);
							pmd.setSpec(spec);
							pmd.setPur_num("".equals(pur_num)?0:Double.parseDouble(pur_num));
							pmd.setMaterailcoilno(materailcoilno);
							pmd.setPur_unload_addr(pur_unload_addr);
							pmd.setSal_contract_no(sal_contract_no);
							pmd.setBalance_no(balance_no);
							pmd.setSales(sales);
							pmd.setIncoms(incoms);
							pmd.setSal_unload_addr(sal_unload_addr);
							pmd.setSal_price("".equals(sal_price)?0:Double.parseDouble(sal_price));
							pmd.setSal_freight_price("".equals(sal_freight_price)?0:Double.parseDouble(sal_freight_price));
							pmd.setSal_price_differ("".equals(sal_price_differ)?0:Double.parseDouble(sal_price_differ));
							pmd.setSal_money_differ("".equals(sal_money_differ)?0:Double.parseDouble(sal_money_differ));
							pmd.setSal_differ_reason(sal_differ_reason);
							pmd.setSal_subadd_situation(sal_subadd_situation);
							pmd.setSal_subadd_money("".equals(sal_subadd_money)?0:Double.parseDouble(sal_subadd_money));
							pmd.setPur_price("".equals(pur_price)?0:Double.parseDouble(pur_price));
							pmd.setPur_freight_price("".equals(pur_freight_price)?0:Double.parseDouble(pur_freight_price));
							pmd.setIn_price_differ("".equals(in_price_differ)?0:Double.parseDouble(in_price_differ));
							pmd.setIn_money_differ("".equals(in_money_differ)?0:Double.parseDouble(in_money_differ));
							pmd.setIn_differ_reason(in_differ_reason);
							pmd.setIn_subadd_situation(in_subadd_situation);
							pmd.setIn_subadd_money("".equals(in_subadd_money)?0:Double.parseDouble(in_subadd_money));
							pmd.setPur_cycle(pur_cycle);
							pmd.setPur_price_add("".equals(pur_price_add)?0:Double.parseDouble(pur_price_add));
							pmd.setPur_add_money("".equals(pur_add_money)?0:Double.parseDouble(pur_add_money));
							pmd.setSal_cycle(sal_cycle);
							pmd.setSal_price_add("".equals(sal_price_add)?0:Double.parseDouble(sal_price_add));
							pmd.setSal_add_money("".equals(sal_add_money)?0:Double.parseDouble(sal_add_money));
							pmd.setMemo(memo);
							pmd.setCreate_time(now);
							pmd.setCreate_user("sys");
							this.getMapper(PurMatDMapper.class).insert(pmd);
						}else {
							PMD.setPur_price("".equals(pur_price)?0:Double.parseDouble(pur_price));
							PMD.setCreate_time(now);
							PMD.setCreate_user("sys");
							this.getMapper(PurMatDMapper.class).update(PMD);
						}
					}
						
				}
			} catch (Exception e) {
				throw new Exception("Excel表格数据读取失败！" + e.getMessage());
			}
			return rm; 
		} 	
	}

	/**
	 * 删除功能
	 * @param cp
	 * @return
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDeletePurMatD(CommonPage<PurMatD> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		List<PurMatD> pmdList = cp.getObjectList();
		if (pmdList!=null && pmdList.size()>0) {
			Double addWeight = 20d;
			for (PurMatD PMD : pmdList) {
				PurMatD pmd = this.getMapper(PurMatDMapper.class).findById(PMD.getMaterailcoilno());
				if (pmd==null) {
					throw new Exception("未找到钢卷号【"+PMD.getMaterailcoilno()+"】的录入采购原料明细");
				}
				//1.删除导入的pur_madt_d表
				this.getMapper(PurMatDMapper.class).delete(pmd.getMaterailcoilno());
				//2.判断是否有导入的合同主信息
				String pur_contract_no = pmd.getPur_contract_no();//采购合同号
				PurOrderM pom = new PurOrderM();
				pom.setContract_no(pur_contract_no);
				//pom.setCreate_name("sys");
				List<PurOrderM> pomList = this.getMapper(PurOrderMMapper.class).find(pom, 0, 0);
				if (pomList==null || pomList.size()==0) {
					throw new Exception("未找到导入的采购合同主信息【"+pur_contract_no+"】");
				}
				//3.存在合同主信息，则判断是否有合同行信息
				pom = pomList.get(0);
				PurOrderC poc = new PurOrderC();
				poc.setContract_no(pom.getContract_no());
				poc.setContract_pk(pom.getContract_pk());
				poc.setCreate_name("sys");
				poc.setSteel_name(pmd.getSteel_name());
				poc.setSpec_name(pmd.getSpec());
				poc.setPrice_with_tax(pmd.getPur_price());//含税单价
				List<PurOrderC> pocList = this.getMapper(PurOrderCMapper.class).find(poc, 0, 0);
				if (pocList!=null && pocList.size() > 0) {
					//如果存在合同行信息，则删除对应的合同行信息
					poc = pocList.get(0);
					Double qty = poc.getQty();
					if (qty>addWeight) {
						//修改重量
						poc.setQty(poc.getQty()-addWeight);
						poc.setWith_tax_amt(poc.getQty() * poc.getPrice_with_tax());//含税金额
						poc.setWithout_tax_amt(poc.getQty() * poc.getPrice_without_tax());//不含税金额
						poc.setTax_amt(poc.getWith_tax_amt() - poc.getWithout_tax_amt());//税额								
						this.getMapper(PurOrderCMapper.class).update(poc);
					}else if (qty==addWeight || qty.equals(addWeight)) {
						//删除合同行信息
						this.getMapper(PurOrderCMapper.class).delete(poc.getOrder_pk());
						//判断合同下是否存在其它合同行信息，不存在其它行信息，则删除合同主新
						poc = new PurOrderC();
						poc.setContract_no(pom.getContract_no());
						poc.setContract_pk(pom.getContract_pk());
						pocList = this.getMapper(PurOrderCMapper.class).find(poc, 0, 0);
						if (pocList==null || pocList.size()==0) {
							this.getMapper(PurOrderMMapper.class).delete(pom.getContract_pk());
						}
					}else {
						//合同行重量不足
						throw new Exception("合同行重量不足默认重量【"+addWeight+"】");
					}
					
				}
			}
		}
		rm.setState("200");
		rm.setMsgInfo("删除成功");
		return rm;
	}
	
	
	/**
	 * 采购合同跟踪查询
	 * @param cp
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQuaryPurContractFollow(CommonPage<PurMatD> cp){
		ResultModel rm = new ResultModel();
		PurMatD pmd = cp.getObject();		
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		try {			
			List<HashMap> list = this.getMapper(PurMatDMapper.class).doQuaryPurContractFollow(pmd,startTime,endTime);
			rm.setState("200");
			rm.setData(list);
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;	
	}
	
}
