package com.ced.sip.purchase.self.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.ced.base.action.BaseAction;
import com.ced.base.exception.BaseException;
import com.ced.sip.common.AttachmentStatus;
import com.ced.sip.common.BaseDataInfosUtil;
import com.ced.sip.common.TableStatus;
import com.ced.sip.common.UserRightInfoUtil;
import com.ced.sip.common.WorkFlowStatus;
import com.ced.sip.common.biz.IAttachmentBiz;
import com.ced.sip.common.biz.IPurchaseRecordLogBiz;
import com.ced.sip.common.entity.Attachment;
import com.ced.sip.common.entity.PurchaseRecordLog;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.ExcelUtil;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.purchase.base.biz.IRequiredCollectBiz;
import com.ced.sip.purchase.base.entity.RequiredCollect;
import com.ced.sip.purchase.base.entity.RequiredCollectDetail;
import com.ced.sip.requirement.biz.IRequiredMaterialBiz;
import com.ced.sip.system.entity.Departments;
import com.ced.sip.system.entity.SystemConfiguration;
import com.ced.sip.workflow.base.service.SnakerEngineFacets;

public class PurchaseSelfAction extends BaseAction {
	@Autowired
	private SnakerEngineFacets facets;
	// 计划
	private IRequiredMaterialBiz iRequiredMaterialBiz;
	// 附件上传服务类
	private IAttachmentBiz iAttachmentBiz;
	//需求汇总分包
	private IRequiredCollectBiz iRequiredCollectBiz;
	//日志服务类
	private IPurchaseRecordLogBiz iPurchaseRecordLogBiz;

	private RequiredCollect requiredCollect;
	private RequiredCollectDetail requiredCollectDetail;
	private List<RequiredCollectDetail> rcdList;
	
