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

import java.io.PrintWriter;
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.BaseDataInfosUtil;
import com.ced.sip.common.DictStatus;
import com.ced.sip.common.TableStatus;
import com.ced.sip.common.UserRightInfoUtil;
import com.ced.sip.common.WorkFlowStatus;
import com.ced.sip.common.biz.IPurchaseRecordLogBiz;
import com.ced.sip.common.entity.PurchaseRecordLog;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.PasswordUtil;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.common.utils.encrypt.RSAEncrypt;
import com.ced.sip.purchase.tender.util.TenderProgressStatus;
import com.ced.sip.purchase.base.biz.IBidProcessLogBiz;
import com.ced.sip.purchase.base.biz.IBusinessResponseItemBiz;
import com.ced.sip.purchase.base.biz.IInviteSupplierBiz;
import com.ced.sip.purchase.base.biz.IRequiredCollectBiz;
import com.ced.sip.purchase.base.entity.BidProcessLog;
import com.ced.sip.purchase.base.entity.BusinessResponseItem;
import com.ced.sip.purchase.base.entity.InviteSupplier;
import com.ced.sip.purchase.base.entity.RequiredCollect;
import com.ced.sip.purchase.tender.biz.ITenderBidListBiz;
import com.ced.sip.purchase.tender.entity.TenderBidList;
import com.ced.sip.supplier.biz.ISupplierInfoBiz;
import com.ced.sip.supplier.entity.SupplierInfo;
/** 
 * 类名称：TenderBidListAction
 * 创建人：luguanglei 
 * 创建时间：2017-05-10
 */
public class TenderBidListAction extends BaseAction {

	// 招标信息 
	private ITenderBidListBiz iTenderBidListBiz;
	
	 //邀请供应商服务类
    private IInviteSupplierBiz iInviteSupplierBiz;
    //商务响应项服务类
    private IBusinessResponseItemBiz iBusinessResponseItemBiz;
    //项目信息服务类
    private IRequiredCollectBiz iRequiredCollectBiz;
	 //标段流程记录实例表
	 private IBidProcessLogBiz iBidProcessLogBiz;
	 //供应商服务类
	 private ISupplierInfoBiz iSupplierInfoBiz;
	 //项目日志记录服务类
	 private IPurchaseRecordLogBiz iPurchaseRecordLogBiz;
	
    
    private Long rcId;
    private String isDetail;
    
    private RequiredCollect requiredCollect;
	// 招标信息
	private TenderBidList tenderBidList;
	
    private InviteSupplier inviteSupplier;
    private BusinessResponseItem businessResponseItem;
    private PurchaseRecordLog purchaseRecordLog;
 	 private BidProcessLog bidProcessLog;
 	 private List<BusinessResponseItem> briList;

