package com.yc.education.controller.admin;

import com.yc.education.controller.BaseController;
import com.yc.education.mapper.AdminsMapper;
import com.yc.education.model.Admins;
import com.yc.education.util.AjaxMessage;
import com.yc.education.util.AppConst;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 后台 统一操作controller
 */
@Controller
@RequestMapping("/admin")
public class AdminsBackController extends BaseController{
	
	@Autowired
	private AdminsMapper adminsMapper;

	/**
	 *验证账户是否存在  Lock-玄清
	 * @return
	 */
	@ResponseBody
	@RequestMapping("gologin.html")
	public AjaxMessage<Object> login(Admins admin, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		AjaxMessage<Object> ajax = new AjaxMessage<>();
		Admins user = adminsMapper.findexist(admin.getName(), admin.getPwd());
		if(user != null){
			ajax.setIs(true);
			request.getSession().setAttribute(AppConst.Session_Admin, user);
			System.out.println("登录成功！");
		}else{
			ajax.setIs(false);
			ajax.setMsg("* 你输入的用户名或密码有误！");
			System.out.println("登录失败！");
		}
		return ajax;
	}

	/**
	 * 修改密码   Lock-玄清
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("updapass.html")
	public AjaxMessage<Object> updapass(String oldpwd,String newpwd,HttpServletRequest request){
		AjaxMessage<Object> ajax = new AjaxMessage<>();
		Admins admins = getLoginUser(request);
		if(admins != null){
			System.err.println(admins.getPwd());
			System.err.println(oldpwd);
			System.err.println(newpwd);
			if((admins.getPwd()).equals(oldpwd)){
				Admins admin = new Admins();
				admin.setId(admins.getId());
				admin.setPwd(newpwd);
				int rows = adminsMapper.updateByPrimaryKeySelective(admin);
				if(rows>0){
					ajax.setIs(true);
					ajax.setMsg("修改成功！");
				}else{
					ajax.setIs(false);
					ajax.setMsg("修改失败！");
				}
			}else{
				ajax.setIs(false);
				ajax.setMsg("你输入的原密码错误！");
			}
		}else{
			ajax.setIs(false);
			ajax.setMsg("修改失败！");
		}
		return ajax;
	}
	
	/**
	 * 注销会话
	 * @return
	 */
	@RequestMapping("logout.html")
	public String logout(HttpSession session){
		session.removeAttribute(AppConst.Session_Admin);
        return "redirect:login.html";
	}

    /**
     * 获取当前登录人名称
     * @param session
     * @return
     */
	@ResponseBody
    @RequestMapping(value="getloginname",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
    public String  getloginname(HttpSession session){
	    Admins admins = (Admins) session.getAttribute(AppConst.Session_Admin);
        if(admins!=null){
            return admins.getName();
        }else{
            return "";
        }
    }

	/**
	 * 跳转到操作成功页面   Lock-玄清
	 * @return
	 */
	@RequestMapping(value={"success.html","success"})
	public ModelAndView success(){
		return new ModelAndView();
	}
	
	/**
	 * 跳转到操作失败页面   Lock-玄清
	 * @return
	 */
	@RequestMapping(value={"error.html","error"})
	public ModelAndView error(){
		return new ModelAndView();
	}


    /**
     * ajax异步上传
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "uploadImage.html", method = RequestMethod.POST)
    public String uploadImage(HttpServletRequest request)
            throws IllegalStateException, IOException {
        System.out.println("进入控制层");
        String pathString="";
        @SuppressWarnings("unused")
        String allpath="";
        List<String> paths = new ArrayList<>();
        // 设置上下文
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 检查form是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 由CommonsMultipartFile继承而来,拥有上面的方法.
                MultipartFile file = multiRequest.getFile(iter.next());
                System.out.println("file:" + file.getSize());
                // 如果文件不为空，则进行处理
                if (!file.isEmpty()) {
                    // 存放产生的随机数
                    String sms = getRandomone();
                    // 对图片文件名进行处理，取得最后的6个字符，然后以"."为分隔符取得文件后缀
                    String originalFileName = file.getOriginalFilename();
                    // 取得后缀
                    String suffixString = originalFileName
                            .substring(originalFileName.lastIndexOf(".") + 1);
                    // 设定文件名称
                    String fileName =  sms+new Date().getTime() + "." + suffixString;
                    //
                    String path = request.getSession().getServletContext().getRealPath("/");
                    String contextPath = request.getSession().getServletContext().getContextPath();
                    File localFile = new File(path+"ajaxupload\\"+fileName);
                    System.err.println(path+"ajaxupload\\"+fileName);
                    try {
                        file.transferTo(localFile);
                        // 将图片名称和相对路径存到数据库中
                        paths.add("/pic/chat/" + fileName);
                        pathString = contextPath+"/ajaxupload/"+fileName;
                        allpath = path+"ajaxupload/"+fileName;
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        // pathString="cao";
        return pathString;
    }
}
