package com.ced.sip.purchase.base.action.epp;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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.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.StringUtil;
import com.ced.sip.purchase.askPrice.util.AskProgressStatus;
import com.ced.sip.purchase.base.biz.IBidAwardBiz;
import com.ced.sip.purchase.base.biz.IBidProcessLogBiz;
import com.ced.sip.purchase.base.biz.IBidResultNoticeBiz;
import com.ced.sip.purchase.base.biz.IRequiredCollectBiz;
import com.ced.sip.purchase.base.entity.BidAward;
import com.ced.sip.purchase.base.entity.BidProcessLog;
import com.ced.sip.purchase.base.entity.BidResultNotice;
import com.ced.sip.purchase.base.entity.RequiredCollect;
import com.ced.sip.purchase.bidding.util.BiddingProgressStatus;
import com.ced.sip.purchase.tender.util.TenderProgressStatus;
import com.ced.sip.supplier.biz.ISupplierInfoBiz;
import com.ced.sip.supplier.entity.SupplierInfo;
import com.ced.sip.system.entity.SystemConfiguration;
/** 
 * 类名称：BidResultNoticeAction
 * 创建人：luguanglei 
 * 创建时间：2017-05-03
 */
public class BidResultNoticeAction extends BaseAction {

	// 中标通知书 
	private IBidResultNoticeBiz iBidResultNoticeBiz;
    //项目信息服务类
    private IRequiredCollectBiz iRequiredCollectBiz;
    //标段流程记录实例表
    private IBidProcessLogBiz iBidProcessLogBiz;
	//项目日志记录服务类
	private IPurchaseRecordLogBiz iPurchaseRecordLogBiz;

	private IAttachmentBiz iAttachmentBiz;
	//授标服务类
	private IBidAwardBiz iBidAwardBiz;
	
	private ISupplierInfoBiz iSupplierInfoBiz;

	private Long rcId;
    private String isDetail;
    
	// 中标通知书
	private BidResultNotice bidResultNotice;
	