	private String ids;
	private Departments departments;
	private PurchaseRecordLog purchaseRecordLog;

	
	/*********************************************************** 自主采购开始 **********************************************************/
	/**
	 * 查看自主采购列表
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String viewRequiredCollect() throws BaseException {
		
		try{
		} catch (Exception e) {
			log.error("查看自主采购信息列表错误！", e);
			throw new BaseException("查看自主采购信息列表错误！", e);
		}
		
		return VIEW ;
		
	}
	
	/**
	 * 查看自主采购信息列表
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String findRequiredCollect() throws BaseException {
		
		try{
			// 汇总 列表信息
			requiredCollect = new RequiredCollect();
			String bidCode=this.getRequest().getParameter("bidCode");
			requiredCollect.setBidCode(bidCode);
			String buyRemark=this.getRequest().getParameter("buyRemark");
			requiredCollect.setBuyRemark(buyRemark);
			
			requiredCollect.setBuyWay(TableStatus.PURCHASE_WAY_08);
			
			String rmCode=this.getRequest().getParameter("rmCode");
			if(StringUtil.isNotBlank(rmCode))
			{
				List<RequiredCollect> list=this.iRequiredCollectBiz.getRequiredCollecListByRmCode(rmCode);
				String condtion=" and (de.bid_Code='1' ";
				for(RequiredCollect rc:list){
					condtion+="or de.bid_Code='"+rc.getBidCode()+"'";
				}
				condtion+=")";
				requiredCollect.setCondition(condtion);
			}
			
			this.setListValue( this.iRequiredCollectBiz.getRequiredCollectList( this.getRollPageDataTables(), requiredCollect) ) ;
			if(this.getListValue()!=null&&this.getListValue().size()>0){
				for(int i=0;i<this.getListValue().size();i++){
					requiredCollect = (RequiredCollect) this.getListValue().get(i);
					requiredCollect.setWriterCn(BaseDataInfosUtil.convertLoginNameToChnName(requiredCollect.getWriter()));
					requiredCollect.setPurchaseDeptName(BaseDataInfosUtil
							.convertDeptIdToName(requiredCollect
									.getPurchaseDeptId()));
				}
			}
			this.getPagejsonDataTables(this.getListValue());
		} catch (Exception e) {
			log.error("查看自主采购信息列表错误！", e);
			throw new BaseException("查看自主采购信息列表错误！", e);
		}
		
		return null ;
		
	}
	/**
	 * 项目立项信息初始化
	 * @return
	 * @throws BaseException 
	 */
	public String saveRequiredCollectInit() throws BaseException {
		try{
			this.getRequest().setAttribute("now",DateUtil.getCurrentDateTime());
			departments=UserRightInfoUtil.getDepartments(this.getRequest());
			this.getRequest().setAttribute("purchaseDeptName",BaseDataInfosUtil.convertDeptIdToName(departments.getPurchaseDeptId()));
			this.getRequest().setAttribute("purchaseDeptId",departments.getPurchaseDeptId());
			this.getRequest().setAttribute("writerCn",UserRightInfoUtil.getChineseName(this.getRequest()));
			this.getRequest().setAttribute("writer",UserRightInfoUtil.getUserName(this.getRequest()));
			this.getRequest().setAttribute("deptName",departments.getDeptName());
			this.getRequest().setAttribute("deptId",departments.getDepId());
		} catch (Exception e) {
			log("项目立项信息初始化错误！", e);
			throw new BaseException("项目立项信息初始化错误！", e);
		}
		return ADD_INIT;
		
	}
	/**
	 * 修改汇总分包信息
	 * @return
	 * @throws BaseException
	 */
	public String saveRequiredCollect() throws BaseException {
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			SystemConfiguration systemConfiguration=BaseDataInfosUtil.convertSystemConfiguration(comId);
			if (requiredCollect.getRcId() == null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

				String bidCodePrefix =systemConfiguration.getRequiredCollectPrefix()+"-"+sdf.format(new Date());
				int floatCode = this.iRequiredCollectBiz.getMaxFloatCodeByPrefixStr(bidCodePrefix);
				requiredCollect.setBidCode(bidCodePrefix+"-" +(new DecimalFormat("0000").format( floatCode + 1 ) ));requiredCollect.setWriteDate(new Date());
				requiredCollect.setWriter(UserRightInfoUtil.getUserName(getRequest()));
				requiredCollect.setFloatCode( (long)floatCode + 1);
				requiredCollect.setStatus(WorkFlowStatus.WORK_FLOW_ORDER_STATUS_01);
				requiredCollect.setBuyWay(TableStatus.PURCHASE_WAY_08);
				this.iRequiredCollectBiz.saveRequiredCollect(requiredCollect);
			} else {
				requiredCollect.setStatus(WorkFlowStatus.WORK_FLOW_ORDER_STATUS_01);
				iRequiredCollectBiz.updateRequiredCollect(requiredCollect);
				// 删除附件
				iAttachmentBiz
						.deleteAttachments(parseAttachIds(requiredCollect
								.getAttIds()));
			}
			// 保存附件
			iAttachmentBiz.saveAttachmentAndUpload(this.setUploadFile(
					requiredCollect, requiredCollect.getRcId(),
					AttachmentStatus.ATTACHMENT_CODE_103, UserRightInfoUtil
							.getUserName(this.getRequest())));
			//删除老数据
			List<RequiredCollectDetail> oldRcdList = this.iRequiredCollectBiz.getRequiredCollectDetailList(requiredCollect.getRcId());
			for(RequiredCollectDetail rcd:oldRcdList){
				this.iRequiredMaterialBiz.updateRequiredMaterialYamountByRcdId(rcd.getRmdId(),rcd.getAmount(),0);
                this.iRequiredCollectBiz.deleteRequiredCollectDetail(rcd);
	         }
			
			// 保存新数据
			if (rcdList != null) {
				for (int i = 0; i < rcdList.size(); i++) {
					requiredCollectDetail = rcdList.get(i);
					if (requiredCollectDetail != null
							&& StringUtil.isNotBlank(requiredCollectDetail.getBuyCode().trim())) {
						requiredCollectDetail.setBidCode(requiredCollect.getBidCode());
						requiredCollectDetail.setRcId(requiredCollect.getRcId());
						requiredCollectDetail.setRmdId(requiredCollectDetail.getRmdId());
						requiredCollectDetail.setIsCollect(TableStatus.COLLECT_TYPE_1);
						iRequiredCollectBiz.saveRequiredCollectDetail(requiredCollectDetail);
						
						iRequiredMaterialBiz.updateRequiredMaterialYamountByRcdId(requiredCollectDetail.getRmdId(), requiredCollectDetail.getAmount(),1);
					}
				}
			}
			    
			String operateContent = "自主采购成功，标段号为【"+requiredCollect.getBidCode()+"】";
			purchaseRecordLog = new PurchaseRecordLog(null, null,requiredCollect.getRcId(), UserRightInfoUtil.getUserId(this.getRequest())+"", UserRightInfoUtil.getUserName(this.getRequest()), DateUtil.getCurrentDateTime(), operateContent,"创建自主采购");
			this.iPurchaseRecordLogBiz.savePurchaseRecordLog(purchaseRecordLog);
			
			
			this.getRequest().setAttribute("message", "新增成功");
			this.getRequest().setAttribute("operModule", "新增自主采购信息");
		} catch (Exception e) {
			log("新增自主采购信息错误！", e);
			throw new BaseException("新增自主采购信息错误！", e);
		}
		return VIEW;
	}

	/**
	 * 修改自主采购初始化
	 * 
	 * @return
	 * @throws BaseException
	 */
	public String updateRequiredCollectInit() throws BaseException {
		try {
			requiredCollect = this.iRequiredCollectBiz.getRequiredCollect(requiredCollect.getRcId());
			// 获取附件
			Map<String, Object> map = iAttachmentBiz
					.getAttachmentMap(new Attachment(
							requiredCollect.getRcId(),
							AttachmentStatus.ATTACHMENT_CODE_103));
			requiredCollect.setUuIdData((String) map.get("uuIdData"));
			requiredCollect.setFileNameData((String) map.get("fileNameData"));
			requiredCollect.setFileTypeData((String) map.get("fileTypeData"));
			requiredCollect.setAttIdData((String) map.get("attIdData"));
			requiredCollect.setAttIds((String) map.get("attIds"));
			
			this.getRequest().setAttribute("purchaseDeptName",BaseDataInfosUtil.convertDeptIdToName(requiredCollect.getPurchaseDeptId()));
			this.getRequest().setAttribute("writerCn",BaseDataInfosUtil.convertLoginNameToChnName(requiredCollect.getWriter()));
			this.getRequest().setAttribute("deptName",BaseDataInfosUtil.convertDeptIdToName(requiredCollect.getDeptId()));
			
			this.setListValue(this.iRequiredCollectBiz.getRequiredCollectDetailList(requiredCollect.getRcId()));

		} catch (Exception e) {
			log("修改自主采购信息初始化错误！", e);
			throw new BaseException("修改自主采购信息初始化错误！", e);
		}
		return MODIFY_INIT;
	}
	/**
	 * 删除立项
	 */
	public String deleteRequiredCollect() throws BaseException {
		try {
			ids = this.getRequest().getParameter("ids");
			// 页面所选汇总明细信息
			String[] idss = ids.split(",");
			for (int i = 0; i < idss.length; i++) {
				if (idss[i] != null) {
					RequiredCollect rc = this.iRequiredCollectBiz
							.getRequiredCollect(new Long(idss[i]));
					requiredCollect = rc;
					List rcdList = this.iRequiredCollectBiz
							.getRequiredCollectDetailList(requiredCollect
									.getRcId());
					for (int j = 0; j < rcdList.size(); j++) {
						RequiredCollectDetail rcd = (RequiredCollectDetail) rcdList.get(j);

						this.iRequiredMaterialBiz.updateRequiredMaterialYamountByRcdId(rcd.getRmdId(),rcd.getAmount(),0);
		                this.iRequiredCollectBiz.deleteRequiredCollectDetail(rcd);

					}
					this.iRequiredCollectBiz.deleteRequiredCollect(rc);
				}
			}
			PrintWriter out = this.getResponse().getWriter();
			String message = "删除成功";
			this.getRequest().setAttribute("message", "删除成功");
			this.getRequest().setAttribute("operModule", "删除立项信息");
			out.print(message);
		} catch (Exception e) {
			log("删除立项信息错误！", e);
			throw new BaseException("删除立项信息错误！", e);
		}

		// return viewRequiredPlan();
		return null;
	}

	/**
	 * 查看计划明细信息
	 * 
	 * @return
	 * @throws BaseException
	 */
	public String viewRequiredCollectDetail() throws BaseException {

		try {
			requiredCollect = this.iRequiredCollectBiz.getRequiredCollect(requiredCollect.getRcId());
			// 获取附件
			Map<String, Object> map = iAttachmentBiz
					.getAttachmentMap(new Attachment(
							requiredCollect.getRcId(),
							AttachmentStatus.ATTACHMENT_CODE_103));
			requiredCollect.setUuIdData((String) map.get("uuIdData"));
			requiredCollect.setFileNameData((String) map.get("fileNameData"));
			requiredCollect.setFileTypeData((String) map.get("fileTypeData"));
			requiredCollect.setAttIdData((String) map.get("attIdData"));
			requiredCollect.setAttIds((String) map.get("attIds"));
			
			this.getRequest().setAttribute("purchaseDeptName",BaseDataInfosUtil.convertDeptIdToName(requiredCollect.getPurchaseDeptId()));
			this.getRequest().setAttribute("writerCn",BaseDataInfosUtil.convertLoginNameToChnName(requiredCollect.getWriter()));
			this.getRequest().setAttribute("deptName",BaseDataInfosUtil.convertDeptIdToName(requiredCollect.getDeptId()));
			
			this.setListValue(this.iRequiredCollectBiz.getRequiredCollectDetailList(requiredCollect.getRcId()));
		
		} catch (Exception e) {
			log("查看计划明细信息错误！", e);
			throw new BaseException("查看计划明细信息错误！", e);
		}
		return DETAIL;

	}
	/**
	 * 立项信息Excel导出
	 * @return
	 * @throws BaseException 
	 */
	 public void  exportRequiredCollectExcel() throws BaseException{
		try{
		 List<String> titleList = new ArrayList<String>();
		 titleList.add("采购组织");
		 titleList.add("项目编号");
		 titleList.add("项目名称");
		 titleList.add("负责人");
		 titleList.add("编制日期");
		 
		 
		// 汇总 列表信息
		requiredCollect = new RequiredCollect();
		String bidCode=this.getRequest().getParameter("bidCode");
		requiredCollect.setBidCode(bidCode);
		String buyRemark=this.getRequest().getParameter("buyRemark");
		requiredCollect.setBuyRemark(buyRemark);
		requiredCollect.setBuyWay(TableStatus.PURCHASE_WAY_08);
		
		String rmCode=this.getRequest().getParameter("rmCode");
		if(StringUtil.isNotBlank(rmCode))
		{
			List<RequiredCollect> list=this.iRequiredCollectBiz.getRequiredCollecListByRmCode(rmCode);
			String condtion=" and (de.bid_Code='1' ";
			for(RequiredCollect rc:list){
				condtion+="or de.bid_Code='"+rc.getBidCode()+"'";
			}
			condtion+=")";
			requiredCollect.setCondition(condtion);
		}
			
		List<RequiredCollect> rclist =this.iRequiredCollectBiz.getRequiredCollectList( this.getRollPageDataTables(), requiredCollect) ;
			
     	 List<Object[]> objList = new ArrayList<Object[]>();
		 for (int i = 0; i < rclist.size(); i++) {
			 requiredCollect=(RequiredCollect)rclist.get(i);
			 if(StringUtil.isNotBlank(requiredCollect)){
				 requiredCollect.setWriterCn(BaseDataInfosUtil.convertLoginNameToChnName(requiredCollect.getWriter()));
				 requiredCollect.setDeptName(BaseDataInfosUtil.convertDeptIdToName(requiredCollect.getDeptId()));
				 requiredCollect.setPurchaseDeptName(BaseDataInfosUtil.convertDeptIdToName(requiredCollect.getPurchaseDeptId()));
				
				 //bidMonitor
				 Object[]  obj=new Object[]{
						 requiredCollect.getPurchaseDeptName(),
						 requiredCollect.getBidCode(),
						 requiredCollect.getBuyRemark(),
						 requiredCollect.getWriterCn(),
						 requiredCollect.getWriteDate()
				 };
				  objList.add(obj);
			 }
		 }
		// 输出的excel文件名
			String file = "自主采购信息.xls";
			String targetfile = this.getServletContext().getRealPath(file);
			// 输出的excel文件工作表名
			List<Map<String, Object>> excelList = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("worksheet", "自主采购信息");
			map.put("titleList", titleList);
			map.put("valueList", objList);
			excelList.add(map);
			// 输出的excel文件工作表名
			new ExcelUtil().expCommonExcel(targetfile,excelList);
			this.getResponse().setContentType("application/octet-stream; charset=utf-8");
			this.getResponse().setHeader("Content-Disposition", "attachment; filename="+new String(file.getBytes("gbk"),"iso-8859-1") );
			//this.getResponse().setHeader( "Set-Cookie", "name=value; HttpOnly"); 
			File files = new File(targetfile);
			FileInputStream is = new FileInputStream(files);
			OutputStream os = this.getResponse().getOutputStream();
			byte[] buff = new byte[1024];
			int readCount = 0;
			readCount = is.read(buff);
			while (readCount != -1) {
				os.write(buff, 0, readCount);
				readCount = is.read(buff);
			}
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}catch (Exception e) {
		log.error("导出自主采购信息列表错误！", e);
		throw new BaseException("导出自主采购信息列表错误！", e);
	}
	 }
	/*********************************************************** 自主采购结束 **********************************************************/
	
	
	public SnakerEngineFacets getFacets() {
		return facets;
	}

	public void setFacets(SnakerEngineFacets facets) {
		this.facets = facets;
	}

	public IRequiredMaterialBiz getiRequiredMaterialBiz() {
		return iRequiredMaterialBiz;
	}

	public void setiRequiredMaterialBiz(IRequiredMaterialBiz iRequiredMaterialBiz) {
		this.iRequiredMaterialBiz = iRequiredMaterialBiz;
	}

	public IAttachmentBiz getiAttachmentBiz() {
		return iAttachmentBiz;
	}

	public void setiAttachmentBiz(IAttachmentBiz iAttachmentBiz) {
		this.iAttachmentBiz = iAttachmentBiz;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public IRequiredCollectBiz getiRequiredCollectBiz() {
		return iRequiredCollectBiz;
	}

	public void setiRequiredCollectBiz(IRequiredCollectBiz iRequiredCollectBiz) {
		this.iRequiredCollectBiz = iRequiredCollectBiz;
	}

	public RequiredCollect getRequiredCollect() {
		return requiredCollect;
	}

	public void setRequiredCollect(RequiredCollect requiredCollect) {
		this.requiredCollect = requiredCollect;
	}

	public IPurchaseRecordLogBiz getiPurchaseRecordLogBiz() {
		return iPurchaseRecordLogBiz;
	}

	public void setiPurchaseRecordLogBiz(IPurchaseRecordLogBiz iPurchaseRecordLogBiz) {
		this.iPurchaseRecordLogBiz = iPurchaseRecordLogBiz;
	}

	public List<RequiredCollectDetail> getRcdList() {
		return rcdList;
	}

	public void setRcdList(List<RequiredCollectDetail> rcdList) {
		this.rcdList = rcdList;
	}
}
