package com.controller.admin;


import com.controller.CommonController;
import com.entity.Users;
import com.service.UsersService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.util.Info;
import org.springframework.web.multipart.MultipartFile;

/**
 *  用户控制类
 * @ignore
 * @Author:Alcedo QQ:815657032
 * @Date 2020/4/15 11:05
 */
@Controller
@RequestMapping("/admin/")
public class UsersController {
    @Resource
    private UsersService usersService;

    @Resource
    private CommonController commonController;
    /*设置访问路径*/
    private String path = "admin/views/users/";


    public static final String TABLE_NAME = "用户";




    /*个人信息*/
    @RequestMapping("showUserInfo.do")
    public String showUserInfo(ModelMap map, HttpSession session) {
        if (session.getAttribute("auser") == null) {
            return "login";
        }
        /*通用方法*/
        commonController.commonMethod(map);
        Users u = (Users) session.getAttribute("auser");
        map.put("users", usersService.getById(u.getId()));
        return path + "users_update_person";
    }

    /*保存个人信息*/
    @RequestMapping("updatePersonUser.do")
    public String updateUserInfo(ModelMap map, @RequestParam(value = "file", required = false) MultipartFile file,
                                 Users user, HttpSession session, String img, HttpServletRequest request) {
        img = Info.fileUpload(file, request, img);
        if (img != null && !img.equals("zanwu.jpg")) {
            user.setImg(img);
        }
        usersService.update(user);
        map.put("users", usersService.getById(user.getId()));
        session.setAttribute("suc", "cc");
        return "admin/success";
    }


    /*处理注册*/
    @RequestMapping("doAddReg.do")
    public String doAddReg(HttpServletRequest request, ModelMap map) {
        /*通用方法*/
        commonController.commonMethod(map);
        return "admin/reg";
    }
    @RequestMapping("addReg.do")
    public String addReg(@RequestParam(value = "file", required = false) MultipartFile file, String img,
                           HttpServletRequest request, Users users, HttpSession session) {
        img = Info.fileUpload(file, request, img);
        users.setImg(img);
        users.setPubtime(new Timestamp(System.currentTimeMillis()).toString().substring(0, 19));
        usersService.add(users);
        return "admin/login";
    }

    /**
     * ===后台用户管理===
     *
     * @return
     */

    /*处理添加用户*/
    @RequestMapping("doAddUsers.do")
    public String doAddUsers(HttpServletRequest request, ModelMap map) {
        /*通用方法*/
        commonController.commonMethod(map);
        return path + "users_add";
    }



    // 添加用户
    @RequestMapping("addUsers.do")
    public String addUsers(@RequestParam(value = "file", required = false) MultipartFile file, String img,
                           HttpServletRequest request, Users users, HttpSession session) {
        img = Info.fileUpload(file, request, img);
        users.setImg(img);
        users.setPubtime(new Timestamp(System.currentTimeMillis()).toString().substring(0, 19));
        usersService.add(users);
        return "admin/success";
    }


    /*处理修改用户*/
    @RequestMapping("doUpdateUsers.do")
    public String doUpdateUsers(HttpServletRequest request, int id, ModelMap map) {
        map.put("users", usersService.getById(id));
        /*通用方法*/
        commonController.commonMethod(map);
        return path + "users_update";
    }

    /*查看用户*/
    @RequestMapping("doLookUsers.do")
    public String doLookUsers(HttpServletRequest request, int id, ModelMap map) {
        map.put("users", usersService.getById(id));
        /*通用方法*/
        commonController.commonMethod(map);
        return path + "users_look";
    }

    /*保存用户*/
    @RequestMapping("updateUsers.do")
    public String updateUsers(@RequestParam(value = "file", required = false) MultipartFile file, String img,
                              HttpServletRequest request, Users users) {
        img = Info.fileUpload(file, request, img);
        if (img != null && !img.equals("")) {
            users.setImg(img);
        }
        usersService.update(users);
        return "admin/success";
    }


