package com.ruoyi.web.controller.monitor;

import com.ruoyi.common.config.RuoyiConfig;
import com.ruoyi.common.constant.ShiroConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.platform.PlatformTenant;
import com.ruoyi.common.core.domain.platform.dto.PlatformUserDTO;
import com.ruoyi.common.core.domain.platform.vo.PlatformMenuVO;
import com.ruoyi.common.core.domain.platform.vo.PlatformUserVO;
import com.ruoyi.common.core.domain.platform.vo.SysMenuVO;
import com.ruoyi.common.core.domain.saas.dto.SysUserDTO;
import com.ruoyi.common.core.domain.saas.vo.SysUserVO;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.bean.DozerUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.platform.service.IPlatformMenuService;
import com.ruoyi.platform.service.IPlatformTenantService;
import com.ruoyi.platform.service.ISysConfigService;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.utils.ShiroUtils.getSubject;

/**
 *@Description 首页 业务处理
 *@Author zhushuyong
 *@Date 2021/5/26 14:55
 *@since:
 *@copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 *            GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Controller
public class SysIndexController extends BaseController
{
    @Autowired
    private ISysMenuService saaSMenuService;

    @Autowired
    private IPlatformMenuService platformMenuService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IPlatformTenantService platformTenantService;

    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap)
    {
        Object obj = getSubject().getPrincipal();
        if (obj instanceof SysUserVO) {
            // 取身份信息
            SysUserVO user = ShiroUtils.getSysUser();
            // 根据用户id取出菜单
            List<SysMenuVO> menus = saaSMenuService.selectMenusByUser(DozerUtils.copyProperties(user, SysUserDTO.class));
            PlatformTenant platformTenant = platformTenantService.getById(user.getTenantId());
            mmap.put("menus", menus);
            mmap.put("user", user);
            mmap.put("tenant", platformTenant);
            mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
            mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        } else if (obj instanceof PlatformUserVO) {
            // 取身份信息
            PlatformUserVO user = ShiroUtils.getPlatformUser();
            // 根据用户id取出菜单
            List<PlatformMenuVO> menus = platformMenuService.selectMenusByUser(DozerUtils.copyProperties(user, PlatformUserDTO.class));
            mmap.put("menus", menus);
            mmap.put("user", user);
            mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
            mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        }
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        mmap.put("ignoreFooter", configService.selectConfigByKey("sys.index.ignoreFooter"));
        mmap.put("copyrightYear", RuoyiConfig.getCopyrightYear());
        mmap.put("demoEnabled", RuoyiConfig.isDemoEnabled());


        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies)
        {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName()))
            {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        if (obj instanceof PlatformUserVO) {
            webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "platform/index-topnav" : "platform/index";
        }
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap)
    {
        mmap.put("user", ShiroUtils.getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password)
    {
        SysUserVO user = ShiroUtils.getSysUser();
        if (StringUtils.isNull(user))
        {
            return AjaxResult.error("服务器超时，请重新登陆");
        }
        if (passwordService.matches(user, password))
        {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin()
    {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response)
    {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap)
    {
        mmap.put("version", RuoyiConfig.getVersion());
        return "main";
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