    private RequiredCollect requiredCollect;
  	private BidProcessLog bidProcessLog;
    private PurchaseRecordLog purchaseRecordLog;
	/**
 	* 当流程监控执行关键节点时候需要更新标段监控表，同时更新当前节点的完成时间，插入下一个节点的接收时间
 	* @param rcId 项目id
 	* @param currProgress_Status 当前节点
 	* @param nextProgress_Status 下一个节点
 	* @param nextProgress_Status_Text 下一个节点的节点名称
 	* @author luguanglei
 	* @throws BaseException 
 	*/
 	private void updateBidMonitorAndBidProcessLog(Long rcId,Long currProgress_Status, Long nextProgress_Status,String nextProgress_Status_Text)throws BaseException{
 		//修改项目监控至下一个节点
 		requiredCollect=new RequiredCollect();
 		requiredCollect.setRcId(rcId);
 		requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
 	    if(requiredCollect.getServiceStatus()<nextProgress_Status){
 	    	requiredCollect.setServiceStatus(nextProgress_Status);
 	    	requiredCollect.setServiceStatusCn(nextProgress_Status_Text);
 	        this.iRequiredCollectBiz.updateRequiredCollect(requiredCollect);
 	    }
 	  //修改项目日志表的当前节点的完成时间
 	    bidProcessLog=new BidProcessLog();
 	    bidProcessLog.setRcId(rcId);
 	    bidProcessLog.setBidNode(currProgress_Status);
 	    bidProcessLog=this.iBidProcessLogBiz.getBidProcessLogByRcIdAndBidNode(bidProcessLog);
 	    bidProcessLog.setCompleteDate(DateUtil.getCurrentDateTime());
 	    this.iBidProcessLogBiz.updateBidProcessLog(bidProcessLog);
 	
 	}
 	/**
	 * 判断是否是编制人员
	 * @param bidMonitor
	 * @return
	 */
 	private  boolean isWriter(String writer){
		boolean isWriter=false;
		String username=UserRightInfoUtil.getUserName(this.getRequest());
		//当前登录人是不是编制人员
		if(username.equals(writer)) isWriter=true;
		return isWriter;
	}
	/**
	 * 查看中标通知书信息列表  采购监控
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String viewBidResultNoticeMonitor() throws BaseException {
		String view="bidResultNoticeMonitorDetail";
		try{
			
			requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
			
			if(!isWriter(requiredCollect.getWriter())) isDetail="detail";
			
			
			bidResultNotice=new BidResultNotice();
			bidResultNotice.setRcId(rcId);
			List<BidResultNotice> bidResultNoticeList=this.iBidResultNoticeBiz.getBidResultNoticeList(bidResultNotice);
			for(BidResultNotice bidResultNotice:bidResultNoticeList){
				bidResultNotice.setAttachmentUrl(iAttachmentBiz.getAttachmentPageUrl(
						iAttachmentBiz.getAttachmentList(new Attachment(bidResultNotice
								.getBrnId(), AttachmentStatus.ATTACHMENT_CODE_203)),
						"0", this.getRequest()));
			}
			
			this.getRequest().setAttribute("bidResultNoticeList", bidResultNoticeList);
			boolean falg=false;
			if(requiredCollect.getBuyWay().equals(TableStatus.PURCHASE_WAY_00)){
				falg=TenderProgressStatus.Progress_Status_30==requiredCollect.getServiceStatus();
			}else if(requiredCollect.getBuyWay().equals(TableStatus.PURCHASE_WAY_01)){
				falg=AskProgressStatus.Progress_Status_28==requiredCollect.getServiceStatus();
			}else if(requiredCollect.getBuyWay().equals(TableStatus.PURCHASE_WAY_02)){
				falg=BiddingProgressStatus.Progress_Status_28==requiredCollect.getServiceStatus();
			}
			//当前流程进度为问题解答 且项目状态为正常 且非查看页面
            if(TableStatus.BID_STATUS_1.equals(requiredCollect.getBidStatus())&&falg&&StringUtil.isBlank(isDetail))
			{   
            	view="bidResultNoticeMonitorUpdate";
			}
			
		} catch (Exception e) {
			log.error("查看中标通知书信息列表错误！", e);
			throw new BaseException("查看中标通知书信息列表错误！", e);
		}	
			
		return view ;
				
	}
	/**
	 * 中标通知书结束，整个采购执行完成
	 * @return
	 * @throws BaseException 
	 */
	public String updateBidResultNoticeMonitor() throws BaseException {
		String view="success";
		String text="",operateContent="";
		try{
			
			requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
			requiredCollect.setBidStatus(TableStatus.BID_STATUS_6);
			requiredCollect.setBidStatusCn(TableStatus.BID_STATUS_6_TEXT);
			this.iRequiredCollectBiz.updateRequiredCollect(requiredCollect);
			
			operateContent="中标通知书发布完成";
			if(requiredCollect.getBuyWay().equals(TableStatus.PURCHASE_WAY_00)){
			    text=TenderProgressStatus.Progress_Status_30_Text;
			    updateBidMonitorAndBidProcessLog(rcId, TenderProgressStatus.Progress_Status_30, TenderProgressStatus.Progress_Status_31, TenderProgressStatus.Progress_Status_31_Text);
			}else if(requiredCollect.getBuyWay().equals(TableStatus.PURCHASE_WAY_01)){
				text=AskProgressStatus.Progress_Status_29_Text;
				updateBidMonitorAndBidProcessLog(rcId, AskProgressStatus.Progress_Status_28, AskProgressStatus.Progress_Status_29, AskProgressStatus.Progress_Status_29_Text);
			}else if(requiredCollect.getBuyWay().equals(TableStatus.PURCHASE_WAY_02)){
				text=BiddingProgressStatus.Progress_Status_29_Text;
				updateBidMonitorAndBidProcessLog(rcId, BiddingProgressStatus.Progress_Status_28, BiddingProgressStatus.Progress_Status_29, BiddingProgressStatus.Progress_Status_29_Text);
			}
			
				
			//保存流程跟踪信息
			purchaseRecordLog = new PurchaseRecordLog();
			purchaseRecordLog.setOperateDate(DateUtil.getCurrentDateTime());
			purchaseRecordLog.setOperatorId(UserRightInfoUtil.getUserId(this.getRequest())+"");
			purchaseRecordLog.setOperatorName(UserRightInfoUtil.getUserName(this.getRequest()));
			purchaseRecordLog.setRcId(rcId);
			purchaseRecordLog.setOperateContent(operateContent);
			purchaseRecordLog.setBidNode(text);
			this.iPurchaseRecordLogBiz.savePurchaseRecordLog(purchaseRecordLog);
			
			this.getRequest().setAttribute("message","操作成功");
			this.getRequest().setAttribute("operModule", text+"成功");
		} catch (Exception e) {
			log("中标通知书结束，整个采购执行完成错误！", e);
			throw new BaseException("中标通知书结束，整个采购执行完成错误！", e);
		}
		return view;
		
	}
	/**
	 * 保存中标通知书信息初始化
	 * @return
	 * @throws BaseException 
	 */
	public String saveBidResultNoticeInit() throws BaseException {
		try{
			String supplierName="";
			BidAward bidAward=new BidAward();
			bidAward.setRcId(rcId);
		    List<BidAward> baList=new ArrayList<BidAward>();
		    List<Object[]> objectList=this.iBidAwardBiz.getBidAwardList(bidAward);
		    for(Object[] object:objectList){
		    	bidAward=(BidAward)object[0];
		    	supplierName=(String)object[1];
		    	bidAward.setSupplierName(supplierName);
		    	baList.add(bidAward);
		    }
		    this.getRequest().setAttribute("baList", baList);
		} catch (Exception e) {
			log("保存中标通知书信息初始化错误！", e);
			throw new BaseException("保存中标通知书信息初始化错误！", e);
		}
		return ADD_INIT;
		
	}
	
