package com.ced.sip.purchase.askPrice.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.StringUtil;
import com.ced.sip.common.utils.encrypt.RSAEncrypt;
import com.ced.sip.purchase.askPrice.biz.IAskBidListBiz;
import com.ced.sip.purchase.askPrice.entity.AskBidList;
import com.ced.sip.purchase.askPrice.util.AskProgressStatus;
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.supplier.biz.ISupplierInfoBiz;
import com.ced.sip.supplier.entity.SupplierInfo;

public class AskBidListAction extends BaseAction {
	 //询价信息服务类
     private IAskBidListBiz iAskBidListBiz;
     //邀请供应商服务类
     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 AskBidList askBidList;
     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 viewAskBidListMonitor() throws BaseException {
		String view="askBidListMonitorDetail";
		try{
			
			requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
			
			if(!isWriter(requiredCollect.getWriter())) isDetail="detail";
			
			askBidList = new AskBidList();
			askBidList=this.iAskBidListBiz.getAskBidListByRcId(rcId);
			if(askBidList.getAblId()!=null ){//清单计划存在
				
			}else{
				askBidList.setResponsibleUser(UserRightInfoUtil.getChineseName(this.getRequest()));
				askBidList.setResponsiblePhone(UserRightInfoUtil.getUserPhone(this.getRequest()));
				askBidList.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="askBidListMonitorUpdate";
			}else{
				askBidList.setPriceTypeCn(BaseDataInfosUtil.convertDictCodeToName(askBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1702));
				askBidList.setPriceColumnTypeCn(BaseDataInfosUtil.convertDictCodeToName(askBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1703));
			}
			
			
		} catch (Exception e) {
			log("通过项目进入询价计划错误！", e);
			throw new BaseException("通过项目进入询价计划错误！", e);
		}
		return view;
	}
	/**
	 * 保存询价计划 商务响应项  邀请供应商
	 * @return
	 * @throws BaseException 
	 */
	public String updateAskBidList() throws BaseException {
		String view="success";
		try{
			String userNameCn=UserRightInfoUtil.getChineseName(getRequest());
			String userName=UserRightInfoUtil.getUserName(this.getRequest());
			Long comId=UserRightInfoUtil.getComId(this.getRequest());
			askBidList.setAskDate(DateUtil.StringToDate(askBidList.getAskDateStr(),"yyyy-MM-dd HH:mm"));
			askBidList.setDecryptionDate(DateUtil.StringToDate(askBidList.getDecryptionDateStr(),"yyyy-MM-dd HH:mm"));
			askBidList.setReturnDate(DateUtil.StringToDate(askBidList.getReturnDateStr(),"yyyy-MM-dd HH:mm"));	
			askBidList.setPriceStatus(TableStatus.PRICE_STATUS_01);
			if(askBidList.getAblId()==null){
				askBidList.setWriteDate(new Date());
				askBidList.setWriter(userName);
				this.iAskBidListBiz.saveAskBidList(askBidList);
			}else{
				this.iAskBidListBiz.updateAskBidList(askBidList);
				
				//删除
				this.iInviteSupplierBiz.deleteInviteSupplierByRcId(askBidList.getRcId());
				this.iBusinessResponseItemBiz.deleteBusinessResponseItemByRcId(askBidList.getRcId());
			}	
			
			requiredCollect=new RequiredCollect();
			requiredCollect.setRcId(askBidList.getRcId());
			requiredCollect.setBidReturnDate(askBidList.getReturnDate());
			requiredCollect.setBidOpenDate(askBidList.getAskDate());
			this.iRequiredCollectBiz.updateRequiredCollectNodeByRequiredCollect(requiredCollect);
			
			Map<String,String> map=null;
			String publicKey,privateKey;
			//增加
			String supValue = this.getRequest().getParameter("supIds");
			String supTypeValue = this.getRequest().getParameter("supTypes");
			if(!supValue.equals(",")){
				String[] supArr = supValue.split(",");
				String[] supTypeArr = supTypeValue.split(",");
				Long id=0L;
				int type;
				SupplierInfo suppInfo=null;
				InviteSupplier inviteSupplier;
				//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(askBidList.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(askBidList.getRcId());
						businessResponseItem.setWriteDate(DateUtil.getCurrentDateTime());
						businessResponseItem.setWriter(UserRightInfoUtil.getUserName(this.getRequest()));
						iBusinessResponseItemBiz.saveBusinessResponseItem(businessResponseItem);
					}
				}
			}
			String operateContent="询价计划已编制，询价日期为【"+DateUtil.getStringFromDate(askBidList.getAskDate())+"】";
			updateBidMonitorAndBidProcessLog(askBidList.getRcId(), AskProgressStatus.Progress_Status_20, AskProgressStatus.Progress_Status_21, AskProgressStatus.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(askBidList.getRcId());
			purchaseRecordLog.setOperateContent(operateContent);
			purchaseRecordLog.setBidNode(AskProgressStatus.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(isWriter) msg="1";
			out.print(msg);
		} catch (Exception e) {
			log("通用方法判断消息当前登录人是否显示待办消息提示(采购流程界面)！", e);
			throw new BaseException("通用方法判断消息当前登录人是否显示待办消息提示(采购流程界面)！", e);
		}
		return null;
		
	}
	/**
	 * 询价项目询价计划
	 * @return
	 * @throws BaseException 
	 */
	public String viewAskBidListDetail() throws BaseException {

		requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
		askBidList=this.iAskBidListBiz.getAskBidListByRcId(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);
		askBidList.setPriceTypeCn(BaseDataInfosUtil.convertDictCodeToName(askBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1702));
		askBidList.setPriceColumnTypeCn(BaseDataInfosUtil.convertDictCodeToName(askBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1703));
		return "askBidListMonitorDetail";
	}
	public IAskBidListBiz getiAskBidListBiz() {
		return iAskBidListBiz;
	}
	public void setiAskBidListBiz(IAskBidListBiz iAskBidListBiz) {
		this.iAskBidListBiz = iAskBidListBiz;
	}
	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 AskBidList getAskBidList() {
		return askBidList;
	}
	public void setAskBidList(AskBidList askBidList) {
		this.askBidList = askBidList;
	}
	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;
	}
	
}
