package com.ced.sip.contract.action.epp;

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.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.entity.HistoryOrder;
import org.snaker.engine.entity.Order;
import org.snaker.engine.entity.Task;
import org.springframework.beans.factory.annotation.Autowired;

import com.ced.base.action.BaseAction;
import com.ced.base.exception.BaseException;
import com.ced.base.utils.GlobalSettingBase;
import com.ced.sip.common.AttachmentStatus;
import com.ced.sip.common.BaseDataInfosUtil;
import com.ced.sip.common.DictStatus;
import com.ced.sip.common.UserRightInfoUtil;
import com.ced.sip.common.WorkFlowStatus;
import com.ced.sip.common.WorkFlowStatusMap;
import com.ced.sip.common.biz.IAttachmentBiz;
import com.ced.sip.common.entity.Attachment;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.MoneyUtil;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.contract.biz.IContractClassBiz;
import com.ced.sip.contract.biz.IContractConfirmBiz;
import com.ced.sip.contract.biz.IContractInfoBiz;
import com.ced.sip.contract.biz.IContractMaterialBiz;
import com.ced.sip.contract.biz.IContractTemplateBiz;
import com.ced.sip.contract.entity.ContractClass;
import com.ced.sip.contract.entity.ContractConfirm;
import com.ced.sip.contract.entity.ContractInfo;
import com.ced.sip.contract.entity.ContractMaterial;
import com.ced.sip.contract.entity.ContractTemplate;
import com.ced.sip.contract.util.ContractStatus;
import com.ced.sip.contract.util.alertFile.WordTemplateUtilities;
import com.ced.sip.purchase.base.biz.IBidAwardBiz;
import com.ced.sip.purchase.base.biz.IBidAwardDetailBiz;
import com.ced.sip.purchase.base.biz.IRequiredCollectBiz;
import com.ced.sip.purchase.base.entity.BidAward;
import com.ced.sip.purchase.base.entity.BidAwardDetail;
import com.ced.sip.purchase.base.entity.RequiredCollect;
import com.ced.sip.purchase.base.entity.RequiredCollectDetail;
import com.ced.sip.supplier.biz.ISupplierInfoBiz;
import com.ced.sip.supplier.entity.SupplierInfo;
import com.ced.sip.system.biz.ISysCompanyBiz;
import com.ced.sip.system.entity.Dictionary;
import com.ced.sip.system.entity.SysCompany;
import com.ced.sip.system.entity.SystemConfiguration;
import com.ced.sip.system.entity.Users;
import com.ced.sip.workflow.base.service.SnakerEngineFacets;
/** 
 * 类名称：ContractInfoAction
 * 创建人：luguanglei 
 * 创建时间：2017-07-19
 */
public class ContractInfoAction extends BaseAction {

	@Autowired
	private SnakerEngineFacets facets; 
	//上传文件存放路径   
    private final static String UPLOADDIR = "upload/contract/";
	// 合同信息 
	private IContractInfoBiz iContractInfoBiz;
	//合同明细信息
	private IContractMaterialBiz iContractMaterialBiz;
	//合同字典信息
	private IContractClassBiz iContractClassBiz;
	//项目信息
	private IRequiredCollectBiz iRequiredCollectBiz;
	//授标信息
	private IBidAwardBiz iBidAwardBiz;
	//授标明细信息
	private IBidAwardDetailBiz iBidAwardDetailBiz;
	//供应商服务类
	private ISupplierInfoBiz iSupplierInfoBiz;
	//采购单位服务类
	private ISysCompanyBiz iSysCompanyBiz;
	//合同模版服务类
	private IContractTemplateBiz iContractTemplateBiz;
	//合同确认信息
	private IContractConfirmBiz iContractConfirmBiz;
	// 附件上传服务类
	private IAttachmentBiz iAttachmentBiz;
	
	
	// 合同信息
	private ContractInfo contractInfo;
	
	private ContractMaterial contractMaterial;
	
	private ContractConfirm contractConfirm;
	// 授标
	private BidAward bidAward;
	
	private RequiredCollect requiredCollect;
	
    private RequiredCollectDetail requiredCollectDetail;

	private List<ContractMaterial> cmList;
	
    private SupplierInfo supplierInfo;
    
    private SysCompany sysCompany;
    
	private ContractClass contractClass;
	
