package com.bohuikeji.frame.module.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.frame.module.admin.annotation.InitLog;
import com.bohuikeji.frame.module.admin.base.ControllerBase;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.back.PageEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysLog;
import com.bohuikeji.frame.module.admin.entity.sys.SysMenu;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.service.ISysMenuService;
import com.bohuikeji.frame.module.admin.service.ISysUserService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 登陆，登出等处理
 * @author 10552
 */
@RestController
@RequestMapping("/login")
@Slf4j
public class FrameLoginController extends ControllerBase {
    @Autowired
    ISysUserService userService;
    @Autowired
    ISysMenuService menuService;

    /**
     * 登陆
     * @return
     */
    @InitLog(value = "系统框架——用户登陆",action = "登陆")
    @GetMapping("/login")
    public APIEntity login(HttpServletRequest request,String username, String password,String captcha){
        SysLog sysLog=getLog(request);
        sysLog.setLogModel("用户登陆");
        sysLog.setLogType("登录日志");
        sysLog.setLogMenu("用户登陆");
        if (!CaptchaUtil.ver(captcha, request)) {
            CaptchaUtil.clear(request);
            sysLog.setLogDetail("用户登陆失败，验证码不正确");
            return APIEntity.fail("验证码不正确！");
        }
        SysUser user=userService.getOne(new QueryWrapper<SysUser>().eq("user_phone",username).eq("user_pwd",password));
        if (user==null){
            CaptchaUtil.clear(request);
            sysLog.setLogDetail("用户登陆失败，账号或密码错误");
            return APIEntity.fail("账号或密码错误");
        }

        if (!"正常".equals(user.getUserStatus())){
            sysLog.setLogUser(user.getUserId());
            return APIEntity.fail("您的账号状态异常，请联系管理员。");
        }
        List<SysMenu> menuList;
        //超级管理员默认获取所以菜单
        if (user.getRoleId()==1){
            menuList=menuService.list(new QueryWrapper<SysMenu>().eq("levle",1).eq("display",1).eq("share",0).orderByAsc("sort"));
        }
        else{
            menuList=menuService.list(new QueryWrapper<SysMenu>()
                    .apply("id in(select menu_id from sys_menu_role where role_id ={0}) and display=1 and levle=1 order by sort asc",user.getRoleId()));
        }
        if(menuList.size()<1){
            sysLog.setLogUser(user.getUserId());
            return APIEntity.fail("您好，该账号没有已授权的操作菜单，请联系管理员完成授权后再次登录。");
        }
        SysMenu indexMenu=null;
        for(int i=0;i<menuList.size();i++){
            SysMenu menu=menuList.get(i);
            if(menu.getIsIndex()){
                indexMenu=menu;
            }
            List<SysMenu> sonMenus =menuService.list(new QueryWrapper<SysMenu>().eq("super_id",menu.getId())
                    .eq("display",true).apply(" id in(select menu_id from sys_menu_role where role_id ={0}) order by sort",user.getRoleId()));
            if (sonMenus.size()<1){
                sonMenus=menuService.list(new QueryWrapper<SysMenu>()
                        .eq("super_id",menu.getId())
                        .eq("display",true)
                        .orderByAsc("sort"));
            }
            for(SysMenu son:sonMenus){
                if(son.getIsIndex()){
                    indexMenu=son;
                }
            }
            menu.setSonMenu(sonMenus);
            menuList.set(i,menu);
        }
        if (indexMenu==null){
            log.error("【登陆失败】用户认证成功，但当前菜单表中未设置首页菜单。");
            sysLog.setLogUser(user.getUserId());
            return APIEntity.fail("错误，用户认证成功，但未找到系统首页，请为该账号设置首页菜单。");
        }
        //session有效期8小时
        session.setMaxInactiveInterval(60*60*60*8);
        session.setAttribute("loginUser",user);
        session.setAttribute("menuList",menuList);
        session.setAttribute("activeMenu",indexMenu);
        sysLog.setLogUser(user.getUserId());
        sysLog.setLogDetail("登陆成功");
        return APIEntity.success(indexMenu.getUrl());
    }

    /**
     * 登出
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public PageEntity logout(HttpSession session){
        session.setAttribute("loginUser",null);
        return PageEntity.redirect("views/login");
    }

    /**
     * 修改密码提交
     * @param userId
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @PostMapping("/update/password")
    public APIEntity changePwd(Integer userId,String oldPwd,String newPwd){
        SysUser user=userService.getOne(new QueryWrapper<SysUser>().eq("user_id",userId).eq("user_pwd",oldPwd));
        if (user!=null){
            if (userService.update(new UpdateWrapper<SysUser>().set("user_pwd",newPwd).eq("user_id",userId))){
                return  APIEntity.success();
            }
            return  APIEntity.fail("修改失败，系统服务异常！");
        }
        return  APIEntity.fail("修改失败，旧密码错误！");
    }

    /**
     * 获取验证码
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.setLen(2);  // 几位数运算，默认是两位
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        captcha.text();  // 获取运算的结果：5
        CaptchaUtil.out(captcha,request, response);
    }



}
