package com.qiankun.controller;
 
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

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

import com.qiankun.utils.JwtTokenUtil;
import com.qiankun.utils.UserUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
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.UserVo;
 
@Controller
public class UserController extends BaseController<Object>{
    
    @Autowired
	private UserService userService;
    @Autowired
    private JwtTokenUtil tokenUtil;
    
    
    
    @Auth(verifyLogin = false, verifyURL = false)
    @RequestMapping("/login")
    public ModelAndView login() throws Exception {
        ModelAndView t_view = new ModelAndView();
        t_view.setViewName("login");
        return t_view;
    }  
    
    
    
    @RequestMapping("/user/add")
    public ModelAndView userAdd(String id) throws Exception {
        ModelAndView view = new ModelAndView();
        UserVo vo = new UserVo();
        if(StringUtils.isNotBlank(id)) {
        	User user = userService.findById(id);
        	vo.setId(user.getId());
        	vo.setUserName(user.getMobile());
        	vo.setUserCode(user.getUserCode());
        	vo.setName(user.getName());
        	vo.setGender(user.getGender());
        	vo.setBirthday(user.getBirthday());
        	vo.setPaperType(user.getPaperType());
        	vo.setPaperId(user.getPaperId());
        	vo.setNation(user.getNation());
        	vo.setNativePlace(user.getNativePlace());
        	vo.setNationality(user.getNationality());
        	vo.setEducation(user.getEducation());
        	vo.setDomicilePlace(user.getDomicilePlace());
        	vo.setAddr(user.getAddr());
        	vo.setUnit(user.getUnit());
        	vo.setUnitAddr(user.getUnitAddr());
        	vo.setUnitTel(user.getUnitTel());
        	vo.setProfession(user.getProfession());
        	vo.setMobile(user.getMobile());    	
        	vo.setEmail(user.getEmail());
        	vo.setTel(user.getTel());
        	vo.setQq(user.getQq());
        	vo.setWeixin(user.getWeixin());
        	vo.setDonateBloodCount(user.getDonateBloodCount());
        	vo.setBloodType(user.getBloodType());
        	vo.setHeight(user.getHeight());
        	vo.setWeight(user.getWeight());
        	vo.setRemark(user.getRemark());
        	vo.setRole(user.getRole());
        	
        	Set<Contacts> contacts = user.getContacts();
        	Iterator<Contacts> its = contacts.iterator();
        	Integer count = 0;
        	while (its.hasNext()) {
        		Contacts c = its.next();
        		if (count == 0) {
        			vo.setContactsAddr1(c.getAddr());
        			vo.setContactsName1(c.getName());
        			vo.setContactsMobile1(c.getMobile());
        			vo.setContactsRelation1(c.getRelation());
        			vo.setContactsWeixin1(c.getWeixin());
        			vo.setContactsQQ1(c.getQq());
        			count ++;
        		} else {
        			vo.setContactsAddr2(c.getAddr());
        			vo.setContactsName2(c.getName());
        			vo.setContactsMobile2(c.getMobile());
        			vo.setContactsRelation2(c.getRelation());
        			vo.setContactsWeixin2(c.getWeixin());
        			vo.setContactsQQ2(c.getQq());
        		}
        		
        		
        	}
        	
        }
        
        
        view.setViewName("user/saveuser");
        view.getModel().put("dict", dict());
        view.getModel().put("user", vo);
        return view;
    }
    
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/wx/api/user/save",method = RequestMethod.POST)
    public @ResponseBody Map<String,Object> saveUserformWX(@RequestBody UserVo userVo, HttpServletResponse response, HttpServletRequest request) throws Exception{
    	return this.saveUser(userVo, response, request);
    }
    
    
    
