package com.qiankun.controller;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.ResourceBundle;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qiankun.annotation.Auth;
import com.qiankun.controller.base.BaseController;
import com.qiankun.dao.core.Hints;
import com.qiankun.entity.Contacts;
import com.qiankun.entity.User;
import com.qiankun.pages.IPageList;
import com.qiankun.service.UserService;
import com.qiankun.utils.MD5;
import com.qiankun.utils.SessionUtils;
import com.qiankun.vo.ProductVo;
import com.qiankun.vo.UserVo;
 
@Controller
public class UserController extends BaseController<Object>{
    
    @Autowired
	private UserService userService;
    
    @Auth(verifyLogin = false, verifyURL = false)
    @RequestMapping("/reg")
    public ModelAndView index() throws Exception {
        ModelAndView t_view = new ModelAndView();
        t_view.setViewName("reg");
        return t_view;
    }
    
    @Auth(verifyLogin = false, verifyURL = false)
    @RequestMapping("/login")
    public ModelAndView login() throws Exception {
        ModelAndView t_view = new ModelAndView();
        t_view.setViewName("login");
        return t_view;
    }  

    @Auth(verifyLogin = false, verifyURL = false)
    @RequestMapping("/api/user/save")
    public ModelAndView saveUser(UserVo userVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
    	
        ModelAndView view = new ModelAndView();

        User user = new User();
       
        if (StringUtils.isEmpty(userVo.getId())) {
        	
        	Boolean userIsExistMobile = userService.validateUserExistByMobile(userVo.getMobile());
        	if (userIsExistMobile) {
				view.getModel().put("message", "userIsExist_mobile");
				return view;
			}
        	
			Boolean userIsExistUserName = userService.validateUserExistByTeamName(userVo.getTeamName());
			if (userIsExistUserName) {
				view.getModel().put("message", "userIsExist_teamName");
				return view;
			}
        	     	
        	
        	user.setMobile(userVo.getMobile());
        	user.setPwd(MD5.digest(userVo.getPwd()));
        	user.setUserName(userVo.getUserName());
        	
        	user.setEmail(userVo.getEmail());
        	Date date = new Date();
        	user.setCreateTime(date);
        	
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy");        
        	String year = sdf.format(date);
        
        	
        	Contacts product = new Contacts();
        	product.setUser(user);
        	user.getContacts().add(product);
        	view.getModelMap().put("status", 1);
        	       	
        } else {
        	if(userVo.getChangePassword()!=null&&userVo.getChangePassword()){
        		Boolean validatePwd = userService.validatePwd(userVo.getId(), userVo.getOldpwd());
        		if (!validatePwd) {
        			view.getModel().put("message", "oldPwdError");
    				return view;
        		}
			}
        	user = userService.findById(userVo.getId());     
        	if (StringUtils.isNotBlank(userVo.getTeamName())) {
        		Boolean userIsExistUserName = userService.validateUserExistByTeamName(userVo.getTeamName());
    			if (userIsExistUserName) {
    				view.getModel().put("message", "userIsExist_teamName");
    				return view;
    			}
        	}
        	
        	if(userVo.getChangePassword()!=null && userVo.getChangePassword()){
        		user.setPwd(MD5.digest(userVo.getPwd()));		
        	}
        	user.setUserName(userVo.getUserName());
        	user.setEmail(userVo.getEmail());
        	
        	
        }      
        userService.save(user);
        return view;
    }
    
    @Auth(verifyLogin = false, verifyURL = false)
	@RequestMapping("/api/signin")
	public ModelAndView signin(HttpServletRequest request,
			final HttpServletResponse response, String mobile, String pwd)
			throws Exception {
		ModelAndView view = new ModelAndView();
		ResourceBundle rb = ResourceBundle.getBundle("system");
		String superAdmin = rb.getString("account");
		
		if (mobile.equals(superAdmin)) {
			
	        String p = rb.getString("password");
	        if (p.equals(pwd)) {
	        	User user = new User();
	        	user.setMobile(superAdmin);
	        	user.setUserName(superAdmin);
	        	user.setPwd(MD5.digest(pwd));
	        	SessionUtils.setUser(request, user);		
	        	view.getModelMap().addAttribute("status", 2);
	        } else {
	        	view.getModelMap().addAttribute("status", 0);
	        }
        		
		} else {
			User user = userService.userLogin(mobile, pwd);
			if (user != null) {
				// 设置User到Session
	 			SessionUtils.setUser(request, user);		
	 			view.getModelMap().addAttribute("status", 1);
			} else {
				view.getModelMap().addAttribute("status", 0);			
			}
		}
		
		
		return view;
	}
    
