package com.ced.sip.common.action.supplier;

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

import net.sf.json.JSONObject;



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.biz.ICompanySupplierViewBiz;
import com.ced.sip.common.entity.SessionInfo;
import com.ced.sip.common.entity.SessionUser;
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.purchase.base.biz.IBidBulletinBiz;
import com.ced.sip.purchase.base.biz.IInviteSupplierBiz;
import com.ced.sip.purchase.base.biz.IRequiredCollectBiz;
import com.ced.sip.purchase.base.entity.BidBulletin;
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.biz.ISupplierProductInfoBiz;
import com.ced.sip.supplier.entity.SupplierInfo;
import com.ced.sip.system.biz.IDepartmentsBiz;
import com.ced.sip.system.biz.ISysCompanyBiz;
import com.ced.sip.system.biz.ISysUserInoutLogBiz;
import com.ced.sip.system.biz.IUsersBiz;
import com.ced.sip.system.entity.Departments;
import com.ced.sip.system.entity.OrgUser;
import com.ced.sip.system.entity.SysCompany;
import com.ced.sip.system.entity.SysUserInoutLog;
import com.ced.sip.system.entity.Users;

public class WebMobileIndexAction extends BaseAction{ 	
	
	private IBidBulletinBiz iBidBulletinBiz; 		
	private ISupplierProductInfoBiz iSupplierProductInfoBiz;	
	private ICompanySupplierViewBiz iCompanySupplierViewBiz;
	
	private IUsersBiz iUsersBiz;
	private IDepartmentsBiz iDepartmentsBiz;
	private ISupplierInfoBiz iSupplierInfoBiz;
	private ISysUserInoutLogBiz iSysUserInoutLogBiz ;
	private IInviteSupplierBiz iInviteSupplierBiz;
	private ISysCompanyBiz iSysCompanyBiz;
	private IRequiredCollectBiz iRequiredCollectBiz;
	