	/**
	* 当流程监控执行关键节点时候需要更新标段监控表，同时更新当前节点的完成时间，插入下一个节点的接收时间
	* @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);
	  //新增项目日志表的下一个节点的接收时间
	    bidProcessLog=new BidProcessLog();
	    bidProcessLog.setRcId(rcId);
	    bidProcessLog.setBidNode(nextProgress_Status);
	    bidProcessLog=this.iBidProcessLogBiz.getBidProcessLogByRcIdAndBidNode(bidProcessLog);
	    if(bidProcessLog.getBplId()==null){
	    bidProcessLog.setReceiveDate(DateUtil.getCurrentDateTime());
	    this.iBidProcessLogBiz.saveBidProcessLog(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 
	 */
	public String viewTenderBidListMonitor() throws BaseException {
		String view="tenderBidListMonitorDetail";
		try{
			
			requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
			
			if(!isWriter(requiredCollect.getWriter())) isDetail="detail";
			
			tenderBidList = new TenderBidList();
			tenderBidList.setRcId(rcId);
			List<TenderBidList> list=this.iTenderBidListBiz.getTenderBidListList(tenderBidList);
			if(list.size() >0 ){//计划信息存在
				tenderBidList = list.get(0);
				tenderBidList.setBidOpenAdminCn(BaseDataInfosUtil.convertUserIdToChnName(tenderBidList.getBidOpenAdmin()));
				
			}else{
				tenderBidList.setResponsibleUser(UserRightInfoUtil.getChineseName(this.getRequest()));
				tenderBidList.setResponsiblePhone(UserRightInfoUtil.getUserPhone(this.getRequest()));
				tenderBidList.setRcId(rcId);
				
			}
			if(TableStatus.SUPPLIER_TYPE_01.equals(requiredCollect.getSupplierType())){
           //邀请供应商
			inviteSupplier = new InviteSupplier();
			inviteSupplier.setRcId(rcId);
			List<InviteSupplier> sulist = this.iInviteSupplierBiz.getInviteSupplierList(inviteSupplier);
			String supplierId=",";
			String supplierType=",";
			String supplierName="";
			String returnVals="";
			for(int i=0;i<sulist.size();i++){
				inviteSupplier =  sulist.get(i);
				 supplierId +=inviteSupplier.getSupplierId()+",";
				 supplierName +=inviteSupplier.getSupplierName()+",";
				 supplierType +=inviteSupplier.getSourceCategory()+",";
				 returnVals+=inviteSupplier.getSupplierId()+":"+inviteSupplier.getSupplierName()+":"+inviteSupplier.getSourceCategory()+",";
				
			}
			returnVals = StringUtil.subStringLastOfSeparator(returnVals,',');
			this.getRequest().setAttribute("returnVals", returnVals);
			this.getRequest().setAttribute("supplierIds", supplierId);
			this.getRequest().setAttribute("supplierTypes", supplierType);
			
			}
			this.getRequest().setAttribute("supplierType", requiredCollect.getSupplierType());
			
		    //商务响应项
			businessResponseItem=new BusinessResponseItem();
			businessResponseItem.setRcId(rcId);
			List<BusinessResponseItem> businessResponseItemsList=this.iBusinessResponseItemBiz.getBusinessResponseItemList(businessResponseItem);
           this.getRequest().setAttribute("businessResponseItemsList", businessResponseItemsList);
			//公告未发布 且项目状态为正常 且非查看页面
            if(TableStatus.BID_STATUS_1.equals(requiredCollect.getBidStatus())&&TableStatus.NOTICE_TYPE_1.equals(requiredCollect.getIsSendNotice())&&StringUtil.isBlank(isDetail)&&(requiredCollect.getStatus().equals(WorkFlowStatus.WORK_FLOW_ORDER_STATUS_01)||requiredCollect.getStatus().equals(WorkFlowStatus.WORK_FLOW_ORDER_STATUS_3)))
			{   
	           	Map priceTypeMap = BaseDataInfosUtil.getDictInfoToMap(DictStatus.COMMON_DICT_TYPE_1702);
	       	    Map priceColumnTypeMap = BaseDataInfosUtil.getDictInfoToMap(DictStatus.COMMON_DICT_TYPE_1703);
	       	    this.getRequest().setAttribute("priceTypeMap", priceTypeMap);
	       	    this.getRequest().setAttribute("priceColumnTypeMap", priceColumnTypeMap);
	           	view="tenderBidListMonitorUpdate";
			}else{
				tenderBidList.setPriceTypeCn(BaseDataInfosUtil.convertDictCodeToName(tenderBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1702));
				tenderBidList.setPriceColumnTypeCn(BaseDataInfosUtil.convertDictCodeToName(tenderBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1703));
                if(UserRightInfoUtil.getUserId(this.getRequest()).equals(tenderBidList.getBidOpenAdmin()))
					this.getRequest().setAttribute("flag", true);
				else
					this.getRequest().setAttribute("flag", false);
				
			}
			
			
		} catch (Exception e) {
			log("通过项目进入招标信息错误！", e);
			throw new BaseException("通过项目进入招标信息错误！", e);
		}
		return view;
	}
	/**
	 * 保存招标信息 商务响应项  邀请供应商
	 * @return
	 * @throws BaseException 
	 */
	public String updateTenderBidList() throws BaseException {
		String view="success";
		try{
			tenderBidList.setOpenDate(DateUtil.StringToDate(tenderBidList.getOpenDateStr(),"yyyy-MM-dd HH:mm"));
			tenderBidList.setSalesDate(DateUtil.StringToDate(tenderBidList.getSalesDateStr(),"yyyy-MM-dd HH:mm"));
			tenderBidList.setSaleeDate(DateUtil.StringToDate(tenderBidList.getSaleeDateStr(),"yyyy-MM-dd HH:mm"));
			tenderBidList.setReturnDate(DateUtil.StringToDate(tenderBidList.getReturnDateStr(),"yyyy-MM-dd HH:mm"));	
			tenderBidList.setBidOpenPassword(PasswordUtil.genRandomNum(6));
			if(tenderBidList.getTblId()==null){
				tenderBidList.setWriteDate(new Date());
				tenderBidList.setWriter(UserRightInfoUtil.getUserName(getRequest()));
				tenderBidList.setPriceStatus(TableStatus.PRICE_STATUS_01);
				tenderBidList.setCalibtationStatus(TableStatus.CALIBTATION_STATUS_01);
				tenderBidList.setOpenStatus(TableStatus.OPEN_STATUS_01);
				this.iTenderBidListBiz.saveTenderBidList(tenderBidList);
			}else{
				this.iTenderBidListBiz.updateTenderBidList(tenderBidList);
				
				//删除
				this.iInviteSupplierBiz.deleteInviteSupplierByRcId(tenderBidList.getRcId());
				this.iBusinessResponseItemBiz.deleteBusinessResponseItemByRcId(tenderBidList.getRcId());
			}		
			
			requiredCollect=new RequiredCollect();
			requiredCollect.setRcId(tenderBidList.getRcId());
			requiredCollect.setBidReturnDate(tenderBidList.getReturnDate());
			requiredCollect.setBidOpenDate(tenderBidList.getOpenDate());
			this.iRequiredCollectBiz.updateRequiredCollectNodeByRequiredCollect(requiredCollect);
			
			Map<String,String> map=null;
			String publicKey,privateKey;
			//增加
			String supValue = this.getRequest().getParameter("supIds");
			String supTypeValue = this.getRequest().getParameter("supTypes");
			Long id;
			int type;
			SupplierInfo suppInfo;
			InviteSupplier inviteSupplier;
			if(!supValue.equals(",")){
				String[] supArr = supValue.split(",");
				String[] supTypeArr = supTypeValue.split(",");
				//System.out.println(supArr);
				for(int i=1;i<supArr.length;i++){
					if(supArr[i]!=null&&supArr[i]!=""){
						type=Integer.parseInt(supTypeArr[i]);
						id = Long.parseLong(supArr[i]);
						suppInfo = this.iSupplierInfoBiz.getSupplierInfo(id);
						inviteSupplier = new InviteSupplier();
						inviteSupplier.setRcId(tenderBidList.getRcId());
						inviteSupplier.setSupplierId(id);
						inviteSupplier.setSupplierName(suppInfo.getSupplierName());
						inviteSupplier.setWriteDate(DateUtil.getCurrentDateTime());
						inviteSupplier.setWriter(UserRightInfoUtil.getUserName(this.getRequest()));
						inviteSupplier.setPriceNum( new Long(0) ) ;
						inviteSupplier.setSupplierEmail(suppInfo.getContactEmail());
						inviteSupplier.setSupplierPhone(suppInfo.getMobilePhone());
						map=RSAEncrypt.genKeyPair();
						publicKey=map.get("publicKey");
						privateKey=map.get("privateKey");
						inviteSupplier.setPrivateKey(privateKey);
						inviteSupplier.setPublicKey(publicKey);
						inviteSupplier.setSourceCategory(type);
						this.iInviteSupplierBiz.saveInviteSupplier(inviteSupplier); 						
					}
				}
			}
			//增加商务响应项信息
			// 保存新数据
			if (briList != null) {
				for (int i = 0; i < briList.size(); i++) {
					businessResponseItem = briList.get(i);
					if (businessResponseItem != null) {
						businessResponseItem.setRcId(tenderBidList.getRcId());
						businessResponseItem.setWriteDate(DateUtil.getCurrentDateTime());
						businessResponseItem.setWriter(UserRightInfoUtil.getUserName(this.getRequest()));
						iBusinessResponseItemBiz.saveBusinessResponseItem(businessResponseItem);
					}
				}
			}
			String operateContent="招标计划已编制，招标日期为【"+DateUtil.getStringFromDate(tenderBidList.getOpenDate())+"】";
			updateBidMonitorAndBidProcessLog(tenderBidList.getRcId(), TenderProgressStatus.Progress_Status_20, TenderProgressStatus.Progress_Status_21, TenderProgressStatus.Progress_Status_21_Text);
				
			//保存流程跟踪信息
			purchaseRecordLog = new PurchaseRecordLog();
			purchaseRecordLog.setOperateDate(DateUtil.getCurrentDateTime());
			purchaseRecordLog.setOperatorId(UserRightInfoUtil.getUserId(this.getRequest())+"");
			purchaseRecordLog.setOperatorName(UserRightInfoUtil.getUserName(this.getRequest()));
			purchaseRecordLog.setRcId(tenderBidList.getRcId());
			purchaseRecordLog.setOperateContent(operateContent);
			purchaseRecordLog.setBidNode(TenderProgressStatus.Progress_Status_20_Text);
			this.iPurchaseRecordLogBiz.savePurchaseRecordLog(purchaseRecordLog);
			
			this.getRequest().setAttribute("message","操作成功");
			this.getRequest().setAttribute("operModule", "编制招标计划信息成功");
		} catch (Exception e) {
			log("编制招标计划信息错误！", e);
			throw new BaseException("编制招标计划信息错误！", e);
		}
		return view;
		
	}
	/**
	 * 通用方法判断消息当前登录人是否显示待办消息提示(采购流程界面)
	 * @return 0 不显示 1 显示
	 * @throws BaseException 
	 */
	public String messageBidMonitor() throws BaseException {
		String msg="0";
		PrintWriter out = null;
		try{
			out = this.getResponse().getWriter();
			requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
			boolean isWriter=isWriter(requiredCollect.getWriter());
			long currNode=requiredCollect.getServiceStatus();
			if(currNode==TenderProgressStatus.Progress_Status_27){
				tenderBidList=this.iTenderBidListBiz.getTenderBidListByRcId(rcId);
				if(UserRightInfoUtil.getUserId(this.getRequest()).equals(tenderBidList.getBidOpenAdmin())){
					msg="1";
				}
			}else{
				if(isWriter) msg="1";
			}
			out.print(msg);
		} catch (Exception e) {
			log("通用方法判断消息当前登录人是否显示待办消息提示(采购流程界面)！", e);
			throw new BaseException("通用方法判断消息当前登录人是否显示待办消息提示(采购流程界面)！", e);
		}
		return null;
		
	}
	/**
	 * 招标计划查看
	 * @return
	 * @throws BaseException 
	 */
	public String viewTenderBidListDetail() throws BaseException {
		requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
		tenderBidList=this.iTenderBidListBiz.getTenderBidListByRcId(rcId);
		if(TableStatus.SUPPLIER_TYPE_01.equals(requiredCollect.getSupplierType())){
       //邀请供应商
		inviteSupplier = new InviteSupplier();
		inviteSupplier.setRcId(rcId);
		List<InviteSupplier> sulist = this.iInviteSupplierBiz.getInviteSupplierList(inviteSupplier);
		String supplierId=",";
		String supplierType=",";
		String supplierName="";
		String returnVals="";
		for(int i=0;i<sulist.size();i++){
			inviteSupplier =  sulist.get(i);
			 supplierId +=inviteSupplier.getSupplierId()+",";
			 supplierName +=inviteSupplier.getSupplierName()+",";
			 supplierType +=inviteSupplier.getSourceCategory()+",";
			 returnVals+=inviteSupplier.getSupplierId()+":"+inviteSupplier.getSupplierName()+":"+inviteSupplier.getSourceCategory()+",";
			
		}
		returnVals = StringUtil.subStringLastOfSeparator(returnVals,',');
		this.getRequest().setAttribute("returnVals", returnVals);
		this.getRequest().setAttribute("supplierIds", supplierId);
		this.getRequest().setAttribute("supplierTypes", supplierType);
		
		}
		this.getRequest().setAttribute("supplierType", requiredCollect.getSupplierType());
		
	    //商务响应项
		businessResponseItem=new BusinessResponseItem();
		businessResponseItem.setRcId(rcId);
		List<BusinessResponseItem> businessResponseItemsList=this.iBusinessResponseItemBiz.getBusinessResponseItemList(businessResponseItem);
        this.getRequest().setAttribute("businessResponseItemsList", businessResponseItemsList);
				
		tenderBidList.setPriceTypeCn(BaseDataInfosUtil.convertDictCodeToName(tenderBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1702));
		tenderBidList.setPriceColumnTypeCn(BaseDataInfosUtil.convertDictCodeToName(tenderBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1703));
        return "tenderBidListMonitorDetail";
	}
	public ITenderBidListBiz getiTenderBidListBiz() {
		return iTenderBidListBiz;
	}
	public void setiTenderBidListBiz(ITenderBidListBiz iTenderBidListBiz) {
		this.iTenderBidListBiz = iTenderBidListBiz;
	}
	public IInviteSupplierBiz getiInviteSupplierBiz() {
		return iInviteSupplierBiz;
	}
	public void setiInviteSupplierBiz(IInviteSupplierBiz iInviteSupplierBiz) {
		this.iInviteSupplierBiz = iInviteSupplierBiz;
	}
	public IBusinessResponseItemBiz getiBusinessResponseItemBiz() {
		return iBusinessResponseItemBiz;
	}
	public void setiBusinessResponseItemBiz(
			IBusinessResponseItemBiz iBusinessResponseItemBiz) {
		this.iBusinessResponseItemBiz = iBusinessResponseItemBiz;
	}
	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 IRequiredCollectBiz getiRequiredCollectBiz() {
		return iRequiredCollectBiz;
	}
	public void setiRequiredCollectBiz(IRequiredCollectBiz iRequiredCollectBiz) {
		this.iRequiredCollectBiz = iRequiredCollectBiz;
	}
	public TenderBidList getTenderBidList() {
		return tenderBidList;
	}
	public void setTenderBidList(TenderBidList tenderBidList) {
		this.tenderBidList = tenderBidList;
	}
	public ISupplierInfoBiz getiSupplierInfoBiz() {
		return iSupplierInfoBiz;
	}
	public void setiSupplierInfoBiz(ISupplierInfoBiz iSupplierInfoBiz) {
		this.iSupplierInfoBiz = iSupplierInfoBiz;
	}
	public IPurchaseRecordLogBiz getiPurchaseRecordLogBiz() {
		return iPurchaseRecordLogBiz;
	}
	public void setiPurchaseRecordLogBiz(IPurchaseRecordLogBiz iPurchaseRecordLogBiz) {
		this.iPurchaseRecordLogBiz = iPurchaseRecordLogBiz;
	}
	public List<BusinessResponseItem> getBriList() {
		return briList;
	}
	public void setBriList(List<BusinessResponseItem> briList) {
		this.briList = briList;
	}
	public IBidProcessLogBiz getiBidProcessLogBiz() {
		return iBidProcessLogBiz;
	}
	public void setiBidProcessLogBiz(IBidProcessLogBiz iBidProcessLogBiz) {
		this.iBidProcessLogBiz = iBidProcessLogBiz;
	}
	
}