    @RequestMapping("/api/user/list")
    public ModelAndView userList(UserVo userVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        ResourceBundle rb = ResourceBundle.getBundle("system");
		String superAdmin = rb.getString("account");
		String p = rb.getString("password");
		User userSession = SessionUtils.getUser(request);
		
		
		if (superAdmin.equals(userSession.getMobile()) && MD5.digest(p).equals(userSession.getPwd())) {
			
			IPageList<User> userPage = userService.findByUsers(userVo.getSearchStr(), userVo.getGroups(), userVo.getOrder(), userVo.getSort(), 
					new Hints(getStartRow(request), getPageCount(request)));
			
			view.getModelMap().addAttribute("userPage", userPage);
			view.getModelMap().addAttribute("pageCount", getPageCount(request));
			view.getModelMap().addAttribute("pageNumber", getPageNumber(request));
			view.getModelMap().addAttribute("userVo", userVo);
			view.setViewName("userList");
		} else {
			SessionUtils.removeUser(request);
			view.setViewName("index");
		}
        
        
        return view;
    }
    
    @RequestMapping("/api/user/del")
    public ModelAndView delUser(String id, HttpServletResponse response, HttpServletRequest request) throws Exception {
    	ModelAndView view = new ModelAndView();
    	User userSession = SessionUtils.getUser(request);
    	ResourceBundle rb = ResourceBundle.getBundle("system");
 		String superAdmin = rb.getString("account");
    	if (superAdmin.equals(userSession.getMobile()) && (superAdmin.equals(userSession.getUserName()))) {
    		userService.remove(id);     		
    	} else {
    		view.getModelMap().addAttribute("userPage", "Illegal Users");
    	}
    	return view;
    }
    
    @RequestMapping("/api/product/save")
    public ModelAndView saveProduct(ProductVo productVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
    	ModelAndView view = new ModelAndView();
    	User userSession = SessionUtils.getUser(request);
    	User user = userService.findById(userSession.getId());
		Contacts product = new Contacts();
		Set<Contacts> productSet = user.getContacts();
		Iterator<Contacts> its = productSet.iterator();
		if (its.hasNext()) {
			product = its.next();
		}
		product.setName(productVo.getName());
		product.setUpdateTime(new Date());
		user.getContacts().clear();
		user.getContacts().add(product);
		userService.save(user);
		view.getModelMap().put("message","success");
    	return view;
    }
    
    @RequestMapping("/profile")
    public ModelAndView profile(HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
		User user = SessionUtils.getUser(request);
		view.getModelMap().put("user",userService.findById(user.getId()));
		view.setViewName("profile");
		return view;
	}

    @RequestMapping("/product")
    public ModelAndView product(HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
		User userSession = SessionUtils.getUser(request);
		User user = userService.findById(userSession.getId());
		Contacts product = new Contacts();
		Set<Contacts> productSet = user.getContacts();
		Iterator<Contacts> its = productSet.iterator();
		if (its.hasNext()) {
			product = its.next();
		}
		
		view.getModelMap().put("product",product);
		view.getModelMap().put("user",user);
		
		view.setViewName("product");
		return view;
	}
    @RequestMapping("/api/product/enroll/upload")
    public ModelAndView uploadEnroll(@RequestParam(value = "enroll", required = false) MultipartFile file, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
    	ModelAndView view = this.writeImportFile(file , "enroll", new ModelAndView(), request);
    	return view; 	
    }
    
    @RequestMapping("/api/product/report/upload")
    public ModelAndView uploadReport(@RequestParam(value = "report", required = false) MultipartFile file, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
    	ModelAndView view = this.writeImportFile(file , "report", new ModelAndView(), request);
    	return view; 	
    }
    
    @RequestMapping("/api/product/ppt/upload")
    public ModelAndView uploadPPT(@RequestParam(value = "ppt", required = false) MultipartFile file, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
    	ModelAndView view = this.writeImportFile(file , "ppt", new ModelAndView(), request);
    	return view; 	
    }
    
