/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-11-22
 * 描述            ：发票信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Pms.Settlement.impl;
import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Settlement.mapper.PurBalanceFMapper;
import market.Pms.Settlement.service.PurBalanceFService;
import market.Pms.Settlement.vo.PurBalanceF;
import market.Pms.Supp.mapper.PurSuppMMapper;
import market.Pms.Supp.vo.PurSuppM;
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;

@RemoteService(path="PurBalanceFService")
public class PurBalanceFServiceImpl extends BaseServiceImpl<PurBalanceF,Object> implements PurBalanceFService {

	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月28日
	 * @parameter 
	 * @return 
	 * @description 采购发票界面：查询
	 */
	public ResultModel doQuaryPurBalanceF(CommonPage<PurBalanceF> cp){
		ResultModel rm = new ResultModel();		
		try {
			String sWhere=""; 
			PurBalanceF pbf = cp.getObject();
			//票据号码
			if (pbf.getBills_key()!=null && !"".equals(pbf.getBills_key())) {
				sWhere += " and t.bills_key like '%"+pbf.getBills_key()+"%'";
			}
			//发票号码
			if (pbf.getBills_nos()!=null && !"".equals(pbf.getBills_nos())) {
				sWhere += " and t.bills_nos like '%"+pbf.getBills_nos()+"%'";
			}
			//开票方名称				
			if (pbf.getBills_supp_name()!=null && !"".equals(pbf.getBills_supp_name())) {
				sWhere += " and t.bills_supp_name like '%"+pbf.getBills_supp_name()+"%'";
			}
			//开票日期
			if (cp.getStartTime()!=null && !"".equals(cp.getStartTime())) {
				sWhere += " and t.bills_open_date >= to_date('"+cp.getStartTime()+" 00:00:00','yyyy-MM-dd HH24:MI:SS') ";
			}
			if (cp.getEndTime()!=null && !"".equals(cp.getEndTime())) {
				sWhere += " and t.bills_open_date <= to_date('"+cp.getEndTime()+" 23:59:59','yyyy-MM-dd HH24:MI:SS') ";
			}
			sWhere += " and t.validflag > '00'";			
			
			List<PurBalanceF> list =this.getMapper(PurBalanceFMapper.class).doQuaryPurBalanceF(sWhere);
			rm.setData(list);;
			rm.setState("200");
			rm.setMsgInfo("查询成功");		
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败！");
			throw e;
		}
		return rm;
	}

	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月28日
	 * @parameter 
	 * @return 
	 * @description 采购发票界面：新增
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddPurBalanceF(CommonPage<PurBalanceF> cp){
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String deptId = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_ID);
		String deptName = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_NAME);
		ResultModel rm = new ResultModel();	
		List<PurBalanceF> pbfList = cp.getObjectList();
		
		Date now = new Date();
		for (PurBalanceF PBF : pbfList) {
			String bills_key = "FP"+ new SimpleDateFormat("yyyyMMdd").format(now);								
			//票据号KEY值(FPYYYYMMDD)	
			String maxD = this.getMapper(PurBalanceFMapper.class).findBillsKey(bills_key);
			if (maxD != null && maxD.length() > 3) {
				String seq = maxD.substring(maxD.length() - 3);//最后三位流水号
				int iseq = Integer.parseInt(seq) + 1;//流水号+1
				bills_key += String.format("%03d", iseq);//补零操作
			} else {
				bills_key += "001";
			}
			PurBalanceF newPbf = new PurBalanceF();//票据号KEY值(FPYYYYMMDD+3位流水)
			newPbf.setBills_key(bills_key);//ID
			newPbf.setBills_nos(PBF.getBills_nos());//发票号码
			newPbf.setBills_codes(PBF.getBills_codes());//发票代码
			newPbf.setBills_tax_codes(PBF.getBills_tax_codes());//票面税号
			newPbf.setBills_type_code(PBF.getBills_type_code());//发票种类
			newPbf.setBills_type_name(PBF.getBills_type_name());
			
			//发票金额
			Double bills_with_tax_amt = PBF.getBills_with_tax_amt()==null?0:PBF.getBills_with_tax_amt();
			newPbf.setBills_with_tax_amt(bills_with_tax_amt);
			//税率
			newPbf.setBills_tax_rate_val(PBF.getBills_tax_rate_val());
			Double bills_tax_rate_val = (PBF.getBills_tax_rate_val()==null||"".equals(PBF.getBills_tax_rate_val()))?
					0:(Double.parseDouble(PBF.getBills_tax_rate_val())/100);
			
			//税额 = 发票金额  * 税率
			newPbf.setBills_tax_amt(bills_with_tax_amt * bills_tax_rate_val);
			//不含税金额 = 发票金额  * (1-税率 /100) = 发票金额 - 税额 
			newPbf.setBills_without_tax_amt(bills_with_tax_amt - newPbf.getBills_tax_amt());
			
			newPbf.setBills_purpose_code(PBF.getBills_purpose_code());//票据款用途
			newPbf.setBills_purpose_name(PBF.getBills_purpose_name());
			newPbf.setBills_supp_code(PBF.getBills_supp_code());//开票方名称(与供应商代码共用)
			newPbf.setBills_supp_name(PBF.getBills_supp_name());
			newPbf.setBills_entrust_name(PBF.getBills_entrust_name());//委托人
			newPbf.setBills_entrust_date(PBF.getBills_entrust_date());//委托时间
			newPbf.setBills_confirm_name(PBF.getBills_confirm_name());//签收人
			newPbf.setBills_confirm_date(PBF.getBills_confirm_date());//签收时间
			newPbf.setBills_path(PBF.getBills_path());//路径
			newPbf.setBills_open_date(PBF.getBills_open_date());//开票时间
			newPbf.setRemark(PBF.getRemark());//备注				
			newPbf.setDept_code(deptId);//管理部门代码
			newPbf.setDept_desc(deptName);//管理部门描叙 
			newPbf.setCreate_name(userName);
			newPbf.setCreate_userid(userId);
			newPbf.setCreate_time(now);
			this.getMapper(PurBalanceFMapper.class).insert(newPbf);
		}
		rm.setState("200");
		rm.setMsgInfo("新增成功");
		return rm;
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月28日
	 * @parameter 
	 * @return 
	 * @description 采购发票界面：修改编辑
	 */
	public ResultModel doEditPurBalanceF(CommonPage<PurBalanceF> cp){
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);		
		ResultModel rm = new ResultModel();	
		PurBalanceF PBF = cp.getObject();		 
		if (PBF!=null && PBF.getBills_key()!=null) {
			PurBalanceF pbf = this.getMapper(PurBalanceFMapper.class).findById(PBF.getBills_key());
			if (pbf!=null) {
				PurBalanceF newPbf = new PurBalanceF();
				newPbf.setBills_key(PBF.getBills_key());//ID
				newPbf.setBills_nos(PBF.getBills_nos());//发票号码
				newPbf.setBills_codes(PBF.getBills_codes());//发票代码
				newPbf.setBills_tax_codes(PBF.getBills_tax_codes());//票面税号
				newPbf.setBills_type_code(PBF.getBills_type_code());//发票种类
				newPbf.setBills_type_name(PBF.getBills_type_name());
				
				//发票金额
				Double bills_with_tax_amt = PBF.getBills_with_tax_amt()==null?0:PBF.getBills_with_tax_amt();
				newPbf.setBills_with_tax_amt(bills_with_tax_amt);
				//税率
				newPbf.setBills_tax_rate_val(PBF.getBills_tax_rate_val());
				Double bills_tax_rate_val = (PBF.getBills_tax_rate_val()==null||"".equals(PBF.getBills_tax_rate_val()))?
						0:(Double.parseDouble(PBF.getBills_tax_rate_val())/100);
				
				//税额 = 发票金额  * 税率
				newPbf.setBills_tax_amt(bills_with_tax_amt * bills_tax_rate_val);
				//不含税金额 = 发票金额  * (1-税率 /100) = 发票金额 - 税额 
				newPbf.setBills_without_tax_amt(bills_with_tax_amt - newPbf.getBills_tax_amt());
				
				newPbf.setBills_purpose_code(PBF.getBills_purpose_code());//票据款用途
				newPbf.setBills_purpose_name(PBF.getBills_purpose_name());
				newPbf.setBills_supp_code(PBF.getBills_supp_code());//开票方名称(与供应商代码共用)
				newPbf.setBills_supp_name(PBF.getBills_supp_name());
				newPbf.setBills_entrust_name(PBF.getBills_entrust_name());//委托人
				newPbf.setBills_entrust_date(PBF.getBills_entrust_date());//委托时间
				newPbf.setBills_confirm_name(PBF.getBills_confirm_name());
				newPbf.setBills_confirm_date(PBF.getBills_confirm_date());//签收时间
				newPbf.setBills_open_date(PBF.getBills_open_date());//开票时间
				newPbf.setBills_path(PBF.getBills_path());//路径
				newPbf.setRemark(PBF.getRemark());//备注
				newPbf.setUpdate_name(userName);
				newPbf.setUpdate_userid(userId);
				newPbf.setUpdate_time(new Date());
				this.getMapper(PurBalanceFMapper.class).update(newPbf);
			}else {
				rm.setState("500");
				rm.setMsgInfo("当前数据不允许进行修改");
				return rm;
			}
		}
		rm.setState("200");
		rm.setMsgInfo("修改成功");
		return rm;
	}
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2018年11月28日
	 * @parameter 
	 * @return 
	 * @description 采购发票界面：删除
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDeletePurBalanceF(CommonPage<PurBalanceF> cp)
			throws Exception {
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		if (cp.getObjectList() == null || cp.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}

		Date now = new Date();
		for (PurBalanceF PBF : cp.getObjectList()) {
			PurBalanceF pbf=this.getMapper(PurBalanceFMapper.class).findById(PBF.getBills_key());
			if (pbf!=null && "10".equals(pbf.getValidflag())) {//10：未挂账
				PurBalanceF newPbf = new PurBalanceF();
				newPbf.setBills_key(pbf.getBills_key());
				newPbf.setValidflag("00");//无效		
				newPbf.setUpdate_userid(userId);
				newPbf.setUpdate_name(userName);
				newPbf.setUpdate_time(now);
				this.getMapper(PurBalanceFMapper.class).update(newPbf);
			} else {
				throw new Exception("当前数据不允许进行删除");
			}
		} 
		rm.setState("200");
		rm.setMsgInfo("删除成功！");
		return rm;
	}
	
	
	// SELECT SUPP_CODE,SUPP_NAME  FROM PUR_SUPP_M VALIDFLAG=1 AND STATUS =50
	public ResultModel doQueryPurSuppM(CommonPage<PurSuppM> cp){
		ResultModel rm=new ResultModel();
		try{
			PurSuppM psm = new PurSuppM();
			//psm.setStatus("50");
			psm.setValidflag("1");//有效
			List<PurSuppM> lists = this.getMapper(PurSuppMMapper.class).findWithCondition(psm, null, "supp_name", 0, 0);			
			rm.setData(lists);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("错误："+ex.getMessage());
		}
		return rm;
	}
	
	
	/**
	 * 
	 * @author 赵淋支
	 * @date   2019年1月6日
	 * @parameter 
	 * @return 
	 * @description 采购发票的导入
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doImport() 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(PurBalanceFServiceImpl.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数据
			try {
				//第一个表单
				Sheet sheet = wb.getSheetAt(0);
				//行数
				int numRow = sheet.getLastRowNum();
				if (numRow >= 4) {
					Date now = new Date();
					String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
					String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
					
					// 从第5行开始读取
					String cell0,cell1,cell2,cell3,cell4,cell5,cell6,cell7,cell8,cell9,cell10,cell11,cell12;
					for (int i = 4; i <= numRow; i++) {
						Row row = sheet.getRow(i);
						//处理行数据
						cell0 = ImportUtil.getCellValue(row.getCell(0));		//开票日期
						cell1 = ImportUtil.getCellValue(row.getCell(1));		//发票号
						cell2 = ImportUtil.getCellValue(row.getCell(2));		//合同号
						cell3 = ImportUtil.getCellValue(row.getCell(3));		//发票价税合计
						cell4 = ImportUtil.getCellValue(row.getCell(4));		//发票金额
						cell5 = ImportUtil.getCellValue(row.getCell(5));		//发票税额
						cell6 = ImportUtil.getCellValue(row.getCell(6));		//重量
						cell7 = ImportUtil.getCellValue(row.getCell(7));		//金额
						cell8 = ImportUtil.getCellValue(row.getCell(8));		//运费
						cell9 = ImportUtil.getCellValue(row.getCell(9));		//水运重量
						cell10= ImportUtil.getCellValue(row.getCell(10));		//水运金额
						cell11= ImportUtil.getCellValue(row.getCell(11));		//备注
						cell12= ImportUtil.getCellValue(row.getCell(12));		//客户名称
						
						PurBalanceF pbf = new PurBalanceF();
						//开票日期
						if (!"".equals(cell0)) {
							pbf.setBills_open_date(new SimpleDateFormat("yyyy-MM-dd").parse(cell0));
						}
						//发票号()
						cell1 = cell1.replace("'", "");
						String condition = "bills_nos = '"+cell1+"' and validflag > '00' ";
						List<PurBalanceF> pbfList = this.getMapper(PurBalanceFMapper.class).findWithCondition(null, condition, null, 0, 0);
						if (pbfList!=null && pbfList.size() > 0) {
							throw new Exception("发票号【"+cell1+"】已经存在");
						}
						pbf.setBills_nos(cell1);
						pbf.setBills_codes(cell1);
						//合同号
						pbf.setContract_no(cell2.replace("'", ""));
						//票据总金额
						pbf.setBills_with_tax_amt("".equals(cell3)?0.d:Double.parseDouble(cell3));
						//票据不含税金额
						pbf.setBills_without_tax_amt("".equals(cell4)?0.d:Double.parseDouble(cell4));
						//发票税额
						pbf.setBills_tax_amt("".equals(cell5)?0.d:Double.parseDouble(cell5));
						//重量
						pbf.setWeight("".equals(cell6)?0.d:Double.parseDouble(cell6));
						//金额
						pbf.setWeight("".equals(cell7)?0.d:Double.parseDouble(cell7));
						//运费
						pbf.setWeight("".equals(cell8)?0.d:Double.parseDouble(cell8));
						//水运重量
						pbf.setWeight("".equals(cell9)?0.d:Double.parseDouble(cell9));
						//水运金额
						pbf.setWeight("".equals(cell10)?0.d:Double.parseDouble(cell10));
						//备注
						pbf.setRemark(cell11);	
						//客户名称--供应商名称
						pbf.setBills_supp_name(cell12); 
						//System.out.println("发票税额:"+pbf.getBills_tax_amt()+";  发票号"+pbf.getBills_codes());
						//创建时间为导入时间
						pbf.setCreate_time(now);
						//创建人为导入人
						pbf.setCreate_name(userName);
						pbf.setCreate_userid(userId);
						// 设置主键ID
						String bills_key = "FP"+ new SimpleDateFormat("yyyyMMdd").format(new SimpleDateFormat("yyyy-MM-dd").parse(cell0));								
						//票据号KEY值(FPYYYYMMDD)	
						String maxD = this.getMapper(PurBalanceFMapper.class).findBillsKey(bills_key);
						if (maxD != null && maxD.length() > 3) {
							String seq = maxD.substring(maxD.length() - 3);//最后三位流水号
							int iseq = Integer.parseInt(seq) + 1;//流水号+1
							bills_key += String.format("%03d", iseq);//补零操作
						} else {
							bills_key += "001";
						}
						pbf.setBills_key(bills_key);
						// 将数据写入到数据库
						this.getMapper(PurBalanceFMapper.class).insert(pbf);
					}
				}
			} catch (Exception e) {
				throw new Exception("Excel表格数据读取失败！" + e.getMessage());
			}
			return rm; 
		} 	
	}
	
	
	
	
	
	
	 
}