    // 分页查询用户信息的列表
    @RequestMapping("usersList.do")
    public String usersList(@RequestParam(value = "page", defaultValue = "0") Integer page, ModelMap map,
                            HttpSession session) {
        Users users = (Users) session.getAttribute("auser");
        if (users == null) {
            return "admin/login";
        } else {
            Map<String, Object> bMap = new HashMap<>();
            if (users.getUtype().equals("辅导员")){
                bMap.put("fid",users.getId());
            }
            bMap.put("utype", "普通用户");
            List<Users> list = usersService.getAll(bMap);
            map.put("list", list);
            /*通用方法*/
            commonController.commonMethod(map);
            return path + "users_list";
        }
    }




    // 分页查询用户信息的列表--模糊查询
    @RequestMapping("usersListSearch.do")
    public String usersListSearch(@RequestParam(value = "page", defaultValue = "0") Integer page, ModelMap map,
                                  HttpSession session, Users users) {
        Map<String, Object> bMap = new HashMap<>();

        if (users.getName() != null && !users.getName().equals("")) {
            bMap.put("name", users.getName());
        }
        if (users.getUname() != null && !users.getUname().equals("")) {
            bMap.put("uname", users.getUname());
        }
        if (users.getAddress() != null && !users.getAddress().equals("")) {
            bMap.put("address", users.getAddress());
        }
        if (users.getUtype() != null && !users.getUtype().equals("")) {
            bMap.put("utype", users.getUtype());
        }
        if (users.getAge() != null && !users.getAge().equals("")) {
            bMap.put("age", users.getAge());
        }

        if (users.getEmail() != null && !users.getEmail().equals("")) {
            bMap.put("email", users.getEmail());
        }
        /*bMap.put("utype","普通用户");*/
        List<Users> list = usersService.getAll(bMap);
        map.put("list", list);
        /*通用方法*/
        commonController.commonMethod(map);
        return path + "users_list";
    }

    /*删除用户*/
    @RequestMapping("deleteUsers.do")
    public String deleteUsers(int id) {
        usersService.delete(id);
        return "admin/success";
    }








    /*处理添加用户*/
    @RequestMapping("doAddUsers_fdy.do")
    public String doAddUsers_fdy(HttpServletRequest request, ModelMap map) {
        /*通用方法*/
        commonController.commonMethod(map);
        return path+"users_add_fdy";
    }

    // 添加用户
    @RequestMapping("addUsers_fdy.do")
    public String addUsers_fdy(@RequestParam(value="file",required=false)MultipartFile file,String img,
                               HttpServletRequest request,Users users, HttpSession session){
        img=Info.fileUpload(file, request, img);
        users.setImg(img);
        users.setUtype("辅导员");
        users.setPubtime(new Timestamp(System.currentTimeMillis()).toString().substring(0,19));
        usersService.add(users);
        return "admin/success";
    }




    /*处理修改用户*/
    @RequestMapping("doUpdateUsers_fdy.do")
    public String doUpdateUsers_fdy(HttpServletRequest request, int id, ModelMap map) {
        map.put("users", usersService.getById(id));
        /*通用方法*/
        commonController.commonMethod(map);
        return path+"users_update_fdy";
    }

    /*查看用户*/
    @RequestMapping("doLookUsers_fdy.do")
    public String doLookUsers_fdy(HttpServletRequest request, int id, ModelMap map) {
        map.put("users", usersService.getById(id));
        /*通用方法*/
        commonController.commonMethod(map);
        return path+"users_look_fdy";
    }

    /*保存用户*/
    @RequestMapping("updateUsers_fdy.do")
    public String updateUsers_fdy(@RequestParam(value="file",required=false)MultipartFile file,String img,
                                  HttpServletRequest request,Users users) {
        img=Info.fileUpload(file, request, img);
        if(img!=null&&!img.equals("")){
            users.setImg(img);
        }
        usersService.update(users);
        return "admin/success";
    }