	/**
	 * 保存中标通知书信息
	 * @return
	 * @throws BaseException 
	 */
	public String saveBidResultNotice() throws BaseException {
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			String userName=UserRightInfoUtil.getUserName(getRequest());
			String status=this.getRequest().getParameter("status");
			bidResultNotice.setWriteDate(new Date());
			bidResultNotice.setWriter(userName);	
			this.iBidResultNoticeBiz.saveBidResultNotice(bidResultNotice);
			//保存附件
			bidResultNotice.setAttIdData(bidResultNotice.getAttIdData());
			bidResultNotice.setUuIdData(bidResultNotice.getUuIdData());
			bidResultNotice.setFileNameData(bidResultNotice.getFileNameData());
			bidResultNotice.setFileTypeData(bidResultNotice.getFileTypeData());			
			iAttachmentBiz.saveAttachmentAndUpload( this.setUploadFile( bidResultNotice, bidResultNotice.getBrnId(), AttachmentStatus.ATTACHMENT_CODE_203, userName) ) ;
			
			if(status.equals(TableStatus.WINNING_TYPE_0)){				
				String userNameCn=UserRightInfoUtil.getChineseName(this.getRequest());
				SupplierInfo supplierInfo=this.iSupplierInfoBiz.getSupplierInfo(bidResultNotice.getSupplierId());
				requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(bidResultNotice.getRcId());
				SystemConfiguration sysConfiguration=BaseDataInfosUtil.convertSystemConfiguration(requiredCollect.getComId()); 
				String subject="邮件提醒："+sysConfiguration.getSystemCurrentDept()+"发布的"+requiredCollect.getBuyRemark()+"中标通知书已经发放。",content=""+requiredCollect.getBuyRemark()+"("+requiredCollect.getBidCode()+")中标通知书已经发放，请尽快登录电子采购平台下载。";
				String smsTitle=sysConfiguration.getSystemCurrentDept()+"发布的"+requiredCollect.getBuyRemark()+"中标通知书已经发放。请尽快登录电子采购平台下载。"; 
				this.saveSendMailToUsers(supplierInfo.getContactEmail(), subject, content,userNameCn);
				this.saveSmsMessageToUsers(supplierInfo.getSupplierPhone(), smsTitle, userNameCn);
				this.saveSysMessage(userNameCn, userName, supplierInfo.getSupplierName(), supplierInfo.getSupplierId()+"", 1, smsTitle, comId);
			}
			this.getRequest().setAttribute("message", "添加成功");
			this.getRequest().setAttribute("operModule", "新增中标通知书");
		} catch (Exception e) {
			log("保存中标通知书信息错误！", e);
			throw new BaseException("保存中标通知书信息错误！", e);
		}
		
