package cn.com.liandisys.ycjt.ggcx.admin.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import cn.com.liandisys.ycjt.ggcx.admin.model.User;
import cn.com.liandisys.ycjt.ggcx.admin.service.UserService;
import cn.com.liandisys.ycjt.ggcx.admin.utils.Digests;
import cn.com.liandisys.ycjt.ggcx.common.util.UserUtils;




/**
 * 后台管理登录控制器
 * @author jiangchao
 * @version 2016-11-28
 */
@Controller
@RequestMapping(value = "/admin")
public class AdminMainController {
	
	protected Logger logger = LoggerFactory.getLogger(AdminMainController.class);
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/main", method = RequestMethod.GET)
    public String main() {
        return "admin/main";
    }
	
	/**
	 * 跳转到密码修改页面
	 * @return 密码设定页面
	 */
	@RequestMapping(value="/passwordMng", method=RequestMethod.GET)
	public String list(){
		return "admin/accountMng/passwordMng";
	}
	
	/**
	 * 修改密码
	 * @param passwordOld 旧密码
	 * @param passwordNew 新密码
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/save", method=RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> PasswordSave(@RequestParam("oldPassword")String passwordOld,
        @RequestParam("newPassword")String passwordNew,Model model) throws IOException{
		 Map<String, Object> result = new HashMap<String, Object>();
		Subject subject = SecurityUtils.getSubject();
		User userTemp=(User) subject.getPrincipal();
	    String loginname = userTemp.getLoginName();
	    //获得新密码
	    User user=userService.findByLoginName(loginname);
	    String password=user.getPassword();
	    //密码加密
	    String passwordtemp =Digests.md5Hex(new ByteArrayInputStream(passwordOld.getBytes()));
	    //比较输入旧密码是否正确
	    if(!password.equals(passwordtemp)){
	    	result.put("result", "error");
	        result.put("msg", "请输入正确的旧密码");
	        return result;
	    }
	    passwordNew = Digests.md5Hex(new ByteArrayInputStream(passwordNew.getBytes()));
	    user.setPassword(passwordNew);
	    try{
	    	 userService.saveUser(user);
	    	 result.put("result", "ok");
	    }catch(Exception e){
	       e.toString();
	       result.put("result", "error");
           result.put("msg", "更新密码失败！");
           return result;
	    }
	    result.put("msg", "更新密码成功！");
        return result;
	}
	
	
}
