/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-08-13
 * 描述            ：采购计划主表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Pms.Demand.impl;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import market.Com.pb.DoubleUtil;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Demand.mapper.PurDemandCMapper;
import market.Pms.Demand.mapper.PurDemandMMapper;
import market.Pms.Demand.mapper.PurPlanCMapper;
import market.Pms.Demand.mapper.PurPlanMMapper;
import market.Pms.Demand.service.PurPlanMService;
import market.Pms.Demand.vo.PurDemandC;
import market.Pms.Demand.vo.PurDemandM;
import market.Pms.Demand.vo.PurPlanC;
import market.Pms.Demand.vo.PurPlanM;
import market.Pms.Mat.mapper.PurMatClassMapper;
import market.Pms.Mat.vo.PurMatClass;

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.mapper.UserMapper;
import com.hnshituo.core.auth.service.HomeService;
import com.hnshituo.core.auth.vo.User;

@RemoteService(path="PurPlanMService")
public class PurPlanMServiceImpl extends BaseServiceImpl<PurPlanM,Object> implements PurPlanMService {
	/**
	 * 计划信息查询
	 * 
	 * @param oci
	 * @return
	 */
	public ResultModel doQueryWeb(CommonPage<PurPlanM> oci) {
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
//		String userName = (String) this.getSession().getAttribute(
//				HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		PageModel<PurPlanM> pm = new PageModel<PurPlanM>(oci.getPageIndex(),
				oci.getPageSize());
		PurPlanM queryCls = oci.getObject() == null ? (new PurPlanM()) : oci
				.getObject();
		String startTime = oci.getStartTime();
		String endTime = oci.getEndTime();
		try {
			User user2=this.getMapper(UserMapper.class).findById(userId);
			String str="";
			if("资材备件科".equals(user2.getDept_name())||"原料科".equals(user2.getDept_name())){
				str+=user2.getDept_name();
			}
			long  i=this.getMapper(PurPlanMMapper.class).CountPlanM(
					queryCls, startTime, endTime,str);
			List<PurPlanM>  list=this.getMapper(PurPlanMMapper.class).findPlanM(queryCls,
					startTime, endTime,
					(oci.getPageIndex() - 1) * oci.getPageSize(),
					oci.getPageIndex() * oci.getPageSize(),str);
			pm.setTotal(i);
			pm.setRows(list);
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("错误：" + ex.getMessage());
			throw ex;
		}
		return rm;
	}
	/**
	 * 计划信息查询--导出
	 * 
	 * @param oci
	 * @return
	 */
	public ResultModel dodoExcel(CommonPage<PurPlanM> oci) {
		ResultModel rm = new ResultModel();
//		PageModel<PurPlanM> pm = new PageModel<PurPlanM>(oci.getPageIndex(),
//				oci.getPageSize());
		PurPlanM queryCls = oci.getObject() == null ? (new PurPlanM()) : oci
				.getObject();
		String startTime = oci.getStartTime();
		String endTime = oci.getEndTime();
		try {
//			long  i=this.getMapper(PurPlanMMapper.class).CountPlanM(
//					queryCls, startTime, endTime,null);
			List<PurPlanM>  list=this.getMapper(PurPlanMMapper.class).findPlanM(queryCls,
					startTime, endTime,
					(oci.getPageIndex() - 1) * oci.getPageSize(),
					oci.getPageIndex() * oci.getPageSize(),null);
			// 1，创建一个webbook，对应一个Excel文件
//			WritableWorkbook workbook;
			//2,设置用户下载路径
			String path = this.getRequest().getServletContext().getRealPath("/")+ "excel" + File.separator;  //临时保存路径
			File dir = new File(path);
			if(!dir.exists()) {
				new File(path).mkdir();
			}
			generateExcel(rm, list, path);
			rm.setState("200");
			rm.setMsgInfo("导出成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("导出失败，请联系管理员"+ex.getMessage());
		}
		return rm;
	}
	/**
	 *
	 * 报表打印
	 * **/
	private void generateExcel(ResultModel rm, List<PurPlanM> list, String path)
			throws IOException, WriteException, RowsExceededException {
		Calendar cal = Calendar.getInstance();
		String year=cal.get(Calendar.YEAR)+"年";
		String month=(cal.get(Calendar.MONTH)+1)+"月";
		String dept=cal.get(Calendar.DATE)+"日";
		String filename = year + month + dept + "计划信息报表";
		WritableWorkbook workbook;
		String file=filename+".xls";  //文件名
		//3. 操作EXCEL文件
		workbook = Workbook.createWorkbook(new File(path+file));
		WritableSheet sheet = workbook.createSheet("计划信息报表", 1);
		//行高
		sheet.getSettings().setDefaultRowHeight(300);
		//字体  参数可自行配置
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
		cellFormat1.setAlignment(Alignment.CENTRE);
		cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		//表头
		sheet.mergeCells(0, 0, 0, 1);
		sheet.addCell(new Label(0,0,"采购计划号",cellFormat1));

		sheet.mergeCells(1, 0, 1, 1);
		sheet.addCell(new Label(1,0,"采购分类",cellFormat1));

		sheet.mergeCells(2, 0, 2, 1);
		sheet.addCell(new Label(2,0,"数据状态",cellFormat1));

		sheet.mergeCells(3, 0, 3, 1);
		sheet.addCell(new Label(3,0,"审批状态",cellFormat1));

		sheet.mergeCells(4, 0, 4, 1);
		sheet.addCell(new Label(4,0,"预算总金额",cellFormat1));

		sheet.mergeCells(5, 0, 5, 1);
		sheet.addCell(new Label(5,0,"计划年月",cellFormat1));

		sheet.mergeCells(6, 0, 6, 1);
		sheet.addCell(new Label(6,0,"紧急程度",cellFormat1));

		sheet.mergeCells(7, 0, 7, 1);
		sheet.addCell(new Label(7,0,"申请单位",cellFormat1));

		sheet.mergeCells(8, 0, 8, 1);
		sheet.addCell(new Label(8,0,"申请人",cellFormat1));

		sheet.mergeCells(9, 0, 9, 1);
		sheet.addCell(new Label(9,0,"申请时间",cellFormat1));
		
		WritableFont font = new WritableFont(WritableFont.ARIAL,11,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat = new WritableCellFormat(font); 
		cellFormat.setAlignment(Alignment.CENTRE);
		cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		//时间转字符串的格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		double totalTheoryWeight = 0d, totalBalance_price=0d,totalAmount = 0d;
		for(int i = 0; i < list.size(); i++) {
			//计划号
			if(list.get(i).getPlan_no() != null && !"".equals(list.get(i).getPlan_no())) {
				sheet.addCell(new Label(0,i+2,list.get(i).getPlan_no(),cellFormat));
			}
			//采购分类
			if(list.get(i).getPru_type_name() != null && !"".equals(list.get(i).getPru_type_name() )) {
				sheet.addCell(new Label(1,i+2,list.get(i).getPru_type_name() ,cellFormat));
			}
			//数据状态
			if(list.get(i).getValidflag() != null && !"".equals(list.get(i).getValidflag() )) {
				if("10".equals(list.get(i).getValidflag())){
				      sheet.addCell(new Label(2,i+2,"草稿" ,cellFormat));
				}else if("20".equals(list.get(i).getValidflag())){
					  sheet.addCell(new Label(2,i+2,"生效" ,cellFormat));
				}
			}
			//审批状态
			if(list.get(i).getStatus() != null && !"".equals(list.get(i).getStatus() )) {
				if("00".equals(list.get(i).getStatus())){
				      sheet.addCell(new Label(3,i+2,"待提报" ,cellFormat));
				}else if("10".equals(list.get(i).getStatus())){
					  sheet.addCell(new Label(3,i+2,"待审批" ,cellFormat));
				}else if("20".equals(list.get(i).getStatus())){
					  sheet.addCell(new Label(3,i+2,"审批中" ,cellFormat));
				}else if("30".equals(list.get(i).getStatus())){
					  sheet.addCell(new Label(3,i+2,"审批拒绝" ,cellFormat));
				}else if("40".equals(list.get(i).getStatus())){
					  sheet.addCell(new Label(3,i+2,"审批退回" ,cellFormat));
				}else if("50".equals(list.get(i).getStatus())){
					  sheet.addCell(new Label(3,i+2,"审批通过" ,cellFormat));
				}
			}
			//预算总金额
			if(list.get(i).getTotalbudget_amt() != null && !"".equals(list.get(i).getTotalbudget_amt() )) {
				sheet.addCell(new Label(4,i+2," "+list.get(i).getTotalbudget_amt(),cellFormat));
			}
			//计划年月
			if(list.get(i).getBal_year_month() != null && !"".equals(list.get(i).getBal_year_month() )) {
				sheet.addCell(new Label(5,i+2," "+list.get(i).getBal_year_month(),cellFormat));
			}
			//紧急程度
			if(list.get(i).getUrgency_type_name() != null && !"".equals(list.get(i).getUrgency_type_name())) {
				sheet.addCell(new Label(6,i+2," "+list.get(i).getUrgency_type_name(),cellFormat));
			}
			//申请单位
			if(list.get(i).getApply_org_name() != null && !"".equals(list.get(i).getApply_org_name())) {
				sheet.addCell(new Label(7,i+2," "+list.get(i).getApply_org_name(),cellFormat));
			}
			//申请人
			if(list.get(i).getApply_org_name() != null && !"".equals(list.get(i).getApply_org_name())) {
				sheet.addCell(new Label(7,i+2," "+list.get(i).getApply_org_name(),cellFormat));
			}
			//申请时间
			if(list.get(i).getCreate_time() != null && !"".equals(list.get(i).getCreate_time() )) {
				sheet.addCell(new Label(7,i+2,sdf.format(list.get(i).getCreate_time()) ,cellFormat));
			}
			
			
		}

		sheet.addCell(new Label(0,list.size()+2,"总计",cellFormat));
		WritableCellFormat cellFormat2 = new WritableCellFormat(font); 
		cellFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
//		DecimalFormat df=new DecimalFormat("0.00");
		sheet.addCell(new Label(1,list.size()+2,""+list.size(),cellFormat2));//统计总条数
		sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
		sheet.getSettings().setVerticalFreeze(2);
		//关闭
		workbook.write();
		workbook.close();

		rm.setData("/download?filename="+file);
	}
	/**
	 * 计划信息需求接口查询
	 * 
	 * @param oci
	 * @return
	 */
	public ResultModel doPurDemandC(CommonPage<PurDemandM> oci) {
		ResultModel rm = new ResultModel();
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
//		String userName = (String) this.getSession().getAttribute(
//				HomeService.SESSION_USER_NAME);
		PageModel<PurDemandC> pm = new PageModel<PurDemandC>(oci.getPageIndex(),
				oci.getPageSize());
		PurDemandM pdm= oci.getObject() == null ? (new PurDemandM()) : oci
				.getObject();
		String startTime = oci.getStartTime();
		String endTime = oci.getEndTime();
		try {
			User user2=this.getMapper(UserMapper.class).findById(userId);
			String str="";
			if("资材备件科".equals(user2.getDept_name())||"原料科".equals(user2.getDept_name())){
				str+=user2.getDept_name();
			} 
			long  i=this.getMapper(PurDemandCMapper.class).CountPurDemandC(
					pdm, startTime, endTime,str);
			List<PurDemandC>  list=this.getMapper(PurDemandCMapper.class).findPurDemandC(pdm,
					startTime, endTime,
					(oci.getPageIndex() - 1) * oci.getPageSize(),
					oci.getPageIndex() * oci.getPageSize(),str);
			pm.setTotal(i);
			pm.setRows(list);
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("错误：" + ex.getMessage());
			throw ex;
		}
		return rm;
	}
	
	/**
	 * 计划信息新增
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddWeb(CommonPage<PurDemandC> oci) 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 (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入需新增的数据！");
			return rm;
		}
		User user2=this.getMapper(UserMapper.class).findById(userId);
		try {
			PurPlanM  ppm=new PurPlanM();
			PurDemandC pdc=oci.getObjectList().get(0);
			String plan_no = "JH"
					+ new SimpleDateFormat("yyyyMMdd").format(new Date());
			String maxD = this.getMapper(PurPlanMMapper.class)
					.findMaxPlanNo(plan_no);
			if (maxD != null && maxD.length() > 4) {
				String seq = maxD.substring(maxD.length() - 4);
				int iseq = Integer.parseInt(seq) + 1;
				plan_no += String.format("%04d", iseq);
			} else {
				plan_no += "0001";
			}
			String  deand_no=pdc.getDemand_no();
			PurDemandM pdm=this.getMapper(PurDemandMMapper.class).findById(deand_no);
			ppm.setDept_code(user2.getDept_id());//设置部门
			ppm.setDept_desc(user2.getDept_name());
		    ppm.setPru_type_code(pdm.getPru_type_code());//采购类型
		    ppm.setPru_type_name(pdm.getPru_type_name());
		    ppm.setUrgency_type_cede(pdm.getUrgency_type_cede());//紧急程度
		    ppm.setUrgency_type_name(pdm.getUrgency_type_name());
		    ppm.setBal_year_month(pdm.getBal_year_month());
			ppm.setPlan_no(plan_no);//计划号
			ppm.setValidflag("10");// 默认10草稿
			ppm.setStatus("00"); // 默认00待提报
			ppm.setApply_org_code(pdc.getApply_org_code());//部门代码
			ppm.setApply_org_name(pdc.getApply_org_name());//部门名称
			ppm.setCreate_userid(userId);
			ppm.setCreate_name(userName);
			ppm.setCreate_time(new Date());
			
			//这里接收需求行号通过的信息集合，先新增一条计划主信息，
			//再判断每条下面的需求行信息编辑量加已编辑量和核准量进行比较，进行计划行信息新增
			for (PurDemandC pdc2 : oci.getObjectList()) {
				PurPlanC  ppc=new PurPlanC();
//				String plan_sqe = "JH"
//						+ new SimpleDateFormat("yyyyMMdd").format(new Date()); 
				String plan_sqe = plan_no; 
				String maxplan_sqe = this.getMapper(PurPlanCMapper.class)
						.findMaxPlanSqe(plan_sqe);
				if (maxplan_sqe != null && maxplan_sqe.length() > 4) {
					String seq = maxplan_sqe.substring(maxplan_sqe.length() - 3);
					int iseq = Integer.parseInt(seq) + 1;
					plan_sqe += String.format("%03d", iseq);
				} else {
					plan_sqe += "001";
				}
				ppc.setPlan_sqe(plan_sqe);
				ppc.setPlan_no(ppm.getPlan_no());
				ppc.setDemand_sqe(pdc2.getDemand_sqe());//需求行号
				ppc.setMat_class_code(pdc2.getMat_class_code());
				ppc.setMat_class_name(pdc2.getMat_class_name());
				ppc.setItem_code(pdc2.getItem_code());//物料编码
				ppc.setItem_name(pdc2.getItem_name());
				ppc.setItem_desc(pdc2.getItem_desc());
				ppc.setItem_idx(pdc2.getItem_idx());
				ppc.setStandards_code(pdc2.getStandards_code());//标准代码
				ppc.setStandards_name(pdc2.getStandards_name());
				ppc.setSpec_name(pdc2.getSpec_name());//规格
				ppc.setSteel_code(pdc2.getSteel_code());//钢种牌号
				ppc.setSteel_name(pdc2.getSteel_name());
				ppc.setAttr_code(pdc2.getAttr_code());//属性
				ppc.setAttr_name(pdc2.getAttr_name());
				ppc.setDelivery_state_code(pdc2.getDelivery_state_code());//交货状态
				ppc.setDelivery_state_name(pdc2.getDelivery_state_name());
				Double  approval=DoubleUtil.add(pdc2.getQty_edit_val(), pdc2.getQty_val());
				if(approval>pdc2.getQty()){
//					rm.setState("500");
//					rm.setMsgInfo(ppc.getDemand_sqe()+"核准数量超过计划数量，请重新编辑");
//					return rm;
					throw new Exception(ppc.getDemand_sqe()+"核准数量超过计划数量，请重新编辑");
				}
				//统计该需求行下所有的累计核准数量
//				PurPlanC  ppc3=this.getMapper(PurPlanCMapper.class).findByDemandSqe(pdc2.getDemand_sqe());
//				if(ppc3.getDemand_sqe()!=null&&!"".equals(ppc3.getDemand_sqe())){
//				    Double  approval2=DoubleUtil.add(ppc3.getQty_yc_used(), ppc3.getQty_val());
//				    if(approval2>pdc2.getQty()){
//					rm.setState("500");
//					rm.setMsgInfo(ppc.getDemand_sqe()+"累计核准数量超过计划数量，请重新编辑");
//					return rm;
//				  }
//				}
				ppc.setQty(pdc2.getQty_edit_val());//需求行号的核准数量为这里的计划数量，计划核准数量先为空；			
				ppc.setQty_yc_used(approval);//预采已分配数量
				ppc.setQty_yc_useable(DoubleUtil.sub(pdc2.getQty(), approval));//预采可分配数量
				ppc.setUom_code(pdc2.getUom_code());//采购单位
				ppc.setUom_name(pdc2.getUom_name());
				ppc.setBudget_price(pdc2.getBudget_price());//预算单价
				if("".equals(ppc.getBudget_price())){
					ppc.setBudget_price(0d);
				}
				ppc.setBudget_amt(DoubleUtil.mul(ppc.getQty(), ppc.getBudget_price()));//预算总额
				ppc.setLast_delivery_date(pdc2.getLast_delivery_date());//交货日期
				ppc.setDelivery_location_code(pdc2.getDelivery_location_code());
				ppc.setDelivery_location(pdc2.getDelivery_location());//交货地址
				ppc.setReceive_type_code(pdc2.getReceive_type_code());//收货方式
				ppc.setReceive_type_name(pdc2.getReceive_type_name());
				ppc.setBudget_type_code(pdc2.getBudget_type_code());//预算类型
				ppc.setBudget_type_name(pdc2.getBudget_type_name());
				ppc.setUsage_kind_code(pdc2.getUsage_kind_code());//用途类型
				ppc.setUsage_kind_name(pdc2.getUsage_kind_name());
				ppc.setExpense_type_code(pdc2.getExpense_type_code());//费用类型
				ppc.setExpense_type_name(pdc2.getExpense_type_name());
				ppc.setValidflag("10");//默认草稿状态
				ppc.setStatus("00");//默认待审批状态
				PurMatClass  pmc=this.getMapper(PurMatClassMapper.class).findById(pdc2.getMat_class_code());
				ppc.setDept_code(pmc.getDept_code());//设置部门
				ppc.setDept_desc(pmc.getDept_desc());
				ppc.setUnit_code(pmc.getUnit_code());//设置科室
				ppc.setUnit_desc(pmc.getUnit_desc());
				ppc.setCreate_userid(userId);
				ppc.setCreate_name(userName);
				ppc.setCreate_time(new Date());
//				ppcList.add(ppc);
				this.getMapper(PurPlanCMapper.class).insert(ppc);
				ppm.setDept_code(pmc.getDept_code());//重新设置一次主信息部门
				ppm.setDept_desc(pmc.getDept_desc());
				ppm.setUnit_code(pmc.getUnit_code());//重新设置一次科室
				ppm.setUnit_desc(pmc.getUnit_desc());
			}

			this.getMapper(PurPlanMMapper.class).insert(ppm);
			rm.setState("200");
			rm.setMsgInfo("新增成功！");
		} catch (Exception ex) {
//			rm.setState("500");
//			rm.setMsgInfo("新增失败，请联系管理员");
			throw new Exception(ex.getMessage());
			
		}
		return rm;
	}
	/**
	 * 计划信息提报
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel upPurPlanM(CommonPage<PurPlanM> oci)
			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 (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		try {
			for (PurPlanM ppm : oci.getObjectList()) {
				PurPlanM ppm2=this.getMapper(PurPlanMMapper.class).findById(ppm.getPlan_no());
				ppm.setRemark(ppm2.getRemark());
				if ("10".equals(ppm2.getValidflag())
						&& ("00".equals(ppm2.getStatus()) || "40".equals(ppm2
								.getStatus()))) {
					// 主表
					ppm2.setStatus("10"); // 暂时提报即审批通过并且生效
					ppm2.setValidflag("20"); // 暂时生效
					ppm2.setUpdate_userid(userId);
					ppm2.setUpdate_name(userName);
					ppm2.setUpdate_time(new Date());
					this.getMapper(PurPlanMMapper.class).update(ppm2);
					// 从表
					PurPlanC ppc = new PurPlanC();
					ppc.setPlan_no(ppm.getPlan_no());
					List<PurPlanC> ppcList = this.getMapper(
							PurPlanCMapper.class).find(ppc, 0, 0);
					if (ppcList.size() > 0) {
						for (PurPlanC ppc2: ppcList) {
							ppc2.setStatus("10"); // 暂时提报即审批通过并且生效
							ppc2.setValidflag("20"); // 暂时生效
							ppc2.setUpdate_userid(userId);
							ppc2.setUpdate_name(userName);
							ppc2.setUpdate_time(new Date());
							this.getMapper(PurPlanCMapper.class).update(ppc2);
						}
					}
				} else {
					rm.setState("500");
					rm.setMsgInfo("提报失败，请联系管理员");
					return rm;
				}
			}

			rm.setState("200");
			rm.setMsgInfo("提报成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("提报失败，请联系管理员");
			throw ex;
		}
		return rm;
	}
	
	/**
	 * 计划信息提报撤销
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel disPurPlanM(CommonPage<PurPlanM> oci)
			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 (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		try {
			for (PurPlanM ppm : oci.getObjectList()) {
				PurPlanM ppm2=this.getMapper(PurPlanMMapper.class).findById(ppm.getPlan_no());
				ppm.setRemark(ppm2.getRemark());
				if ("20".equals(ppm2.getValidflag())
						&& ("10".equals(ppm2.getStatus()) || "40".equals(ppm2
								.getStatus()))) {
					// 主表
					ppm2.setStatus("00"); // 置为待提报
					ppm2.setValidflag("10"); // 置为草稿状态
					ppm2.setUpdate_userid(userId);
					ppm2.setUpdate_name(userName);
					ppm2.setUpdate_time(new Date());
					this.getMapper(PurPlanMMapper.class).update(ppm2);
					// 从表
					PurPlanC ppc = new PurPlanC();
					ppc.setPlan_no(ppm.getPlan_no());
					List<PurPlanC> ppcList = this.getMapper(
							PurPlanCMapper.class).find(ppc, 0, 0);
					if (ppcList.size() > 0) {
						for (PurPlanC ppc2: ppcList) {
							ppc2.setStatus("00"); //  置为待提报
							ppc2.setValidflag("10"); // 置为草稿状态
							ppc2.setUpdate_userid(userId);
							ppc2.setUpdate_name(userName);
							ppc2.setUpdate_time(new Date());
							this.getMapper(PurPlanCMapper.class).update(ppc2);
						}
					}
				} else {
					rm.setState("500");
					rm.setMsgInfo("当前数据不能提报撤销！");
					return rm;
				}
			}

			rm.setState("200");
			rm.setMsgInfo("提报撤销成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("提报撤销失败，请联系管理员");
			throw ex;
		}
		return rm;
	}
	/**
	 * 计划信息审批
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel appPurPlanM(CommonPage<PurPlanM> oci)
			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 (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		String memo1=oci.getMemo1();
		if(memo1==null&&"".equals(memo1)){
			rm.setState("500");
			rm.setMsgInfo("请选择操作！");
			return rm;
		}
		try {
			for (PurPlanM ppm2 : oci.getObjectList()) {
				PurPlanM pdm=this.getMapper(PurPlanMMapper.class).findById(ppm2.getPlan_no());
				pdm.setRemark(ppm2.getRemark());
				if ("10".equals(pdm.getStatus()) ) {
					if("1".equals(memo1)){
					// 主表
					pdm.setStatus("50"); //审批通过
					pdm.setUpdate_userid(userId);
					pdm.setUpdate_name(userName);
					pdm.setUpdate_time(new Date());
					this.getMapper(PurPlanMMapper.class).update(pdm);
					// 从表
					PurPlanC pdc = new PurPlanC();
					pdc.setPlan_no(pdm.getPlan_no());
					List<PurPlanC> pdcList = this.getMapper(
							PurPlanCMapper.class).find(pdc, 0, 0);
					if (pdcList.size() > 0) {
						for (PurPlanC pDc : pdcList) {
							if ("10".equals(pDc.getStatus())) {
							pDc.setStatus("50"); // 审批通过
							pDc.setUpdate_userid(userId);
							pDc.setUpdate_name(userName);
							pDc.setUpdate_time(new Date());
							this.getMapper(PurPlanCMapper.class).update(pDc);
							}
						}
					}
					}
					if("2".equals(memo1)){
						// 主表
						pdm.setStatus("40"); //审批退回
						pdm.setUpdate_userid(userId);
						pdm.setUpdate_name(userName);
						pdm.setUpdate_time(new Date());
						this.getMapper(PurPlanMMapper.class).update(pdm);
						// 从表
						PurPlanC pdc = new PurPlanC();
						pdc.setPlan_no(pdm.getPlan_no());
						List<PurPlanC> pdcList = this.getMapper(
								PurPlanCMapper.class).find(pdc, 0, 0);
						if (pdcList.size() > 0) {
							for (PurPlanC pDc : pdcList) {
								pDc.setStatus("40"); // 审批退回
								pDc.setUpdate_userid(userId);
								pDc.setUpdate_name(userName);
								pDc.setUpdate_time(new Date());
								this.getMapper(PurPlanCMapper.class).update(pDc);
							}
						}
						}
					 if("3".equals(memo1)){
						// 主表
						pdm.setStatus("30"); //审批拒绝
						pdm.setValidflag("00");//数据状态变为无效
						pdm.setUpdate_userid(userId);
						pdm.setUpdate_name(userName);
						pdm.setUpdate_time(new Date());
						this.getMapper(PurPlanMMapper.class).update(pdm);
						// 从表
						PurPlanC pdc = new PurPlanC();
						pdc.setPlan_no(pdm.getPlan_no());
						List<PurPlanC> pdcList = this.getMapper(
								PurPlanCMapper.class).find(pdc, 0, 0);
						if (pdcList.size() > 0) {
							for (PurPlanC pDc : pdcList) {
								pDc.setStatus("30"); // 审批拒绝
								pDc.setValidflag("00");//数据状态变为无效
								pDc.setUpdate_userid(userId);
								pDc.setUpdate_name(userName);
								pDc.setUpdate_time(new Date());
								this.getMapper(PurPlanCMapper.class).update(pDc);
							}
						}
						}
				} else {
					rm.setState("500");
					rm.setMsgInfo("数据状态不为待审批，请刷新界面！");
					return rm;
				}
			}

			rm.setState("200");
			rm.setMsgInfo("审批成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("审批失败，请联系管理员");
			throw ex;
		}
		return rm;
	}
	/**
	 * 计划信息删除
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDelete(CommonPage<PurPlanM> oci) 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 (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		try {
			for (PurPlanM pdc : oci.getObjectList()) {
				//数据状态无效或草稿状态。审批状态待提报、拒绝、退回。可进行删除操作。
				if (("00".equals(pdc.getValidflag())||"10".equals(pdc.getValidflag()))
						&& ("00".equals(pdc.getStatus()) || "30".equals(pdc
								.getStatus())|| "40".equals(pdc
								.getStatus()))) {
				//计划主表
				this.getMapper(PurPlanMMapper.class).delete(pdc.getPlan_no());	
				//计划从表
				this.getMapper(PurPlanCMapper.class).deleteByPlanNo(pdc.getPlan_no());	
				}else{
					rm.setState("500");
					rm.setMsgInfo("该数据不能删除！");
					return rm;
				}		
			}
			rm.setState("200");
			rm.setMsgInfo("删除成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("删除失败，请联系管理员");
			throw ex;
		}
		return rm;
	}
	
	/**
	 * @author 赵淋支
	 * @date   2018年11月1日
	 * @parameter 
	 * @return 
	 * @description 计划编制：自动审批
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAutoExamPurPlanM(CommonPage<PurPlanM> oci)
			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 (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		try {
			Date now = new Date();
			for (PurPlanM ppm : oci.getObjectList()) {
				PurPlanM ppm2=this.getMapper(PurPlanMMapper.class).findById(ppm.getPlan_no());
				if (ppm2==null) {
					rm.setState("500");
					rm.setMsgInfo("采购计划号["+ppm.getPlan_no()+"]的数据不存在，请重新查询！");
					return rm;
				}				
				if ("10".equals(ppm2.getValidflag())
						&& ("00".equals(ppm2.getStatus()))) {
					//草稿+待提报
					//主表
					PurPlanM newPPM = new PurPlanM();
					newPPM.setPlan_no(ppm2.getPlan_no());//ID
					newPPM.setValidflag("20"); //生效
					newPPM.setStatus("50"); //审批通过
					newPPM.setUpdate_userid(userId);
					newPPM.setUpdate_name(userName);
					newPPM.setUpdate_time(now);
					this.getMapper(PurPlanMMapper.class).update(newPPM);
					//从表
					PurPlanC ppc = new PurPlanC();
					ppc.setPlan_no(ppm.getPlan_no());
					ppc.setValidflag("10");//草稿
					ppc.setStatus("00");//待提报
					List<PurPlanC> ppcList = this.getMapper(
							PurPlanCMapper.class).find(ppc, 0, 0);
					if (ppcList!=null && ppcList.size() > 0) {
						for (PurPlanC ppc2: ppcList) {
							PurPlanC newPPC = new PurPlanC();
							newPPC.setPlan_sqe(ppc2.getPlan_sqe());//ID
							newPPC.setValidflag("20"); //生效
							newPPC.setStatus("50"); //审批通过
							newPPC.setUpdate_userid(userId);
							newPPC.setUpdate_name(userName);
							newPPC.setUpdate_time(now);
							this.getMapper(PurPlanCMapper.class).update(newPPC);
						}
					}
				} else {
					rm.setState("500");
					rm.setMsgInfo("状态不是待提报，无法自动审批！");
					return rm;
				}
			} 
			rm.setState("200");
			rm.setMsgInfo("自动审批成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("自动审批失败，请联系管理员:"+ex.getMessage());
			throw ex;
		}
		return rm;
	}
	
	/**
	 * @author 赵淋支
	 * @date   2018年11月1日
	 * @parameter 
	 * @return 
	 * @description 计划编制：撤销审批
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAutoCancelExamPurPlanM(CommonPage<PurPlanM> oci)
			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 (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		try {
			Date now = new Date();
			for (PurPlanM ppm : oci.getObjectList()) {
				PurPlanM ppm2=this.getMapper(PurPlanMMapper.class).findById(ppm.getPlan_no());
				if (ppm2==null) {
					rm.setState("500");
					rm.setMsgInfo("采购计划号["+ppm.getPlan_no()+"]的数据不存在，请重新查询！");
					return rm;
				}				
				if ("20".equals(ppm2.getValidflag())
						&& ("50".equals(ppm2.getStatus()))) {
					int count = this.getMapper(PurPlanCMapper.class).findIsPurchaseC(ppm2.getPlan_no());
					if (count > 0) {
						rm.setState("500");
						rm.setMsgInfo("采购计划号["+ppm.getPlan_no()+"]的采购单行信息已产生采购单信息，无法撤销审批！");
						return rm;
					}
					
					//生效+审批通过
					// 主表
					PurPlanM newPPM = new PurPlanM();
					newPPM.setPlan_no(ppm2.getPlan_no());//ID
					newPPM.setValidflag("10"); //草稿
					newPPM.setStatus("00"); //待提报
					newPPM.setUpdate_userid(userId);
					newPPM.setUpdate_name(userName);
					newPPM.setUpdate_time(now);
					this.getMapper(PurPlanMMapper.class).update(newPPM);
					// 从表
					PurPlanC ppc = new PurPlanC();
					ppc.setPlan_no(ppm.getPlan_no());
					ppc.setValidflag("20");//生效
					ppc.setStatus("50");//审批通过
					List<PurPlanC> ppcList = this.getMapper(
							PurPlanCMapper.class).find(ppc, 0, 0);
					if (ppcList!=null && ppcList.size() > 0) {
						for (PurPlanC ppc2: ppcList) {
							PurPlanC newPPC = new PurPlanC();
							newPPC.setPlan_sqe(ppc2.getPlan_sqe());//ID
							newPPC.setValidflag("10"); //草稿
							newPPC.setStatus("00"); //待提报
							newPPC.setUpdate_userid(userId);
							newPPC.setUpdate_name(userName);
							newPPC.setUpdate_time(now);
							this.getMapper(PurPlanCMapper.class).update(newPPC);
						}
					}
				} else {
					rm.setState("500");
					rm.setMsgInfo("状态不是审批通过，无法撤销审批！");
					return rm;
				}
			} 
			rm.setState("200");
			rm.setMsgInfo("撤销审批成功！");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("撤销审批失败，请联系管理员:"+ex.getMessage());
			throw ex;
		}
		return rm;
	}
	
}