		return ADD_INIT;
		
	}
	
	/**
	 * 修改中标通知书信息初始化
	 * @return
	 * @throws BaseException 
	 */
	public String updateBidResultNoticeInit() throws BaseException {
		
		try{		
		    
			bidResultNotice=this.iBidResultNoticeBiz.getBidResultNotice(bidResultNotice.getBrnId() );
			//获取附件
			Map<String,Object> map=iAttachmentBiz.getAttachmentMap( new Attachment(bidResultNotice.getBrnId(), AttachmentStatus.ATTACHMENT_CODE_203 ) );
			bidResultNotice.setUuIdData((String)map.get("uuIdData"));
			bidResultNotice.setFileNameData((String)map.get("fileNameData"));
			bidResultNotice.setFileTypeData((String)map.get("fileTypeData"));
			bidResultNotice.setAttIdData((String)map.get("attIdData"));
			
			String supplierName="";
			BidAward bidAward=new BidAward();
			bidAward.setRcId(bidResultNotice.getRcId());
		    List<BidAward> baList=new ArrayList<BidAward>();
		    List<Object[]> objectList=this.iBidAwardBiz.getBidAwardList(bidAward);
		    for(Object[] object:objectList){
		    	bidAward=(BidAward)object[0];
		    	supplierName=(String)object[1];
		    	bidAward.setSupplierName(supplierName);
		    	baList.add(bidAward);
		    }
		    this.getRequest().setAttribute("baList", baList);
		} catch (Exception e) {
			log("修改中标通知书信息初始化错误！", e);
			throw new BaseException("修改中标通知书信息初始化错误！", e);
		}
		return MODIFY_INIT;
		
	}
	
	/**
	 * 修改中标通知书信息
	 * @return
	 * @throws BaseException 
	 */
	public String updateBidResultNotice() throws BaseException {
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			String userName=UserRightInfoUtil.getUserName(getRequest());
			String status=this.getRequest().getParameter("status");
			if(status.equals(TableStatus.WINNING_TYPE_0)){
				bidResultNotice.setPublishDate(new Date());
				bidResultNotice.setPublisher(UserRightInfoUtil.getUserName(getRequest()));
			}
			this.iBidResultNoticeBiz.updateBidResultNotice(bidResultNotice);
			//保存附件
			bidResultNotice.setAttIdData(bidResultNotice.getAttIdData());
			bidResultNotice.setUuIdData(bidResultNotice.getUuIdData());
			bidResultNotice.setFileNameData(bidResultNotice.getFileNameData());
			bidResultNotice.setFileTypeData(bidResultNotice.getFileTypeData());			
			iAttachmentBiz.saveAttachmentAndUpload( this.setUploadFile( bidResultNotice, bidResultNotice.getBrnId(), AttachmentStatus.ATTACHMENT_CODE_203, UserRightInfoUtil.getUserName(this.getRequest()) ) ) ;
			// 删除附件
			iAttachmentBiz.deleteAttachments( parseAttachIds( bidResultNotice.getAttIds() ) ) ;
			
			bidResultNotice.setAttIdData("[]");
			bidResultNotice.setUuIdData("[]");
			bidResultNotice.setFileNameData("[]");
			bidResultNotice.setFileTypeData("[]");	
			
			if(status.equals(TableStatus.WINNING_TYPE_0)){				
				String userNameCn=UserRightInfoUtil.getChineseName(this.getRequest());
				SupplierInfo supplierInfo=this.iSupplierInfoBiz.getSupplierInfo(bidResultNotice.getSupplierId());
				requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(bidResultNotice.getRcId());
				String subject="邮件提醒："+requiredCollect.getPurchaseDeptName()+"发布的"+requiredCollect.getBuyRemark()+"中标通知书已经发放。",content=""+requiredCollect.getBuyRemark()+"("+requiredCollect.getBidCode()+")中标通知书已经发放，请尽快登录电子采购平台下载。";
				String smsTitle=requiredCollect.getPurchaseDeptName()+"发布的"+requiredCollect.getBuyRemark()+"中标通知书已经发放。请尽快登录电子采购平台下载。"; 
				this.saveSendMailToUsers(supplierInfo.getContactEmail(), subject, content,userNameCn);
				this.saveSmsMessageToUsers(supplierInfo.getSupplierPhone(), smsTitle, userNameCn);
				this.saveSysMessage(userNameCn, userName, supplierInfo.getSupplierName(), supplierInfo.getSupplierId()+"", 1, smsTitle, comId);
			}
			this.getRequest().setAttribute("message", "修改成功");
			this.getRequest().setAttribute("operModule", "修改中标通知书");
		} catch (Exception e) {
			log("修改中标通知书信息错误！", e);
			throw new BaseException("修改中标通知书信息错误！", e);
		}
		return MODIFY_INIT;
	}
	
	/**
	 * 删除中标通知书信息
	 * @return
	 * @throws BaseException 
	 */
	public String deleteBidResultNotice() throws BaseException {
		try{
		    BidResultNotice bidResultNotice=new BidResultNotice();
			String ids=this.getRequest().getParameter("ids");
 			String[] str=ids.split(",");
 			for(int i=0;i<str.length;i++){
 				if(StringUtil.isNotBlank(str[i]))
 				{
	 				bidResultNotice=this.iBidResultNoticeBiz.getBidResultNotice(new Long(str[i]));
	 				this.iBidResultNoticeBiz.deleteBidResultNotice(bidResultNotice);
 				}
 			}
 			this.getRequest().setAttribute("message", "删除成功");
			this.getRequest().setAttribute("operModule", "删除中标通知书");
			PrintWriter out = this.getResponse().getWriter();			
			out.println("删除成功");
		} catch (Exception e) {
			log("删除中标通知书信息错误！", e);
			throw new BaseException("删除中标通知书信息错误！", e);
		}
		return null;
		
	}
	
	/**
	 * 查看中标通知书明细信息
	 * @return
	 * @throws BaseException 
	 */
	public String viewBidResultNoticeDetail() throws BaseException {
		
		try{
			bidResultNotice=this.iBidResultNoticeBiz.getBidResultNotice(bidResultNotice.getBrnId() );
		} catch (Exception e) {
			log("查看中标通知书明细信息错误！", e);
			throw new BaseException("查看中标通知书明细信息错误！", e);
		}
		return DETAIL;
		
	}
	/**
	 * 供应商中标信息
	 * @return
	 * @throws BaseException
	 */
    public String viewSupplierBehavior() throws BaseException{
    	try{
    		String supplierId=this.getRequest().getParameter("supplierId");
    		this.getRequest().setAttribute("supplierId", supplierId);
		} catch (Exception e) {
			log("查看供应商中标信息信息错误！", e);
			throw new BaseException("查看供应商中标信息信息错误！", e);
		}
		return "supplierBehavior";
    }
    /**
     * 供应商中标信息列表
     * @return
     * @throws BaseException
     */
    public String findSupplierBehavior() throws BaseException{
    	 try {
             Long comId = UserRightInfoUtil.getComId(getRequest());
             bidResultNotice = new BidResultNotice();
             requiredCollect= new RequiredCollect();
             requiredCollect.setComId(comId);
             Long supplierId = Long.parseLong(this.getRequest().getParameter("supplierId"));
             bidResultNotice.setSupplierId(supplierId);
             
             List<BidResultNotice> bidResultNoticeList=new ArrayList<BidResultNotice>();
             List<Object[]> list=this.iBidResultNoticeBiz.getSupplierBehavior(
                     this.getRollPageDataTables(), bidResultNotice, requiredCollect);
             for(Object[] obj:list){
            	 bidResultNotice = (BidResultNotice)obj[0];
            	 bidResultNotice.setWriter(BaseDataInfosUtil.convertLoginNameToChnName(bidResultNotice.getWriter()));
            	 bidResultNotice.setBidCode((String)obj[1]);
            	 bidResultNotice.setBuyRemark((String)obj[2]);
            	 bidResultNotice.setBuyWayCn(BaseDataInfosUtil.convertBuyWayToBuyType((String)obj[3]));
            	 bidResultNoticeList.add(bidResultNotice);
             }
             this.getPagejsonDataTables(bidResultNoticeList);
         } catch (Exception e) {
             log.error("查看核心供应商基本信息列表错误！", e);
             throw new BaseException("查看核心供应商基本信息列表错误！", e);
         }
         return null;
    }
	public IBidResultNoticeBiz getiBidResultNoticeBiz() {
		return iBidResultNoticeBiz;
	}

	public void setiBidResultNoticeBiz(IBidResultNoticeBiz iBidResultNoticeBiz) {
		this.iBidResultNoticeBiz = iBidResultNoticeBiz;
	}

	public BidResultNotice getBidResultNotice() {
		return bidResultNotice;
	}

	public void setBidResultNotice(BidResultNotice bidResultNotice) {
		this.bidResultNotice = bidResultNotice;
	}
	public IRequiredCollectBiz getiRequiredCollectBiz() {
		return iRequiredCollectBiz;
	}
	public void setiRequiredCollectBiz(IRequiredCollectBiz iRequiredCollectBiz) {
		this.iRequiredCollectBiz = iRequiredCollectBiz;
	}
	public IBidProcessLogBiz getiBidProcessLogBiz() {
		return iBidProcessLogBiz;
	}
	public void setiBidProcessLogBiz(IBidProcessLogBiz iBidProcessLogBiz) {
		this.iBidProcessLogBiz = iBidProcessLogBiz;
	}
	public IPurchaseRecordLogBiz getiPurchaseRecordLogBiz() {
		return iPurchaseRecordLogBiz;
	}
	public void setiPurchaseRecordLogBiz(IPurchaseRecordLogBiz iPurchaseRecordLogBiz) {
		this.iPurchaseRecordLogBiz = iPurchaseRecordLogBiz;
	}
	public IAttachmentBiz getiAttachmentBiz() {
		return iAttachmentBiz;
	}
	public void setiAttachmentBiz(IAttachmentBiz iAttachmentBiz) {
		this.iAttachmentBiz = iAttachmentBiz;
	}
	public Long getRcId() {
		return rcId;
	}
	public void setRcId(Long rcId) {
		this.rcId = rcId;
	}
	public String getIsDetail() {
		return isDetail;
	}
	public void setIsDetail(String isDetail) {
		this.isDetail = isDetail;
	}
	public IBidAwardBiz getiBidAwardBiz() {
		return iBidAwardBiz;
	}
	public void setiBidAwardBiz(IBidAwardBiz iBidAwardBiz) {
		this.iBidAwardBiz = iBidAwardBiz;
	}
	public ISupplierInfoBiz getiSupplierInfoBiz() {
		return iSupplierInfoBiz;
	}
	public void setiSupplierInfoBiz(ISupplierInfoBiz iSupplierInfoBiz) {
		this.iSupplierInfoBiz = iSupplierInfoBiz;
	}
	
}
