package com.lightinit.hsdatashow.controller;

import com.lightinit.hsdatashow.common.MenuUtils;
import com.lightinit.hsdatashow.common.RoleModulesUtilsPro;
import com.lightinit.hsdatashow.entity.*;
import com.lightinit.hsdatashow.json.pojo.JsonResult;
import com.lightinit.hsdatashow.json.pojo.ListResult;
import com.lightinit.hsdatashow.service.IAdminService;
import com.lightinit.hsdatashow.service.IMenuService;
import com.lightinit.hsdatashow.service.IRoleService;
import com.lightinit.hsdatashow.service.IUserModuleService;
import com.google.code.kaptcha.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
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 javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Mr.Yao on 2017/4/11.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private RoleModulesUtilsPro roleModulesUtilsPro;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IUserModuleService userModuleService;

    @RequestMapping(value = "view/password.action")
    public String print_user_modify_password(){
        return "user/modifypwd";
    }

    @RequestMapping(value = "view/list.action")
    public String print_user_list(){
        return "user/userlist";
    }

    @ResponseBody
    @RequestMapping(value = "json/list.action",method = RequestMethod.GET)
    public ListResult<Admin> print_json_user_list(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int rows){
        ListResult<Admin> result=new ListResult<Admin>();
        result.setTotal(adminService.QueryCount(null,""));
        result.setRows(adminService.QueryList(null,"",page,rows));
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "json/save.action",method = RequestMethod.POST)
    public JsonResult print_json_user_add(@RequestParam(defaultValue = "0") long id, @RequestParam String username, @RequestParam String fullname, @RequestParam String password, @RequestParam(defaultValue = "0") int lock){
        JsonResult jsonResult=new JsonResult();
        if(StringUtils.isEmpty(username)){
            jsonResult.setStatus(0);
            jsonResult.setMessage("用户名称不能为空");
        }else if(StringUtils.isEmpty(fullname)){
            jsonResult.setStatus(0);
            jsonResult.setMessage("用户全称不能为空");
        }else if(StringUtils.isEmpty(password)){
            jsonResult.setStatus(0);
            jsonResult.setMessage("账户密码不能为空");
        }else if(lock<0){
            jsonResult.setStatus(0);
            jsonResult.setMessage("账户状态不能为空");
        }else {
            boolean success=false;
            String salt ="";
            String password_cipherText="";
            Admin admin=adminService.QueryOne(id);
            if(id <= 0  || admin==null){
                if(adminService.IsExits(username)){
                    jsonResult.setStatus(0);
                    jsonResult.setMessage("账户已经存在");
                    return jsonResult;
                }else {
                    admin = new Admin();
                    salt = new SecureRandomNumberGenerator().nextBytes().toHex();
                    password_cipherText = new Md5Hash(password, username + salt, 3).toHex();
                    admin.setUsername(username);
                    admin.setAccountlock(lock);
                    admin.setPassword(password_cipherText);
                    admin.setSalt(salt);
                    admin.setShowname(fullname);
                    admin.setCreatedAt(new Date());
                    success = adminService.AddAdmin(admin);
                }
            }else if(admin.getUsername().equalsIgnoreCase(username)==false){
                jsonResult.setStatus(0);
                jsonResult.setMessage("用户信息错误");
                return jsonResult;
            }else{
                salt = admin.getSalt();
                password_cipherText= new Md5Hash(password,username+salt,3).toHex();
                admin.setAccountlock(lock);
                if(admin.getPassword().equalsIgnoreCase(password)==false && admin.getPassword().equalsIgnoreCase(password_cipherText)==false){
                    admin.setPassword(password_cipherText);
                }
                admin.setShowname(fullname);
                success =adminService.UpdateAdmin(admin);
            }
            jsonResult.setStatus(success?1:0);
            jsonResult.setMessage(success?"账户添加成功":"账户添加失败");
        }
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping(value = "json/role/grant.action",method = RequestMethod.POST)
    public JsonResult print_Grant_User_Role(@RequestParam(defaultValue = "0") long uid,@RequestParam(defaultValue = "") String ids){
        JsonResult jsonResult=new JsonResult();
        if(uid>0) {
            String[]list=ids.split(";");
            List<Long> idList=new ArrayList<Long>();
            for (String id:list) {
                if (StringUtils.isEmpty(id)==false){
                    idList.add(Long.valueOf(id));
                }
            }
            roleService.SaveUserRoles(uid,idList);
            jsonResult.setStatus(1);
            jsonResult.setMessage("授权成功");
        }else{
            jsonResult.setStatus(-1);
            jsonResult.setMessage("参数错误");
        }
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping(value = "json/lock.action",method = RequestMethod.POST)
    public JsonResult print_json_user_lock(@RequestParam(defaultValue = "0") long id,@RequestParam(defaultValue = "0") int lock){
        JsonResult jsonResult=new JsonResult();
        String errorMsg="";
        String successMsg="";
        if(id<=0){
            jsonResult.setStatus(0);
            jsonResult.setMessage("参数错误");
        }else {
            boolean success=false;
            Admin admin=adminService.QueryOne(id);
            if(id <= 0  || admin==null){
                jsonResult.setStatus(0);
                jsonResult.setMessage("账户已经存在");
                return jsonResult;
            }else{
                if(lock==0){
                    errorMsg="账户【"+admin.getShowname()+"】解除锁定失败";
                    successMsg="账户【"+admin.getShowname()+"】已解除锁定";
                }else if(lock==1){
                    errorMsg="账户【"+admin.getShowname()+"】锁定失败";
                    successMsg="账户【"+admin.getShowname()+"】已锁定";
                }else{
                    jsonResult.setStatus(0);
                    jsonResult.setMessage("参数错误");
                    return jsonResult;
                }
                admin.setAccountlock(lock);
                success =adminService.UpdateAdmin(admin);
            }
            jsonResult.setStatus(success?1:0);
            jsonResult.setMessage(success?successMsg:errorMsg);
        }
        return jsonResult;
    }
    @ResponseBody
    @RequestMapping(value = "json/user/delete.action",method = RequestMethod.POST)
    public JsonResult print_delete_user(@RequestParam(defaultValue = "0") long uid){
        JsonResult jsonResult=new JsonResult();
        if (uid > 1) {
            Admin item = adminService.QueryOne(uid);
            if(item==null){
                jsonResult.setStatus(0);
                jsonResult.setMessage("当前用户已不存在");
            }else if(roleService.CheckUserHasRole(uid)){
                jsonResult.setStatus(0);
                jsonResult.setMessage("用户【"+item.getShowname()+"】已经分配角色，请先取消！");
            }else if(userModuleService.CheckUserHasModules(uid)){
                jsonResult.setStatus(0);
                jsonResult.setMessage("用户【"+item.getShowname()+"】已经分配模块，请先取消！");
            }else {
              if(adminService.Delete(uid)){
                  jsonResult.setStatus(1);
                  jsonResult.setMessage("用户【"+item.getShowname()+"】删除成功");
              }else{
                  jsonResult.setStatus(0);
                  jsonResult.setMessage("用户【"+item.getShowname()+"】删除失败");
              }
            }
        } else {
            jsonResult.setStatus(-1);
            jsonResult.setMessage("参数错误");
        }
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping(value = "json/role/list.action",method = RequestMethod.POST)
    public List<AdminRole> print_user_roles_list(@RequestParam(defaultValue = "0") long uid){
        List<AdminRole> result=new ArrayList<AdminRole>();
        if (uid > 0) {
            result = roleService.QueryRoleList(uid);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "json/module/list.action",method = RequestMethod.POST)
    public List<RoleModule> print_user_module_list(@RequestParam(defaultValue = "0") long uid){
        List<RoleModule> result= roleModulesUtilsPro.UserHasModules(uid);
        return result;
    }
    @ResponseBody
    @RequestMapping(value = "json/menu/list.action",method = RequestMethod.GET)
    public List<MenuDataEntity> print_Json_Menu_Role(@RequestParam(defaultValue = "0") long uid){
        List<MenuDataEntity> resultList=new ArrayList<MenuDataEntity>();
        List<MenuDataEntity> list=new ArrayList<MenuDataEntity>();
        list.addAll(MenuUtils.InitSystemTopMenu());
        List<Menu> menuList= menuService.QueryList(1,1000,null);
        for (Menu item:menuList) {
            MenuDataEntity _item= MenuUtils.MenuConverter(item,new ArrayList<RoleModule>(),true);
            if(_item!=null)
                list.add(_item);
        }
        list.addAll(MenuUtils.InitSystemBottomMenu());
        if(uid>0){
            List<AdminRole> adminRoleList= roleService.QueryRoleList(uid);
            List<Long> roleIds=new ArrayList<Long>();
            for (AdminRole mRrole:adminRoleList) {
                roleIds.add(mRrole.getId());
            }
            List<SentryRole> sentryRole= roleService.QueryManyRole(roleIds);
            List<Long> roleModules=new ArrayList<Long>();
            for (SentryRole mSentryRole:sentryRole) {
               List<Long> _tmpList=roleModulesUtilsPro.RoleHasModules(mSentryRole.getId());
                for (Long i:_tmpList) {
                    if(roleModules.contains(i)==false)
                        roleModules.add(i);
                }
            }
            resultList = MenuUtils.UserRolePermission(list, roleModules);
        }else{
            resultList.clear();
        }
        return resultList;
    }

    @ResponseBody
    @RequestMapping(value = "json/module/grant.action",method = RequestMethod.POST)
    public JsonResult print_Grant_User_Module(@RequestParam(defaultValue = "0") long uid,@RequestParam(defaultValue = "") String ids){
        JsonResult jsonResult=new JsonResult();
        if(uid>0) {
            String[]list=ids.split(";");
            List<Long> idList=new ArrayList<Long>();
            for (String id:list) {
                if (StringUtils.isEmpty(id)==false){
                    idList.add(Long.valueOf(id));
                }
            }
            userModuleService.SaveUserModule(uid,idList);
            jsonResult.setStatus(1);
            jsonResult.setMessage("授权成功");
        }else{
            jsonResult.setStatus(-1);
            jsonResult.setMessage("参数错误");
        }
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping(value = "json/password/modify.action",method = RequestMethod.POST)
    public JsonResult print_json_user_password_modify(HttpSession session, @RequestParam(defaultValue = "") String id, @RequestParam(defaultValue = "") String password, @RequestParam(defaultValue = "") String newpsw, @RequestParam(defaultValue = "") String captcha){
        JsonResult jsonResult=new JsonResult();
        String capText=session.getAttribute(Constants.KAPTCHA_SESSION_KEY)!=null?session.getAttribute(Constants.KAPTCHA_SESSION_KEY).toString():"";
        if(StringUtils.isEmpty(capText) || StringUtils.isEmpty(captcha)){
            jsonResult.setStatus(0);
            jsonResult.setMessage("验证码错误");
        }else if (capText.equalsIgnoreCase(captcha)==false){
            jsonResult.setStatus(0);
            jsonResult.setMessage("验证码错误");
        }else {
            if (StringUtils.isEmpty(id)) {
                jsonResult.setStatus(0);
                jsonResult.setMessage("用户不存在");
            } else if (StringUtils.isEmpty(password)) {
                jsonResult.setStatus(0);
                jsonResult.setMessage("原始密码不能为空");
            } else if (StringUtils.isEmpty(newpsw)) {
                jsonResult.setStatus(0);
                jsonResult.setMessage("新密码不能为空");
            } else if (newpsw.equalsIgnoreCase(password)) {
                jsonResult.setStatus(0);
                jsonResult.setMessage("新密码不能与原始密码一样");
            } else {
                boolean success = false;
                String salt = "";
                Admin admin = adminService.SelectOne(id);
                if (admin == null) {
                    jsonResult.setStatus(0);
                    jsonResult.setMessage("账户不存在");
                    return jsonResult;
                } else {
                    salt = admin.getSalt();
                    String password_cipherText = new Md5Hash(password, admin.getUsername() + salt, 3).toHex();
                    if (admin.getPassword().equalsIgnoreCase(password_cipherText) == false) {
                        jsonResult.setStatus(0);
                        jsonResult.setMessage("原始密码错误");
                        return jsonResult;
                    }
                    String password_cipherText_new = new Md5Hash(newpsw, admin.getUsername() + salt, 3).toHex();
                    admin.setPassword(password_cipherText_new);
                    success = adminService.UpdateAdmin(admin);
                    if(success){
                        Subject currentUser = SecurityUtils.getSubject();
                        try {
                            currentUser.logout();
                        } catch (Exception e) {

                        }
                    }
                }
                jsonResult.setStatus(success ? 1 : 0);
                jsonResult.setMessage(success ? "密码修改成功,请重新登录" : "密码修改失败");
            }
        }
        return jsonResult;
    }
}