    @RequestMapping("/api/user/save")
    public Map<String, Object> saveUser(UserVo userVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
    	
        Map<String, Object> map = new HashMap<>();
        
    	User user = new User();
    	Date date = new Date();	
    	
    	if (StringUtils.isEmpty(userVo.getId())) {
    		
    		Boolean userIsExistPaperId = userService.validateUserExistByPaperId(userVo.getPaperId());
        	if (userIsExistPaperId) {
        		map.put("status", 0);
        		map.put("message", "userIsExist_paperId");
        		return map;
        	}
        	
        	Boolean userIsExistUserName = userService.validateUserExistByUserName(userVo.getUserName());
        	if (userIsExistUserName) {
        		map.put("status", 0);
        		map.put("message", "userIsExist_userName");
        		return map;
        	}
        	
			user.setCreateTime(date);
			map.put("status", 1);
        } else {

        	user = userService.findById(userVo.getId());
        	
        	if (StringUtils.isNotBlank(userVo.getPaperId()) && !userVo.getPaperId().equals(user.getPaperId())) {
        		Boolean userIsExistPaperId = userService.validateUserExistByPaperId(userVo.getPaperId());
    			if (userIsExistPaperId) {
    				map.put("status", 0);
    				map.put("message", "userIsExist_paperId");
    				return map;
    			}
        	}
        	
        	if (StringUtils.isNotBlank(userVo.getUserName()) && !userVo.getUserName().equals(user.getUserName())) {
        		Boolean userIsExistUserName = userService.validateUserExistByUserName(userVo.getUserName());
    			if (userIsExistUserName) {
    				map.put("status", 0);
    				map.put("message", "userIsExist_userName");
    				return map;
    			}
        	}
        	
        	user.setUpdateTime(date);	
        	user.getContacts().clear();
        	map.put("status", 2);
        }  

    	user.setUserName(userVo.getMobile());
        user.setName(userVo.getName());
        user.setOpenid(userVo.getOpenid());
        user.setGender(userVo.getGender());
        user.setBirthday(userVo.getBirthday());
        user.setPaperType(userVo.getPaperType());
        user.setPaperId(userVo.getPaperId());
        user.setNation(userVo.getNation());
        user.setNativePlace(userVo.getNativePlace());
        user.setNationality(userVo.getNationality());
        user.setEducation(userVo.getEducation());
        user.setDomicilePlace(userVo.getDomicilePlace());
        user.setAddr(userVo.getAddr());
        user.setUnit(userVo.getUnit());
        user.setUnitAddr(userVo.getUnitAddr());
        user.setUnitTel(userVo.getUnitTel());
        user.setProfession(userVo.getProfession());
        user.setMobile(userVo.getMobile());    	
    	user.setEmail(userVo.getEmail());
    	user.setTel(userVo.getTel());
    	user.setQq(userVo.getQq());
    	user.setWeixin(userVo.getWeixin());
    	user.setDonateBloodCount(userVo.getDonateBloodCount());
    	user.setBloodType(userVo.getBloodType());
    	user.setHeight(userVo.getHeight());
    	user.setWeight(userVo.getWeight());
    	user.setRemark(userVo.getRemark());
    	user.setRole(userVo.getRole());
    	user.setStatus(userVo.getStatus());
    	
    	Contacts contacts1 = new Contacts();
    	contacts1.setName(userVo.getContactsName1());
    	contacts1.setAddr(userVo.getContactsAddr1());
    	contacts1.setMobile(userVo.getContactsMobile1());
    	contacts1.setRelation(userVo.getContactsRelation1());
    	contacts1.setWeixin(userVo.getContactsWeixin1());
    	contacts1.setQq(userVo.getContactsQQ1());
    	contacts1.setUpdateTime(date);        	
    	contacts1.setUser(user);
    	user.getContacts().add(contacts1);
    	
    	Contacts contacts2 = new Contacts();
    	contacts2.setName(userVo.getContactsName2());
    	contacts2.setAddr(userVo.getContactsAddr2());
    	contacts2.setMobile(userVo.getContactsMobile2());
    	contacts2.setRelation(userVo.getContactsRelation2());
    	contacts2.setWeixin(userVo.getContactsWeixin2());
    	contacts2.setQq(userVo.getContactsQQ2());
    	contacts2.setUpdateTime(date);        	
    	contacts2.setUser(user);
    	user.getContacts().add(contacts2);
    	
        User u = userService.save(user);
        map.put("user", UserUtils.converToVo(u));
        map.put("sKey",tokenUtil.generateToken(u.getOpenid()));
        return map;
    }
    
    @Auth(verifyLogin = false, verifyURL = false)
	@RequestMapping("/api/signin")
	public ModelAndView signin(HttpServletRequest request,
			final HttpServletResponse response, String userName, String pwd)
			throws Exception {
		ModelAndView view = new ModelAndView();
		ResourceBundle rb = ResourceBundle.getBundle("system");
		String superAdmin = rb.getString("account");
		
		if (userName.equals(superAdmin)) {
			
	        String p = rb.getString("password");
	        if (p.equals(pwd)) {
	        	User user = new User();
	        	user.setMobile(superAdmin);
	        	user.setPwd(MD5.digest(pwd));
	        	SessionUtils.setUser(request, user);		
	        	view.getModelMap().addAttribute("status", 1);
	        } else {
	        	view.getModelMap().addAttribute("status", 0);
	        }
        		
		} else {
			User user = userService.userLogin(userName, pwd);
			if (user != null) {
				// 设置User到Session
				if ("1".equals(user.getRole())){
					SessionUtils.setUser(request, user);		
		 			view.getModelMap().addAttribute("status", 1);
				} else {
					view.getModelMap().addAttribute("status", 0);
				}
	 			
			} else {
				view.getModelMap().addAttribute("status", 0);			
			}
		}
		
		
		return view;
	}
    
    @RequestMapping("/user/list")
    public ModelAndView userList(UserVo userVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        IPageList<User> userPage = userService.findByUsers(userVo.getSearchStr(), userVo.getRole(), userVo.getStatus(), 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("user/userlist");
		
        
        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;
    }

}