    @RequestMapping("/api/product/attachment/upload")
    public ModelAndView uploadAttachment(@RequestParam(value = "attachment", required = false) MultipartFile file, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
    	ModelAndView view = this.writeImportFile(file , "attachment", new ModelAndView(), request);
    	return view; 	
    }
    
    public ModelAndView writeImportFile(MultipartFile file, String type, ModelAndView view, HttpServletRequest request) throws Exception {
    	if (file != null) {			
			if (file.getSize()<=0) {
				view.getModelMap().put("status", 0);
	    		view.getModelMap().put("size", 0);
	    		return view;
	    	}
			if ("enroll".equals(type) && file.getSize() > 10240000) {
				view.getModelMap().put("size", 10);
				view.getModelMap().put("status", 0);
				return view;
			}
			if ("report".equals(type) && file.getSize() > 51200000) {
				view.getModelMap().put("size", 50);
				view.getModelMap().put("status", 0);
				return view;
			}
			if ("ppt".equals(type) && file.getSize() > 102400000) {
				view.getModelMap().put("size", 100);
				view.getModelMap().put("status", 0);
				return view;
			}
			if ("attachment".equals(type) && file.getSize() > 102400000) {
				view.getModelMap().put("size", 100);
				view.getModelMap().put("status", 0);
				return view;
			}
		}
    	
    	User userSession = SessionUtils.getUser(request);
    	
        ResourceBundle rb = ResourceBundle.getBundle("system");
        String path = rb.getString("file_path")  + "/";
        File f = new File(path);
        if (!f.exists() && !f.isDirectory()) {
        	f.mkdir();
        }
        
        path = path + type + "/";
        f = new File(path);

        if (!f.exists() && !f.isDirectory()) {
        	f.mkdir();
	    }
        
        if (f.exists() && f.isDirectory()) {

        	String[] tempList = f.list();  
            File temp = null;  
            for (int i = 0; i < tempList.length; i++) {  
                if (path.endsWith(File.separator)) {  
                    temp = new File(path + tempList[i]);  
                } else {  
                    temp = new File(path + File.separator + tempList[i]);  
                }  
                if (temp.isFile()) {  
                    temp.delete();  
                }  
               
            }  
            
	    }
        
 
        String fileFullName = file.getOriginalFilename();
        FileOutputStream t_fos = null;
        try {
            t_fos = new FileOutputStream(new File(path, fileFullName), true);
            t_fos.write(file.getBytes());
        } finally {
            try {
                if (t_fos != null) {
                    t_fos.flush();
                    t_fos.close();
                }
            } catch (final Exception t_e) {
                throw t_e;
            }
        }
        view.getModelMap().put("fileName", fileFullName);
        view.getModelMap().put("status", 1);
        
        
        User user = userService.findById(userSession.getId());
		Contacts product = new Contacts();
		Set<Contacts> productSet = user.getContacts();
		Iterator<Contacts> its = productSet.iterator();
		if (its.hasNext()) {
			product = its.next();
		}
		
		product.setUpdateTime(new Date());
		user.getContacts().clear();
		user.getContacts().add(product);
		userService.save(user);
		
        return view;
    }
    
    @RequestMapping("/api/product/download")
    public ModelAndView downloadFile(String fileName, String type, String userId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	ModelAndView view = new ModelAndView();

    	FileInputStream fis = null;
    	OutputStream os = null;
        try {  
        	User userSession = SessionUtils.getUser(request);
        	ResourceBundle rb = ResourceBundle.getBundle("system");
        	
        	
        	String path = rb.getString("file_path") + userId + "/" + type + "/" + fileName;
        	response.setContentType("application/octet-stream");  
        	response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
        	//File file = new File(path);  
        	fis = new FileInputStream(path);
            os = response.getOutputStream();
            byte[] b = new byte[1024];
			int i = 0; 
			while ( (i = fis.read(b)) > 0 ) 
			{
			os.write(b, 0, i);
			} 
			os.flush();
            
        } catch (IOException e) {  
            ;
        }  finally {
	        if(fis != null) {  
	        	try{
	            fis.close();
	            fis = null;
	        	}
	            catch(Exception e)
	        	{
	        		//System.out.print(e.toString());
	        	}
	        }
	        if(os != null) {
	         try{
	            os.close();
	            os = null;
	        }
            catch(Exception e)
        	{
        		//System.out.print(e.toString());
        	}
	        }
	    } 
        view.setViewName("download");
    	return view;
    }
}