	private Users users;	
	private SupplierInfo supplierInfo;
	private SessionUser sessionUser;	
	private SysCompany sysCompany;
	private Long id;
	private RequiredCollect requiredCollect;
	
	
	/**
	 * 触屏版主页
	 * @return
	 * @throws BaseException
	 */
	public String index() throws BaseException{
		//查询采购公告信息
		BidBulletin bidBulletin=new BidBulletin();
		List<BidBulletin> bbList=this.iBidBulletinBiz.getBidBulletinList(this.getRollPageDataTables(),bidBulletin,3);
		
		
		this.getRequest().setAttribute("bbList", bbList);
		
		
		return "index";
	}
	/**
	 * 触屏版项目搜索
	 * @return
	 * @throws BaseException
	 */
	public String xmSearch() throws BaseException{
		
		String bidInfo=this.getRequest().getParameter("bidInfo");
		this.getRequest().setAttribute("bidInfo", bidInfo);
		
		
		//招标类型  公告类型 发布时间类型
		String bidderType=this.getRequest().getParameter("bidderType");
		if(StringUtil.isBlank(bidderType)) bidderType="0";
		this.getRequest().setAttribute("bidderType", Integer.parseInt(bidderType));
		
		String publishType=this.getRequest().getParameter("publishType");
		if(StringUtil.isBlank(publishType)) publishType="0";
		this.getRequest().setAttribute("publishType", publishType);
		
		return "xmSearch";
	}
	/**
	 * 触屏版项目搜索
	 * @return
	 * @throws BaseException
	 */
	public String purchaseQuery() throws BaseException{
		try{
			BidBulletin bidBulletin=new BidBulletin();
			Map<String,Object> map=new HashMap<String, Object>();

			
			String bidInfo=this.getRequest().getParameter("bidInfo");
			bidBulletin.setBulletinTitle(bidInfo);
			
	
			String startDate=this.getRequest().getParameter("startDate");
			String endDate=this.getRequest().getParameter("endDate");
			
			//招标类型  公告类型 发布时间类型
			int bidderType=0,publishType=0;
			//定义时间
			String startDateTmp="",endDateTmp="";
			String bidderTypeTmp=this.getRequest().getParameter("bidderType");
			if(StringUtil.isNotBlank(bidderTypeTmp)) bidderType=Integer.parseInt(bidderTypeTmp);
			map.put("bidderType", bidderType);
			
			
			String publishTypeTmp=this.getRequest().getParameter("publishType");
			if(StringUtil.isNotBlank(publishTypeTmp)) publishType=Integer.parseInt(publishTypeTmp);
			
			if(publishType==1){
				startDateTmp=DateUtil.dayAgo(4);
				endDateTmp=DateUtil.getDefaultDateFormat(new Date());
			}else if(publishType==2){
				startDateTmp=DateUtil.dayAgo(8);
				endDateTmp=DateUtil.getDefaultDateFormat(new Date());
			}else if(publishType==3){
				startDateTmp=DateUtil.dayAgo(31);
				endDateTmp=DateUtil.getDefaultDateFormat(new Date());
			}else if(publishType==4){
				startDateTmp=startDate;
				endDateTmp= endDate;
			}
			map.put("startDate", startDateTmp);
			map.put("endDate", endDateTmp);
			
			//查询采购公告信息
			List<BidBulletin> bbList=this.iBidBulletinBiz.getBidBulletinListByWebApp(this.getRollPageDataTables(), bidBulletin, map);
			this.getPagejsonDataTables(bbList);
		} catch (Exception e) {
			log("触屏版查询项目信息错误！", e);
			throw new BaseException("触屏版查询项目信息错误！", e);
		}
		return null;
	}
	/**
	 * 触屏版 我的页面
	 * @return
	 * @throws BaseException
	 */
	public String about() throws BaseException{
		try{
			int usesType=UserRightInfoUtil.getSessionUserType(this.getRequest());
			String isRegister="";
			if(usesType==0){
				String userNameCn=UserRightInfoUtil.getChineseName(this.getRequest());
	            this.getRequest().setAttribute("userNameCn", userNameCn);
				String userDeptName=UserRightInfoUtil.getUserDeptName(this.getRequest());
	            this.getRequest().setAttribute("userDeptName", userDeptName);
			}else if(usesType==1){
				String supplierName=UserRightInfoUtil.getSupplierName(this.getRequest());
	            this.getRequest().setAttribute("supplierName", supplierName);
				isRegister=(String)this.getRequest().getAttribute("isRegister");
	            this.getRequest().setAttribute("isRegister", isRegister);
			}
            this.getRequest().setAttribute("usesType", usesType);
            int xmcount=this.iBidBulletinBiz.countBidBulletinList(null,3);
            this.getRequest().setAttribute("xmcount", xmcount);
		} catch (Exception e) {
			log("触屏版我的页面信息错误！", e);
			throw new BaseException("触屏版我的页面信息错误！", e);
		}
		return "about";
	}
	/**
	 * 触屏版  登录页面
	 * @return
	 * @throws BaseException
	 */
	public String userLogin() throws BaseException{
		return "userLogin";
	}
	/**
	 * 触屏版  登录校验
	 * @return
	 * @throws BaseException
	 */
	public String verifyLogin() throws BaseException{
		PrintWriter out = null;
		List list =null;	
		int errcode=0;
		try {   
			    String loginType =this.getRequest().getParameter("loginType");
				String username =this.getRequest().getParameter("username");
				String password =this.getRequest().getParameter("password");
				if(("1").equals(loginType)){
					users=new Users();
					users.setUserName(username);
					users.setUserPassword(PasswordUtil.encrypt( password.trim() ) ) ;
					list= iUsersBiz.getUsersList( users ) ;
		           if(list != null && list.size()>0 ) { // 通过用户校验, 保存用户信息到session并返回主页面
						Users user 			= (Users) list.get( 0 ) ;
						
						if( TableStatus.COMMON_STATUS_VALID.equals( user.getIsUsable() ) ){//判断用户是否有效	
							SessionInfo info = new SessionInfo() ;
							
							//判断此用户的类别，3普通用户，1部门经理  2高层领导  4分管领导 首先从缓存里面取,如果缓存里面没有值,则去查询
							int userType=BaseDataInfosUtil.convertLoginNameToUserType(user.getUserName());
							if(userType==0){
								
								userType=3;
								
								//部门经理判断
								List<Departments> list_dept = iDepartmentsBiz.getSignUsersList();
								for(Departments departments:list_dept){
									if(StringUtil.convertNullToBlank(departments.getDepLeaderId()).equals(user.getUserId())){
										userType=1;
										break;
									}
								}
								//分管领导判断
								List<Departments> list_com_dept = iDepartmentsBiz.getComSignUsersList();
								for(Departments departments:list_com_dept){
									if(StringUtil.convertNullToBlank(departments.getDepLeaderId()).equals(user.getUserId())){
										userType=4;
										break;
									}
								}
								//高层领导判断
							   OrgUser orgUser=new OrgUser();
					           orgUser.setOrgCode(TableStatus.Leader);
								List userList=iUsersBiz.getUsersListByOrgUser(orgUser);
								for(int i=0;i<userList.size();i++){
									Users ur = (Users) userList.get(i);
									if(StringUtil.convertNullToBlank(ur.getUserName()).equals(user.getUserName())){
										userType=2;
										break;
									}
								}
							}
                            user.setUserType(userType);		
							BaseDataInfosUtil.updateUserCache("update", user);
							
							info.setUsers( user );
							
							info.setDept( iDepartmentsBiz.getDepartments( user.getDepId() ) ) ;
							
							List<Departments> deptIdList=iDepartmentsBiz.getDepIdsByUserId(user.getUserName());  //该用户所有权限部门
							info.setDeptIdList(deptIdList);
							
							List<Departments> leaderList=iDepartmentsBiz.getDepartsToUserId(user.getUserId());  //该用户是部门领导或是分管领导
							info.setLeaderList(leaderList);
							
							//查询该用户所有的权限部门信息
							List<Departments> departList=new ArrayList<Departments>();
							Departments dept = null;
							dept = this.iDepartmentsBiz.getDepartments(user.getDepId());
							departList.add(dept);
							if(deptIdList!=null|| deptIdList.size()!=0){
								for(Departments de:deptIdList){
									if(StringUtil.isNotBlank(de.getDepId())){
										dept = this.iDepartmentsBiz.getDepartments(de.getDepId());
										departList.add(dept);
									}
								}
							}
							info.setDepartList(departList);
							
							sessionUser=new SessionUser();
							sessionUser.setType(TableStatus.COMMON_TYPE_0);
							sessionUser.setLoginName(user.getUserName());
							sessionUser.setId(user.getUserId());
							sessionUser.setName(user.getUserChinesename());
							sessionUser.setComId(user.getComId());
							info.setSessionUser(sessionUser);
							
							UserRightInfoUtil.setSessionInfo(info, this.getRequest() ) ;
							users.setUserChinesename(user.getUserChinesename());
							
							
							String ip = this.getRequest().getHeader("X-Real-IP");  
							SysUserInoutLog tSysUserInoutLog=new SysUserInoutLog( info.getUsers().getUserName(), info.getUsers().getUserChinesename(),
									ip, new Date(), this.getSession().getId().toString(), TableStatus.COMMON_STATUS_VALID,TableStatus.COMMON_TYPE_0 );
							// 保存登录日志信息
							iSysUserInoutLogBiz.saveSysUserInoutLog(tSysUserInoutLog);
							this.getRequest().getSession().setAttribute("uiId", tSysUserInoutLog.getUilId());
							
						}else {
							errcode=1;
						}	
					}else{ // 校验失败, 返回登陆页面, 提示错误信息
						errcode=2;
					}
				}else if("2".equals(loginType)){
					supplierInfo=new SupplierInfo();
					supplierInfo.setSupplierLoginName(username);
					supplierInfo.setSupplierLoginPwd(PasswordUtil.encrypt(password)) ;
					list= iSupplierInfoBiz.getSupplierInfoListByValidate(supplierInfo);
			        if(list != null && list.size()>0 ) { // 通过用户校验, 保存供应商信息到session并返回主页面
							supplierInfo= (SupplierInfo) list.get( 0 ) ;
							
							if( TableStatus.COMMON_STATUS_VALID.equals( supplierInfo.getIsUsable() ) ){//判断供应商是否有效	
								
								SessionInfo info = new SessionInfo() ;
								info.setSupplierId(supplierInfo.getSupplierId());
								info.setSupplierInfo(supplierInfo);
								info.setSupplierLoginName(supplierInfo.getSupplierLoginName());
								info.setSupplierName(supplierInfo.getSupplierName());
								
								sessionUser=new SessionUser();
								sessionUser.setType(TableStatus.COMMON_TYPE_1);
								sessionUser.setLoginName(supplierInfo.getSupplierLoginName());
								sessionUser.setId(supplierInfo.getSupplierId());
								sessionUser.setName(supplierInfo.getSupplierName());
								info.setSessionUser(sessionUser);
								
								UserRightInfoUtil.setSessionInfo(info, this.getRequest() ) ;

								
								String ip = this.getRequest().getHeader("X-Real-IP");  
								SysUserInoutLog tSysUserInoutLog=new SysUserInoutLog( supplierInfo.getSupplierLoginName(), supplierInfo.getSupplierName(),
										ip, new Date(), this.getSession().getId().toString(), TableStatus.COMMON_STATUS_VALID,TableStatus.COMMON_TYPE_1);
								// 保存登录日志信息
								iSysUserInoutLogBiz.saveSysUserInoutLog(tSysUserInoutLog);
								this.getRequest().getSession().setAttribute("uiId", tSysUserInoutLog.getUilId());
								
							}else {
								errcode=1;
							}	
						}else{ // 校验失败, 返回登陆页面, 提示错误信息
							errcode=2;
						}
				}
				out = this.getResponse().getWriter();
				JSONObject jsonObject = new JSONObject();
				if(errcode!=0){ 
					jsonObject.put("errcode", errcode); 
				}else{ 
					jsonObject.put("success", true);
				}
				//System.out.println(jsonObject.toString());
				out.print(jsonObject.toString());
		} catch (Exception e) {
			log.error("触屏版用户登陆校验错误！", e);
			throw new BaseException("触屏版用户登陆校验错误！", e);
		}
		return null  ;
	}
	/**
	 * 查询公告明细并且进入项目报名页面
	 * @return
	 * @throws BaseException
	 */
	public String viewBidBulletinContentMobile() throws BaseException{
		try{
			BidBulletin bidBulletin=this.iBidBulletinBiz.getBidBulletin(id);
		
			this.getRequest().setAttribute("bidBulletin", bidBulletin);
			
			sysCompany=this.iSysCompanyBiz.getSysCompany(bidBulletin.getComId());
			sysCompany.setManagementModel(BaseDataInfosUtil.convertDictCodeToName(sysCompany.getManagementModel(),DictStatus.COMMON_DICT_TYPE_1708));
		    this.getRequest().setAttribute("sysCompany", sysCompany);
			
			requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(bidBulletin.getRcId());
			this.getRequest().setAttribute("requiredCollect", requiredCollect);
			
			//判断供应商是否登录
			SupplierInfo supplierInfo=UserRightInfoUtil.getSupplierInfo(this.getRequest());
			if(supplierInfo!=null){
				int isInviteSupplier=0;
				InviteSupplier inviteSupplier=new InviteSupplier();
				inviteSupplier.setRcId(requiredCollect.getRcId());
				inviteSupplier.setSupplierId(supplierInfo.getSupplierId());
				List list=this.iInviteSupplierBiz.getInviteSupplierList(inviteSupplier);
				if(list.size()>0){
					isInviteSupplier=1;
				}
				this.getRequest().setAttribute("isInviteSupplier", isInviteSupplier);
			}else{
				int usesType=UserRightInfoUtil.getSessionUserType(this.getRequest());
				if(usesType==0) this.getRequest().setAttribute("eppPerson", 1);
			}
			boolean isApplication=true;
			Date d=new Date();
			if(d.getTime()>bidBulletin.getReturnDate().getTime()){
				isApplication=false;
			}
			this.getRequest().setAttribute("isApplication", isApplication);
			this.getRequest().setAttribute("supplierInfo", supplierInfo);
		} catch (Exception e) {
			log("查询单个公告明细信息并且进入项目报名页面错误！", e);
			throw new BaseException("查询单个公告明细信息并且进入项目报名页面错误！", e);
		}
		return "bidBulletinContentMobile";
	}
	public IBidBulletinBiz getiBidBulletinBiz() {
		return iBidBulletinBiz;
	}

