package com.jeeplus.modules.API.userinfo;

import java.io.InputStream;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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


import com.easemob.server.example.api.impl.EasemobIMUsers;
import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.common.utils.RequestUtils;
import com.jeeplus.modules.sys.security.SystemAuthorizingRealm;
import com.jeeplus.modules.utils.ErrorCode;
import io.swagger.client.model.NewPassword;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.dao.SuggestionDao;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Suggestion;
import com.jeeplus.modules.sys.entity.SystemConfig;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.SystemConfigService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;

import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;


/**
 * 设置Controller
 * @author zmy
 * @version 2017-04-17
 */
@Controller
@RequestMapping(value = "${frontPath}/userInfo/setup")
public class SetUpController extends BaseController{
	@Autowired
	private UserDao userDao;
	@Autowired
	private SystemService systemService;
	@Autowired
	private SuggestionDao suggestionDao;
	@Autowired
	private SystemConfigService systemConfigService;
	

	/**
	 * 意见反馈
	 */
	 @ResponseBody
	 @RequestMapping(value = "saveSuggestion",method=RequestMethod.POST)
		 public AjaxJson saveSuggestion(String id,HttpServletRequest request, HttpServletResponse response)throws Exception  {
		 AjaxJson j=new AjaxJson();
		 HashMap<String, String> requestMap = findRequestMap(request);
         String content = URLDecoder.decode(requestMap.get("content")==null?"":requestMap.get("content"), "UTF-8");
		 User user=UserUtils.get(id);
		 Suggestion suggestion=new Suggestion();
		 suggestion.setCreateBy(user);
	     suggestion.setContent(content);//参数赋值
		 suggestion.preInsert(); //自动生成ID 、createDate、createBy(createBy为登录用户、接口下该值为空)
		 suggestionDao.insert(suggestion); 
		 j.setMsg("感谢您的反馈");
		 j.setErrorCode(ErrorCode.code_1004);
		 return j;
	 }	
	 /**
	  * 消息通知
	  */
//	 @ResponseBody
//	 @RequestMapping(value = "saveNotify",method=RequestMethod.GET)
//	 	public AjaxJson saveNotify(String id,String notifyId,HttpServletRequest request, HttpServletResponse response) {
//		AjaxJson j=new AjaxJson(); 
//		User user=new User();
//		user=userDao.get(id);
//		OaNotify notify=new OaNotify();
//		notify.setId(notifyId);				
//		return j;
//	 }