	private ContractTemplate contractTemplate;
	/**
	 * 查看合同信息信息列表
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String viewContractInfo() throws BaseException {
		String initPage="view";
		try{
			String from = getRequest().getParameter("from");
			String contractName=this.getRequest().getParameter("contractName");
			Long comId=UserRightInfoUtil.getComId(getRequest());
			SystemConfiguration systemConfiguration=BaseDataInfosUtil.convertSystemConfiguration(comId);
			this.getRequest().setAttribute("contractWorkflow", systemConfiguration.getContractWorkflow());
			this.getRequest().setAttribute("work_flow_type",
					WorkFlowStatus.CT_WorkFlow_Type);
			//触屏版使用
            if(StringUtil.isNotBlank(from)) initPage+="Mobile";
		    this.getRequest().setAttribute("contractName", contractName);
		} catch (Exception e) {
			log.error("查看合同信息信息列表错误！", e);
			throw new BaseException("查看合同信息信息列表错误！", e);
		}	
			
		return initPage ;
				
	}
	
	/**
	 * 查看合同信息信息列表
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String findContractInfo() throws BaseException {
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			SystemConfiguration systemConfiguration=BaseDataInfosUtil.convertSystemConfiguration(comId);
			String contractNameB=this.getRequest().getParameter("contractNameB");
			String contractCode=this.getRequest().getParameter("contractCode");
			String contractName=this.getRequest().getParameter("contractName");
			contractInfo=new ContractInfo();
			contractInfo.setContractNameB(contractNameB);
			contractInfo.setContractCode(contractCode);
			contractInfo.setContractName(contractName);
			String sqlStr="";
			if (!UserRightInfoUtil.ifSystemManagerRole(this.getRequest())) {
				sqlStr = UserRightInfoUtil.getUserDepartNameHql(getRequest(),
						"de");
			}
			List list=this.iContractInfoBiz.getContractInfoList(this.getRollPageDataTables(), contractInfo,sqlStr);
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					contractInfo = (ContractInfo) list.get(i);
					if(StringUtil.convertNullToBlank(systemConfiguration.getContractWorkflow()).equals("0")){
						  setProcessLisContract(contractInfo, WorkFlowStatus.Contract_Work_Item,comId);
						}else{
							contractInfo.setOrderState(contractInfo.getRunStatus());
						}
				}
			}
			this.getPagejsonDataTables(list);
		} catch (Exception e) {
			log.error("查看合同信息信息列表错误！", e);
			throw new BaseException("查看合同信息信息列表错误！", e);
		}		
		return null ;		
	}
	 /**
	 * 设置计划流程相关列表
	 */
	private void setProcessLisContract(ContractInfo contract, String processName,Long comId){
		//step1：首先获取流程定义实体
		org.snaker.engine.entity.Process process = facets.getEngine().process().getProcessByName(processName,comId);
		//step2：1、判断流程定义是否存在，2、遍历集合添加流程实例
		if(process != null){
				String newOrderNo=WorkFlowStatus.CT_WorkFlow_Type+contract.getCiId().toString();
				//step3:判断流程实例是否运行
				QueryFilter filter = new QueryFilter();
               filter.setOrderNo(newOrderNo);
				filter.setProcessId(process.getId());
				List<HistoryOrder> holist = facets.getEngine().query().getHistoryOrders(filter);
				if(holist.size() > 0){
					//step5:获取正在运行的流程实例
					filter.setOrderNo(newOrderNo);
					filter.setProcessId(process.getId());
					List<Order> orderlist = facets.getEngine().query().getActiveOrders(filter);
					if(orderlist.size() > 0){
						Order order = orderlist.get((orderlist.size()-1));
						if(order != null){
							List<Task> tasklist = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(order.getId()));
							if(tasklist.size() > 0){
								//设置当前流程名称
								contract.setProcessName(tasklist.get(0).getDisplayName());
							}
							contract.setOrderId(order.getId());//设置实例标示
						}
					}
					HistoryOrder ho = holist.get(0);
					contract.setOrderState(ho.getOrderState().toString());
					contract.setOrderStateName(WorkFlowStatusMap.getWorkflowOrderStatus(ho.getOrderState().toString()));
				}else{
					contract.setOrderStateName(WorkFlowStatus.WORK_FLOW_ORDER_STATUS_01_TEXT);
				}
				contract.setProcessId(process.getId());//设置流程标示
				contract.setInstanceUrl(process.getInstanceUrl());//设置流程实例URL
			
		}
	}
	/**
	 * 保存合同信息信息初始化
	 * @return
	 * @throws BaseException 
	 */
	public String saveContractInfoInit() throws BaseException {
		try{
			Long comId=UserRightInfoUtil.getComId(this.getRequest());
			//合同类型
			contractClass=new ContractClass();
			contractClass.setCategory(ContractStatus.COMMON_CONTRACT_TYPE);
			contractClass.setComId(comId);
		    List list=this.iContractClassBiz.getContractClassList(contractClass);
		    this.getRequest().setAttribute("contractTypeList", list);
            //项目类型
			contractClass.setCategory(ContractStatus.COMMON_PROJECT_TYPE);
		    list=this.iContractClassBiz.getContractClassList(contractClass);
		    this.getRequest().setAttribute("projectTypeList", list);
		    //货币类型
			contractClass.setCategory(ContractStatus.COMMON_MONEY_TYPE);
		    list=this.iContractClassBiz.getContractClassList(contractClass);
		    this.getRequest().setAttribute("moneyTypeList", list);
		    
		    //合同模板
		    contractTemplate=new ContractTemplate();
		    contractTemplate.setComId(comId);
            List<ContractTemplate> contractTemplates=this.iContractTemplateBiz.getContractTemplateList(contractTemplate);
            this.getRequest().setAttribute("contractTemplates", contractTemplates);
            
            List<Dictionary> dictionaryList=BaseDataInfosUtil.getDictInfoToList(DictStatus.COMMON_DICT_TYPE_1711);
			this.getRequest().setAttribute("dictionaryList", dictionaryList);
            
            sysCompany=this.iSysCompanyBiz.getSysCompany(comId);
            this.getRequest().setAttribute("sysCompany", sysCompany);
            this.getRequest().setAttribute("comId", comId);
            
            Users users=UserRightInfoUtil.getUsers(this.getRequest());
            String userChineseName=users.getUserChinesename();
            this.getRequest().setAttribute("userChineseName", userChineseName);
            
            Long deptId=users.getDepId();
            this.getRequest().setAttribute("deptId", deptId);
            
            String contractMobileA=users.getPhoneNum();
            this.getRequest().setAttribute("contractMobileA", contractMobileA);
            
		    String rcId=this.getRequest().getParameter("rcId");
		    if(StringUtil.isNotBlank(rcId)){
		    	Long baId=Long.parseLong(this.getRequest().getParameter("baId"));
		    	
		    	requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(Long.parseLong(rcId));
                this.getRequest().setAttribute("requiredCollect", requiredCollect);
			    
		    	bidAward=this.iBidAwardBiz.getBidAward(baId);
                this.getRequest().setAttribute("bidAward", bidAward);
		    	
		    	List<BidAwardDetail> badList=new ArrayList<BidAwardDetail>();
		    	BidAwardDetail bidAwardDetail=new BidAwardDetail();
				bidAwardDetail.setBaId(bidAward.getBaId());
				List<Object[]> objectList=this.iBidAwardDetailBiz.getBidAwardDetailListRequiredCollectDetail(bidAwardDetail);
				for(Object[] object:objectList){
					bidAwardDetail=(BidAwardDetail)object[0];
					requiredCollectDetail=(RequiredCollectDetail)object[1];
					bidAwardDetail.setRequiredCollectDetail(requiredCollectDetail);
					badList.add(bidAwardDetail);
				}
                this.getRequest().setAttribute("badList", badList);
				
				supplierInfo=this.iSupplierInfoBiz.getSupplierInfo(bidAward.getSupplierId());
                this.getRequest().setAttribute("supplierInfo", supplierInfo);
				
                
		    }
		    
		} catch (Exception e) {
			log("保存合同信息信息初始化错误！", e);
			throw new BaseException("保存合同信息信息初始化错误！", e);
		}
		return ADD_INIT;
		
	}
	
	/**
	 * 保存合同信息信息
	 * @return
	 * @throws BaseException 
	 */
	public String saveContractInfo() throws BaseException {
		
		try{

            Long comId=UserRightInfoUtil.getComId(getRequest());
			SystemConfiguration systemConfiguration=BaseDataInfosUtil.convertSystemConfiguration(comId);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String rmCodePrefix = systemConfiguration.getContractPrefix()+"-"+sdf.format(new Date());
			int floatCode = this.iContractInfoBiz
					.getMaxFloatCodeByContractCodePrefix(rmCodePrefix,comId);
			contractInfo.setContractCode(systemConfiguration.getContractPrefix()+"-"+sdf.format(new Date())
					+"-"+ (new DecimalFormat("0000").format(floatCode + 1)));
			contractInfo.setFloatCode((long) floatCode + 1);
			
            String writer=UserRightInfoUtil.getUserName(this.getRequest());
            //编制人
            contractInfo.setWriter(writer);
	 	   
	 	    //编制日期 
            contractInfo.setWriteDate(DateUtil.getCurrentDateTime());
			 
	 	    //合同运行状态
            contractInfo.setRunStatus(ContractStatus.CONTRACT_RUN_STATUS_01);
	 	    
	 	    //合同运行状态中文
            contractInfo.setStatusCn(ContractStatus.CONTRACT_RUN_STATUS_01_Text);
            
            contractInfo.setIsOrder(1);

            if(StringUtil.isNotBlank(contractInfo.getUuIdData())) contractInfo.setContractAppFile("yes");

			this.iContractInfoBiz.saveContractInfo(contractInfo);				

			//保存附件			
			iAttachmentBiz.saveAttachmentAndUpload( this.setUploadFile( contractInfo, contractInfo.getCiId(), AttachmentStatus.ATTACHMENT_CODE_1002, UserRightInfoUtil.getUserName(this.getRequest()) ) ) ;
			
			Double contractAmount=0.00;
			// 保存合同物资明细数据
			if (cmList != null) {
				for (int i = 0; i < cmList.size(); i++) {
					contractMaterial = cmList.get(i);
					if (contractMaterial != null
							&& StringUtil.isNotBlank(contractMaterial.getMaterialCode().trim())) {
						contractMaterial.setCiId(contractInfo.getCiId());
						contractMaterial.setWaitInputAmount(contractMaterial.getAmount());
						contractMaterial.setRealInputAmount(0.00);
						contractMaterial.setWaitSendAmount(contractMaterial.getAmount());
						contractMaterial.setRealSendAmount(0.00);
						contractMaterial.setIsOrder(1);
						iContractMaterialBiz.saveContractMaterial(contractMaterial);
						contractAmount+=contractMaterial.getAmount();
					}
				}
			}
			contractInfo.setContractAmount(contractAmount);
			contractInfo.setRealInputAmount(0.00);
			contractInfo.setRealSendAmount(0.00);
			this.iContractInfoBiz.updateContractInfo(contractInfo);
			
			//如果是项目中生成的合同，需要更新授标表的是否生成合同
			if(contractInfo.getBaId()!=null){
				bidAward=this.iBidAwardBiz.getBidAward(contractInfo.getBaId());
				bidAward.setIsContract(0);
				this.iBidAwardBiz.updateBidAward(bidAward);
			}
			this.getRequest().setAttribute("message", "添加成功");
			this.getRequest().setAttribute("operModule", "新增合同信息");
		} catch (Exception e) {
			log("保存合同信息信息错误！", e);
			throw new BaseException("保存合同信息信息错误！", e);
		}
		
		return "contractSuccess";
		
	}
	
	/**
	 * 修改合同信息信息初始化
	 * @return
	 * @throws BaseException 
	 */
	public String updateContractInfoInit() throws BaseException {
		
		try{
			Long comId=UserRightInfoUtil.getComId(this.getRequest());
			//合同类型
			contractClass=new ContractClass();
			contractClass.setCategory(ContractStatus.COMMON_CONTRACT_TYPE);
			contractClass.setComId(comId);
		    List list=this.iContractClassBiz.getContractClassList(contractClass);
		    this.getRequest().setAttribute("contractTypeList", list);
            //项目类型
			contractClass.setCategory(ContractStatus.COMMON_PROJECT_TYPE);
		    list=this.iContractClassBiz.getContractClassList(contractClass);
		    this.getRequest().setAttribute("projectTypeList", list);
		    //货币类型
			contractClass.setCategory(ContractStatus.COMMON_MONEY_TYPE);
		    list=this.iContractClassBiz.getContractClassList(contractClass);
		    this.getRequest().setAttribute("moneyTypeList", list);
		    
		    //合同模板
		    contractTemplate=new ContractTemplate();
		    contractTemplate.setComId(comId);
            List<ContractTemplate> contractTemplates=this.iContractTemplateBiz.getContractTemplateList(contractTemplate);
            this.getRequest().setAttribute("contractTemplates", contractTemplates);
           
            List<Dictionary> dictionaryList=BaseDataInfosUtil.getDictInfoToList(DictStatus.COMMON_DICT_TYPE_1711);
			this.getRequest().setAttribute("dictionaryList", dictionaryList);
            
			contractInfo=this.iContractInfoBiz.getContractInfo(contractInfo.getCiId() );
			
			contractMaterial=new ContractMaterial();
			contractMaterial.setCiId(contractInfo.getCiId());
			cmList=this.iContractMaterialBiz.getContractMaterialList(contractMaterial);
			
			//获取附件
			Map<String,Object> map=iAttachmentBiz.getAttachmentMap( new Attachment( contractInfo.getCiId(), AttachmentStatus.ATTACHMENT_CODE_1002 ) );
			contractInfo.setUuIdData((String)map.get("uuIdData"));
			contractInfo.setFileNameData((String)map.get("fileNameData"));
			contractInfo.setFileTypeData((String)map.get("fileTypeData"));
			contractInfo.setAttIdData((String)map.get("attIdData"));
			contractInfo.setAttIds((String)map.get("attIds"));
			
		} catch (Exception e) {
			log("修改合同信息信息初始化错误！", e);
			throw new BaseException("修改合同信息信息初始化错误！", e);
		}
		return MODIFY_INIT;
		
	}
	
	/**
	 * 修改合同信息信息
	 * @return
	 * @throws BaseException 
	 */
	public String updateContractInfo() throws BaseException {
		
		try{

			
            String writer=UserRightInfoUtil.getUserName(this.getRequest());
            contractInfo.setLastModifyPerson(writer);
            contractInfo.setLastModifyDate(DateUtil.getCurrentDateTime());
            contractInfo.setIsOrder(1);
            
            if(StringUtil.isNotBlank(contractInfo.getUuIdData())) contractInfo.setContractAppFile("yes");
           this.iContractInfoBiz.updateContractInfo(contractInfo);	
			
			// 删除附件
			iAttachmentBiz.deleteAttachments( parseAttachIds( contractInfo.getAttIds() ) ) ;
			//保存附件			
			iAttachmentBiz.saveAttachmentAndUpload( this.setUploadFile( contractInfo, contractInfo.getCiId(), AttachmentStatus.ATTACHMENT_CODE_1002, UserRightInfoUtil.getUserName(this.getRequest()) ) ) ;
			
			Double contractAmount=0.00;
			if(contractInfo.getRcId()!=null){
				// 保存合同物资明细数据
				if (cmList != null) {
					for (int i = 0; i < cmList.size(); i++) {
						contractMaterial = cmList.get(i);
						if (contractMaterial != null
								&& StringUtil.isNotBlank(contractMaterial.getCmId())) {
							contractMaterial.setIsOrder(1);
							contractMaterial.setWaitInputAmount(contractMaterial.getAmount());
							contractMaterial.setRealInputAmount(0.00);
							contractMaterial.setWaitSendAmount(contractMaterial.getAmount());
							contractMaterial.setRealSendAmount(0.00);
							iContractMaterialBiz.updateContractMaterial(contractMaterial);
						}
					}
				}
			}else{
				iContractMaterialBiz.deleteContractMaterialByCiId(contractInfo.getCiId());
				// 保存合同物资明细数据
				if (cmList != null) {
					for (int i = 0; i < cmList.size(); i++) {
						contractMaterial = cmList.get(i);
						if (contractMaterial != null
								&& StringUtil.isNotBlank(contractMaterial.getMaterialCode().trim())) {
							contractMaterial.setCiId(contractInfo.getCiId());
							contractMaterial.setWaitInputAmount(contractMaterial.getAmount());
							contractMaterial.setRealInputAmount(0.00);
							contractMaterial.setWaitSendAmount(contractMaterial.getAmount());
							contractMaterial.setRealSendAmount(0.00);
							contractMaterial.setIsOrder(1);
							iContractMaterialBiz.saveContractMaterial(contractMaterial);
							contractAmount+=contractMaterial.getAmount();
						}
					}
				}
				contractInfo.setContractAmount(contractAmount);
				contractInfo.setRealInputAmount(0.00);
				contractInfo.setRealSendAmount(0.00);
				this.iContractInfoBiz.updateContractInfo(contractInfo);
			}
			
			this.getRequest().setAttribute("message", "修改成功");
			this.getRequest().setAttribute("operModule", "修改合同信息");
		} catch (Exception e) {
			log("修改合同信息信息错误！", e);
			throw new BaseException("修改合同信息信息错误！", e);
		}
		return "contractSuccess";
		
	}
	
	/**
	 * 删除合同信息信息
	 * @return
	 * @throws BaseException 
	 */
	public String deleteContractInfo() throws BaseException {
		try{
		    ContractInfo contractInfo=new ContractInfo();
			String ids=this.getRequest().getParameter("ids");
 			String[] str=ids.split(",");
 			for(int i=0;i<str.length;i++){
 				if(StringUtil.isNotBlank(str[i]))
 				{
	 				contractInfo=this.iContractInfoBiz.getContractInfo(new Long(str[i]));
	 				this.iContractInfoBiz.deleteContractInfo(contractInfo);
	 				
	 				//如果是项目中生成的合同，需要更新授标表的是否生成合同
	 				if(contractInfo.getBaId()!=null){
	 					bidAward=this.iBidAwardBiz.getBidAward(contractInfo.getBaId());
	 					bidAward.setIsContract(1);
	 					this.iBidAwardBiz.updateBidAward(bidAward);
	 				}
 				}
 			}
 			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 viewContractInfoDetail() throws BaseException {
		String initPage="detail";
		try{
			String from = getRequest().getParameter("from");
			contractInfo=this.iContractInfoBiz.getContractInfo(contractInfo.getCiId() );
			// 获取合同审批原件
			String appFile=iAttachmentBiz
					.getAttachmentPageUrl(
							iAttachmentBiz.getAttachmentList(new Attachment(
									contractInfo.getCiId(),
									AttachmentStatus.ATTACHMENT_CODE_1002)), "0",
							this.getRequest());
			this.getRequest().setAttribute("appFile", appFile);
			
			//获取合同审批扫描件
			String scanFile=iAttachmentBiz
			.getAttachmentPageUrl(
					iAttachmentBiz.getAttachmentList(new Attachment(
							contractInfo.getCiId(),
							AttachmentStatus.ATTACHMENT_CODE_1003)), "0",
					this.getRequest());
			this.getRequest().setAttribute("scanFile", scanFile);
			
			contractMaterial=new ContractMaterial();
			contractMaterial.setCiId(contractInfo.getCiId());
			cmList=this.iContractMaterialBiz.getContractMaterialList(contractMaterial);
			
			contractConfirm=new ContractConfirm();
			contractConfirm.setCiId(contractInfo.getCiId());
			List confirmList=this.iContractConfirmBiz.getContractConfirmList(contractConfirm);
			this.getRequest().setAttribute("confirmList", confirmList);
			//触屏版使用
            if(StringUtil.isNotBlank(from)) initPage+="Mobile";
            
		} catch (Exception e) {
			log("查看合同信息明细信息错误！", e);
			throw new BaseException("查看合同信息明细信息错误！", e);
		}
		return initPage;
		
	}
	/**
	 * 合同签订信息信息初始化
	 * @return
	 * @throws BaseException 
	 */
	public String updateSignContractInfoInit() throws BaseException {
		
		try{            
			contractInfo=this.iContractInfoBiz.getContractInfo(contractInfo.getCiId() );
		} catch (Exception e) {
			log("合同签订信息初始化错误！", e);
			throw new BaseException("合同签订信息初始化错误！", e);
		}
		return "signInit";
		
	}
	/**
	 * 签订合同信息保存
	 * @return
	 * @throws BaseException
	 */
	public String updateSignContractInfo() throws BaseException{
		try{
			ContractInfo contractInfoTmp=this.iContractInfoBiz.getContractInfo(contractInfo.getCiId() );
			
			contractInfoTmp.setRunStatus(ContractStatus.CONTRACT_RUN_STATUS_07);
			contractInfoTmp.setStatusCn(ContractStatus.CONTRACT_RUN_STATUS_07_Text);
			contractInfoTmp.setSignDate(contractInfo.getSignDate());
			contractInfoTmp.setContractSignAddress(contractInfo.getContractSignAddress());
			contractInfoTmp.setConValidDate(contractInfo.getConValidDate());
			contractInfoTmp.setConFinishDate(contractInfo.getConFinishDate());
			contractInfoTmp.setWarrantyPeriodStartDate(contractInfo.getWarrantyPeriodStartDate());
			contractInfoTmp.setWarrantyPeriodStopDate(contractInfo.getWarrantyPeriodStopDate());
			contractInfoTmp.setRequirementArrivalDate(contractInfo.getRequirementArrivalDate());
			contractInfoTmp.setPaymentType(contractInfo.getPaymentType());
			String writer=UserRightInfoUtil.getUserName(this.getRequest());
			contractInfoTmp.setLastModifyPerson(writer);
			contractInfoTmp.setLastModifyDate(DateUtil.getCurrentDateTime());
			
			this.iContractInfoBiz.updateContractInfo(contractInfoTmp);
			
			//保存附件			
			iAttachmentBiz.saveAttachmentAndUpload( this.setUploadFile( contractInfo, contractInfo.getCiId(), AttachmentStatus.ATTACHMENT_CODE_1003, UserRightInfoUtil.getUserName(this.getRequest()) ) ) ;
			
			
		} catch (Exception e) {
			log("合同签订信息初始化错误！", e);
			throw new BaseException("合同签订信息初始化错误！", e);
		}
		return "success";
	}
	/**
	 * 合同不需要审批的时候提交合同信息
	 * @return
	 * @throws BaseException
	 */
    public String updateProcessContractInfo() throws BaseException{
    	
    	try {
			String ids = this.getRequest().getParameter("ids");
			// 页面所选汇总明细信息
			String[] idss = ids.split(",");
			for (int i = 0; i < idss.length; i++) {
				if (idss[i] != null) {
					contractInfo= this.iContractInfoBiz
							.getContractInfo(new Long(idss[i]));
					contractInfo.setRunStatus(ContractStatus.CONTRACT_RUN_STATUS_00);
					contractInfo.setStatusCn(ContractStatus.CONTRACT_RUN_STATUS_00_Text);
					contractInfo.setAuditDate(DateUtil.getCurrentDateTime());
   					this.iContractInfoBiz.updateContractInfo(contractInfo);
				}
			}
			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 null;
    }
	/**
	 * 发送合同至供应商确认
	 * @return
	 * @throws BaseException 
	 */
	public String saveSendContractInfo() throws BaseException {
		
		try{
		    ContractInfo contractInfo=new ContractInfo();
			String ids=this.getRequest().getParameter("ids");
 			String[] str=ids.split(",");
 			for(int i=0;i<str.length;i++){
 				if(StringUtil.isNotBlank(str[i]))
 				{
	 				contractInfo=this.iContractInfoBiz.getContractInfo(new Long(str[i]));
	 				contractInfo.setRunStatus(ContractStatus.CONTRACT_RUN_STATUS_04);
	 				contractInfo.setStatusCn(ContractStatus.CONTRACT_RUN_STATUS_04_Text);
	 				this.iContractInfoBiz.updateContractInfo(contractInfo);
	 				
	 				String content="待办提示：您有一个合同需要确认，合同名称为"+contractInfo.getContractName()+"，合同金额为"+contractInfo.getContractMoney();
	 				this.saveSmsMessageToUsers(contractInfo.getContractMobileB(), content, contractInfo.getContractUndertaker());
 				}
 			}
 			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 fileAlertContract() throws BaseException{
		try {
			Long tempId=Long.parseLong(this.getRequest().getParameter("tempId"));
			contractInfo=this.iContractInfoBiz.getContractInfo(contractInfo.getCiId());
			contractTemplate=this.iContractTemplateBiz.getContractTemplate(tempId);
			
			contractMaterial=new ContractMaterial();
			contractMaterial.setCiId(contractInfo.getCiId());
			cmList=this.iContractMaterialBiz.getContractMaterialList(contractMaterial);
			
			Map<String, Object> resultsLabel = new HashMap<String, Object>();
			
			/**
			 * 合同基本信息
			 */
			Map<String, String> resultsString = new HashMap<String, String>();
			resultsString.put("合同编号", contractInfo.getContractCode());
			resultsString.put("合同名称", contractInfo.getContractName());
			resultsString.put("合同分类", contractInfo.getContractType());
			resultsString.put("项目名称", contractInfo.getProjectName());
			resultsString.put("项目编号", contractInfo.getBidCode());
			resultsString.put("项目分类", contractInfo.getProjectType());
			resultsString.put("甲方名称", contractInfo.getContractPersonNameA());
			resultsString.put("乙方名称", contractInfo.getContractNameB());
			resultsString.put("甲方地址", contractInfo.getContractAddressA());
			resultsString.put("乙方地址", contractInfo.getContractAddressB());
			resultsString.put("甲方联系人", contractInfo.getContractUndertaker());
			resultsString.put("乙方联系人", contractInfo.getContractPersonB());
			resultsString.put("甲方联系人手机", contractInfo.getContractMobileA());
			resultsString.put("乙方联系人手机", contractInfo.getContractMobileB());
			resultsString.put("甲方电话", contractInfo.getContractTelA());
			resultsString.put("乙方电话", contractInfo.getContractTelB());
			resultsString.put("甲方传真", contractInfo.getContractFaxA());
			resultsString.put("乙方传真", contractInfo.getContractFaxB());
			resultsString.put("合同金额", contractInfo.getContractMoney()+"");
			resultsString.put("货币类型", contractInfo.getConMoneyType());
			resultsString.put("银行账号", contractInfo.getBankAccount());
			resultsString.put("银行户名", contractInfo.getBankAccountName());
			resultsString.put("开户银行", contractInfo.getBank());
			resultsString.put("税号", contractInfo.getDutyParagraph());
			resultsLabel.put("String", resultsString);
			
			/**
			 * 替换表格  合同物资信息
			 *value= List<Map<String,Object>> 是数据中获取出来的
			 */
			List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
			Map<String,Object> maptable=new LinkedHashMap<String, Object>();
			maptable.put("序号", "序号");
			maptable.put("编码", "编码");
			maptable.put("名称", "名称");
			maptable.put("规格型号", "规格型号");
			maptable.put("计量单位", "计量单位");
			maptable.put("数量", "数量");
			maptable.put("单价", "单价");
			maptable.put("小计", "小计");
			maptable.put("备注", "备注");
			list.add(maptable);
			int i=0;
			for(ContractMaterial contractMaterial:cmList){
				i++;
				maptable=new LinkedHashMap<String, Object>();
				maptable.put("序号", i+"");
				maptable.put("编码", contractMaterial.getMaterialCode());
				maptable.put("名称", StringUtil.convertNullToBlank(contractMaterial.getMaterialName()));
				maptable.put("规格型号",StringUtil.convertNullToBlank(contractMaterial.getMaterialType()));
				maptable.put("计量单位", StringUtil.convertNullToBlank(contractMaterial.getUnit()));
				maptable.put("数量", contractMaterial.getAmount()+"");
				maptable.put("单价", contractMaterial.getPrice()+"");
				maptable.put("小计", contractMaterial.getAmount()*contractMaterial.getPrice()+"");
				maptable.put("备注", StringUtil.convertNullToBlank(contractMaterial.getRemark()));
				list.add(maptable);
			}
			maptable=new LinkedHashMap<String, Object>();
			maptable.put("序号", "总计人民币（大写）");
			maptable.put("编码", "");
			maptable.put("名称", "");
			maptable.put("规格型号","");
			maptable.put("计量单位", "");
			maptable.put("数量", "");
			maptable.put("单价","");
			maptable.put("小计",MoneyUtil.NumToRMBStr(contractInfo.getContractMoney()));
			maptable.put("备注","");
			list.add(maptable);
			
			Map<String, Object> resultsTable = new HashMap<String, Object>();
			resultsTable.put("合同物资明细", list);
			resultsLabel.put("Table", resultsTable);
			String infilePath=contractTemplate.getTemplateUrl();
			String fileType="";
			int index = infilePath.lastIndexOf(".");
			if (index > -1) {
				fileType =infilePath.substring(index);
			} 
			String cjrq = new SimpleDateFormat("HHmmss")
					.format(new Date());
			String outfilePath=contractInfo.getContractName()+"_"+cjrq+"."+fileType;
			
			WordTemplateUtilities.GetInstance().toWord(GlobalSettingBase.getFilePath()+infilePath, GlobalSettingBase.getFilePath()+UPLOADDIR+"alertFile/"+outfilePath, resultsLabel);
			this.getResponse().setContentType("application/octet-stream; charset=utf-8");
			this.getResponse().setHeader(
					"Content-Disposition",
					"attachment; filename="
							+ new String(outfilePath.getBytes("gbk"), "iso-8859-1"));
			// this.getResponse().setHeader( "Set-Cookie",
			// "name=value; HttpOnly");
			File files = new File(GlobalSettingBase.getFilePath()+UPLOADDIR+"alertFile/"+outfilePath);
			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("生成合同文本信息错误！", e);
			throw new BaseException("生成合同文本信息错误！", e);
		}
		return null;
	}
	/**
	 * 选择合同信息为订单所用
	 * @return
	 * @throws BaseException
	 */
	public String viewContractForOrder() throws BaseException{		
		try{
			int sign=Integer.parseInt(this.getRequest().getParameter("sign"));
			this.getRequest().setAttribute("sign", sign);
			this.getRequest().setAttribute("type", 2);
		} catch (Exception e) {
			log("选择合同信息为订单所用错误！", e);
			throw new BaseException("选择合同信息为订单所用错误！", e);
		}		
		return "selectContract";
	}
	/**
	 * 查询合同信息为订单所用列表查询
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String findContractInfoForOrder() throws BaseException {
		
		try{
			int sign=Integer.parseInt(this.getRequest().getParameter("sign"));
			String contractNameB=this.getRequest().getParameter("contractNameB");
			String contractCode=this.getRequest().getParameter("contractCode");
			String contractName=this.getRequest().getParameter("contractName");
			contractInfo=new ContractInfo();
			contractInfo.setContractNameB(contractNameB);
			contractInfo.setContractCode(contractCode);
			contractInfo.setContractName(contractName);
			String sqlStr="";
			if (!UserRightInfoUtil.ifSystemManagerRole(this.getRequest())) {
				sqlStr = UserRightInfoUtil.getUserDepartNameHql(getRequest(),
						"de");
			}
			List list=this.iContractInfoBiz.getContractInfoListForOrder(this.getRollPageDataTables(), contractInfo,sign,sqlStr);
			this.getPagejsonDataTables(list);
		} catch (Exception e) {
			log.error("查询合同信息为订单所用列表查询错误！", e);
			throw new BaseException("查询合同信息为订单所用列表查询错误！", e);
		}		
		return null ;		
	}
	/**货单签收管理
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String viewInputContractInfo() throws BaseException {
		
		try{
			
		} catch (Exception e) {
			log.error("货单签收管理列表错误！", e);
			throw new BaseException("货单签收管理列表错误！", e);
		}	
			
		return "contract_input" ;
				
	}
	/**
	 * 货单签收管理列表
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String findInputBillContractInfo() throws BaseException {
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			String orderNameB=this.getRequest().getParameter("orderNameB");
			String orderCode=this.getRequest().getParameter("orderCode");
			String orderName=this.getRequest().getParameter("orderName");
			contractInfo=new ContractInfo();
			contractInfo.setContractNameB(orderNameB);
			contractInfo.setContractCode(orderCode);
			contractInfo.setContractName(orderName);
			contractInfo.setComId(comId);
			String sqlStr = "";
			if (!UserRightInfoUtil.ifSystemManagerRole(this.getRequest())) {
				sqlStr = " and  de.billUndertakerId="+UserRightInfoUtil.getUserId(this.getRequest());
			}
			List list=this.iContractInfoBiz.getInputBillContractInfoList(this.getRollPageDataTables(), contractInfo,sqlStr);
			this.getPagejsonDataTables(list);
		} catch (Exception e) {
			log.error("查看货单签收信息列表错误！", e);
			throw new BaseException("查看货单签收信息列表错误！", e);
		}
		
		return null ;
		
	}
	/**
	 * 合同监督
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String viewContractInfoSupervise() throws BaseException {
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			SystemConfiguration systemConfiguration=BaseDataInfosUtil.convertSystemConfiguration(comId);
			this.getRequest().setAttribute("contractWorkflow", systemConfiguration.getContractWorkflow());
			this.getRequest().setAttribute("work_flow_type",
					WorkFlowStatus.CT_WorkFlow_Type);
		} catch (Exception e) {
			log.error("查看合同信息信息列表错误！", e);
			throw new BaseException("查看合同信息信息列表错误！", e);
		}	
			
		return "contractInfoSupervise" ;
				
	}
	
	/**
	 * 查看合同监督列表
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String findContractInfoSupervise() throws BaseException {
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			SystemConfiguration systemConfiguration=BaseDataInfosUtil.convertSystemConfiguration(comId);
			String contractNameB=this.getRequest().getParameter("contractNameB");
			String contractCode=this.getRequest().getParameter("contractCode");
			String contractName=this.getRequest().getParameter("contractName");
			contractInfo=new ContractInfo();
			contractInfo.setContractNameB(contractNameB);
			contractInfo.setContractCode(contractCode);
			contractInfo.setContractName(contractName);
			String sqlStr="";
			if (!UserRightInfoUtil.ifSystemManagerRole(this.getRequest())) {
				sqlStr = UserRightInfoUtil.getUserDepartNameHql(getRequest(),
						"de");
			}
			List list=this.iContractInfoBiz.getContractInfoSuperviseList(this.getRollPageDataTables(), contractInfo,sqlStr);
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					contractInfo = (ContractInfo) list.get(i);
					if(StringUtil.convertNullToBlank(systemConfiguration.getContractWorkflow()).equals("0")){
						  setProcessLisContract(contractInfo, WorkFlowStatus.Contract_Work_Item,comId);
						}else{
							contractInfo.setOrderState(contractInfo.getRunStatus());
						}
				}
			}
			this.getPagejsonDataTables(list);
		} catch (Exception e) {
			log.error("查看合同监督列表错误！", e);
			throw new BaseException("查看合同监督列表错误！", e);
		}		
		return null ;		
	}
	public IContractInfoBiz getiContractInfoBiz() {
		return iContractInfoBiz;
	}

	public void setiContractInfoBiz(IContractInfoBiz iContractInfoBiz) {
		this.iContractInfoBiz = iContractInfoBiz;
	}

	public ContractInfo getContractInfo() {
		return contractInfo;
	}

	public void setContractInfo(ContractInfo contractInfo) {
		this.contractInfo = contractInfo;
	}

	public IContractMaterialBiz getiContractMaterialBiz() {
		return iContractMaterialBiz;
	}

	public void setiContractMaterialBiz(IContractMaterialBiz iContractMaterialBiz) {
		this.iContractMaterialBiz = iContractMaterialBiz;
	}

	public IContractClassBiz getiContractClassBiz() {
		return iContractClassBiz;
	}

	public void setiContractClassBiz(IContractClassBiz iContractClassBiz) {
		this.iContractClassBiz = iContractClassBiz;
	}

	public IRequiredCollectBiz getiRequiredCollectBiz() {
		return iRequiredCollectBiz;
	}

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

	public IBidAwardBiz getiBidAwardBiz() {
		return iBidAwardBiz;
	}

	public void setiBidAwardBiz(IBidAwardBiz iBidAwardBiz) {
		this.iBidAwardBiz = iBidAwardBiz;
	}

	public IBidAwardDetailBiz getiBidAwardDetailBiz() {
		return iBidAwardDetailBiz;
	}

	public void setiBidAwardDetailBiz(IBidAwardDetailBiz iBidAwardDetailBiz) {
		this.iBidAwardDetailBiz = iBidAwardDetailBiz;
	}

	public ISupplierInfoBiz getiSupplierInfoBiz() {
		return iSupplierInfoBiz;
	}

	public void setiSupplierInfoBiz(ISupplierInfoBiz iSupplierInfoBiz) {
		this.iSupplierInfoBiz = iSupplierInfoBiz;
	}

	public ISysCompanyBiz getiSysCompanyBiz() {
		return iSysCompanyBiz;
	}

	public void setiSysCompanyBiz(ISysCompanyBiz iSysCompanyBiz) {
		this.iSysCompanyBiz = iSysCompanyBiz;
	}

	public IContractTemplateBiz getiContractTemplateBiz() {
		return iContractTemplateBiz;
	}

	public void setiContractTemplateBiz(IContractTemplateBiz iContractTemplateBiz) {
		this.iContractTemplateBiz = iContractTemplateBiz;
	}

	public List<ContractMaterial> getCmList() {
		return cmList;
	}

	public void setCmList(List<ContractMaterial> cmList) {
		this.cmList = cmList;
	}

	public IContractConfirmBiz getiContractConfirmBiz() {
		return iContractConfirmBiz;
	}

	public void setiContractConfirmBiz(IContractConfirmBiz iContractConfirmBiz) {
		this.iContractConfirmBiz = iContractConfirmBiz;
	}

	public IAttachmentBiz getiAttachmentBiz() {
		return iAttachmentBiz;
	}

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