	public void setiBidBulletinBiz(IBidBulletinBiz iBidBulletinBiz) {
		this.iBidBulletinBiz = iBidBulletinBiz;
	}

	public ISupplierProductInfoBiz getiSupplierProductInfoBiz() {
		return iSupplierProductInfoBiz;
	}

	public void setiSupplierProductInfoBiz(
			ISupplierProductInfoBiz iSupplierProductInfoBiz) {
		this.iSupplierProductInfoBiz = iSupplierProductInfoBiz;
	}

	public ICompanySupplierViewBiz getiCompanySupplierViewBiz() {
		return iCompanySupplierViewBiz;
	}

	public void setiCompanySupplierViewBiz(
			ICompanySupplierViewBiz iCompanySupplierViewBiz) {
		this.iCompanySupplierViewBiz = iCompanySupplierViewBiz;
	}
	public IUsersBiz getiUsersBiz() {
		return iUsersBiz;
	}
	public void setiUsersBiz(IUsersBiz iUsersBiz) {
		this.iUsersBiz = iUsersBiz;
	}
	public ISupplierInfoBiz getiSupplierInfoBiz() {
		return iSupplierInfoBiz;
	}
	public void setiSupplierInfoBiz(ISupplierInfoBiz iSupplierInfoBiz) {
		this.iSupplierInfoBiz = iSupplierInfoBiz;
	}
	public IDepartmentsBiz getiDepartmentsBiz() {
		return iDepartmentsBiz;
	}
	public void setiDepartmentsBiz(IDepartmentsBiz iDepartmentsBiz) {
		this.iDepartmentsBiz = iDepartmentsBiz;
	}
	public ISysUserInoutLogBiz getiSysUserInoutLogBiz() {
		return iSysUserInoutLogBiz;
	}
	public void setiSysUserInoutLogBiz(ISysUserInoutLogBiz iSysUserInoutLogBiz) {
		this.iSysUserInoutLogBiz = iSysUserInoutLogBiz;
	}
	public IInviteSupplierBiz getiInviteSupplierBiz() {
		return iInviteSupplierBiz;
	}
	public void setiInviteSupplierBiz(IInviteSupplierBiz iInviteSupplierBiz) {
		this.iInviteSupplierBiz = iInviteSupplierBiz;
	}
	public ISysCompanyBiz getiSysCompanyBiz() {
		return iSysCompanyBiz;
	}
	public void setiSysCompanyBiz(ISysCompanyBiz iSysCompanyBiz) {
		this.iSysCompanyBiz = iSysCompanyBiz;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public IRequiredCollectBiz getiRequiredCollectBiz() {
		return iRequiredCollectBiz;
	}
	public void setiRequiredCollectBiz(IRequiredCollectBiz iRequiredCollectBiz) {
		this.iRequiredCollectBiz = iRequiredCollectBiz;
	}
}