    // 分页查询用户信息的列表
    @RequestMapping("usersList_fdy.do")
    public String usersList_fdy(@RequestParam(value = "page", defaultValue = "0") Integer page, ModelMap map,
                                HttpSession session) {
        Map<String, Object> bMap = new HashMap<>();
        bMap.put("utype","辅导员");

        List<Users> list = usersService.getAll(bMap);
        map.put("list", list);
        /*通用方法*/
        commonController.commonMethod(map);
        return path+"users_list_fdy";
    }

    // 分页查询用户信息的列表--模糊查询
    @RequestMapping("usersListSearch_fdy.do")
    public String usersListSearch_fdy(@RequestParam(value = "page", defaultValue = "0") Integer page, ModelMap map,
                                      HttpSession session, Users users) {
        Map<String, Object> bMap = new HashMap<>();

        if (users.getName() != null && !users.getName().equals("")) {
            bMap.put("name",users.getName());
        }
        if (users.getUname() != null && !users.getUname().equals("")) {
            bMap.put("uname",users.getUname());
        }
        if (users.getAddress() != null && !users.getAddress().equals("")) {
            bMap.put("address",users.getAddress());
        }
        if (users.getUtype() != null && !users.getUtype().equals("")) {
            bMap.put("utype",users.getUtype());
        }
        if (users.getAge() != null && !users.getAge().equals("")) {
            bMap.put("age",users.getAge());
        }

        if (users.getEmail() != null && !users.getEmail().equals("")) {
            bMap.put("email",users.getEmail());
        }
        List<Users> list = usersService.getAll(bMap);
        map.put("list", list);
        /*通用方法*/
        commonController.commonMethod(map);
        return path+"users_list_fdy";
    }

    /*删除用户*/
    @RequestMapping("deleteUsers_fdy.do")
    public String deleteUsers_fdy(int id) {
        usersService.delete(id);
        return "redirect:usersList_fdy.do";
    }


    // 后台登录
    @RequestMapping("alogin.do")
    public void checkLogin(Users user, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        Map<String, Object> uMap = new HashMap<>();
        JSONObject obj = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        System.out.println("name===" + user.getUname());
        System.out.println("pwd===" + user.getPwd());
        System.out.println("utype===" + user.getUtype());
        uMap.put("uname", user.getUname());
        uMap.put("utype", user.getUtype());
        uMap.put("pwd", user.getPwd());
        //获取系统验证码
        String code = request.getSession().getAttribute("code").toString();
        if(user.getCode() == "" || !code.toLowerCase().equals(user.getCode().toLowerCase())){
            obj.put("res", "ng");
            obj.put("status", "2");
            obj.put("data", "验证码错误！");
        }else {
            user = usersService.login(uMap);
            if (user == null) {
                obj.put("res", "ng");
                obj.put("status", "2");
                obj.put("data", "用户名、密码或者角色不正确！");
            } else {
                session.setAttribute("auser", user);
                System.out.println("登录验证成功！");
                obj.put("res", "ok");
                obj.put("status", "0");
                obj.put("data", "登录验证成功！");
            }
        }
        jsonArray.add(obj);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            //out.print(obj);
            out.print(jsonArray);
            out.flush();
        } catch (
                IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }

    }

    //	验证用户名是否存在
    @RequestMapping("checkName.do")
    public void checkName(Users users, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uname", users.getUname());
        System.out.println("uname===" + users.getUname());
        System.out.println("uname222===" + usersService.checkName(map));
        JSONObject obj = new JSONObject();
        if (usersService.checkName(map) != null) {
            obj.put("info", "ng");
        } else {
            obj.put("info", "用户名可以用！");
        }
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(obj);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    // 后台注销登录
    @RequestMapping("loginOut.do")
    public String loginOut(HttpSession session) {
        session.removeAttribute("auser");
        return "admin/login";
    }
}