    //修改密码
    @Transactional
    @ResponseBody
    @RequestMapping(value = "modifyPwd", method = RequestMethod.POST)
    public AjaxJson modifyPwd(HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, String> requestMap = findRequestMap(request);
        AjaxJson j = new AjaxJson();
        String oldPassword = requestMap.get("oldPassword");
        String newPassword = requestMap.get("newPassword");
        String userId = requestMap.get("userId");
        String loginName = requestMap.get("loginName");
        String isCodeModify = requestMap.get("isCodeModify");
        String randomCode = requestMap.get("randomCode");
        String type = requestMap.get("type");
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getResource();
            if (StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(userId)) {
                User user = UserUtils.get(userId);
                if (StringUtils.isNotBlank(oldPassword) && SystemService.validatePassword(oldPassword, user.getPassword())) {
                    systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                    j.setMsg("修改成功");
                    j.setErrorCode(ErrorCode.code_1004);
                } else {
                    j.setMsg("修改失败，旧密码错误");
                    j.setSuccess(false);
                    j.setErrorCode(ErrorCode.code_1012);
                }
            } else if (StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(isCodeModify) && isCodeModify.equals("yes") && StringUtils.isNotBlank(loginName) && StringUtils.isNotBlank(randomCode) &&  StringUtils.isNotBlank(type)) {
                //if (randomCode.equals(request.getSession().getServletContext().getAttribute(loginName)) && type.equals(request.getSession().getServletContext().getAttribute(type))) {
                if (randomCode.equals(jedis.get(loginName)) && type.equals(jedis.get(type))) {
                    User user = UserUtils.getByLoginNameNoSesion(loginName);
                    NewPassword psd = new NewPassword().newpassword(newPassword);
                    EasemobIMUsers easemobIMUsers = new EasemobIMUsers();
                    Object result = easemobIMUsers.getIMUserByUserName(user.getId());
                    if (result != null) {
                        Object result1 = easemobIMUsers.modifyIMUserPasswordWithAdminToken(user.getId(), psd);
                        logger.info(result1.toString());
                    }
                    systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                    j.setMsg("修改成功");
                    j.setErrorCode(ErrorCode.code_1004);
                }else {
                    j.setMsg("修改失败，验证错误");
                    j.setSuccess(false);
                    j.setErrorCode(ErrorCode.code_1012);
                }

            } else {
                j.setMsg("修改失败，验证错误");
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_1012);
            }
        }catch (Exception e){
            j.setMsg("修改失败");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_2004);
        }
        finally {
            JedisUtils.returnResource(jedis);
        }

        return j;
    }

    /**
     * 验证密码
     */
    @ResponseBody
    @RequestMapping(value = "validatePassword",method=RequestMethod.POST)
    public AjaxJson validatePassword(HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, String> requestMap = findRequestMap(request);
        AjaxJson j=new AjaxJson();
        String password=requestMap.get("password");
        String userId=requestMap.get("userId");
        if(!userId.equals(UserUtils.getUser().getId())){
            j.setMsg("验证失败，用户id错误");
            j.setErrorCode(ErrorCode.code_2003);
            j.setSuccess(false);
            return j;
        }
        User user=UserUtils.getUser();
        if(SystemService.validatePassword(password,user.getPassword())){
            j.setErrorCode(ErrorCode.code_1004);
            j.setSuccess(true);
            j.setMsg("密码正确");
        }else{
            j.setErrorCode(ErrorCode.code_1012);
            j.setSuccess(false);
            j.setMsg("密码错误");
        }
        return j;
    }


    /**
     * 更换手机号
     */
    @ResponseBody
    @RequestMapping(value = "updateMobile",method=RequestMethod.POST)
    public AjaxJson updateMobile(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j=new AjaxJson();
        HashMap<String, String> requestMap = findRequestMap(request);
        String userId=requestMap.get("userId");
        String mobile=requestMap.get("mobile");
        User user=UserUtils.getUser();
        if(user == null || user.getId() ==null){
            user = UserUtils.get(userId);
        }
        if(userDao.findUniqueByProperty("login_name", mobile)==null){
            user.setLoginName(mobile);
            user.setMobile(mobile);
            systemService.updateMo(user);
            CacheUtils.remove("userCache");
            j.setMsg("更换成功");
            j.setErrorCode(ErrorCode.code_1004);
        }else{
            j.setErrorCode(ErrorCode.code_1007);
            j.setMsg("更换失败，该手机号已有用户使用");
        }
        UserUtils.getNoSession(userId);
        return j;
    }

    /**
     * 修改密码
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "savePassword",method=RequestMethod.POST)
    public AjaxJson savePassword(String id,HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, String> requestMap = findRequestMap(request);
        AjaxJson j=new AjaxJson();
        String oldPassword=requestMap.get("oldPassword");
        String newPassword=requestMap.get("newPassword");
        User user=new User();
        user=userDao.get(id);
        if(SystemService.validatePassword(oldPassword,user.getPassword())){
            systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
            j.setMsg("修改成功");
            j.setErrorCode(ErrorCode.code_1004);
        }else{
            j.setMsg("修改失败，旧密码错误");
            j.setErrorCode(ErrorCode.code_2003);
        }
        return j;
    }

    /**
     *审批 (*审批成功)
     *
     * @param
     */
    @ResponseBody
    @RequestMapping(value = "updateUser", method = RequestMethod.GET)
    public AjaxJson updateUser(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson json = new AjaxJson();
        User u = new User();
        u.setCompany(UserUtils.getSelectCompany());
        List<User> users = userDao.findList(u);
        for (User user:users){
            if (!user.getId().equals("1")) {
                systemService.updatePasswordById(user.getId(), user.getLoginName(), systemService.encrypeString("123456"));
            }
        }
        json.setSuccess(true);
        json.setMsg("修改成功");
        json.setErrorCode(ErrorCode.code_1004);
        return json;
    }

}
