package com.dgtly.web.controller.system;


import java.util.*;


import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.system.domain.*;
import com.dgtly.system.service.ISysModelLayoutService;
import com.dgtly.system.service.ISysThemeInfoService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.dgtly.common.config.Global;
import com.dgtly.common.core.controller.BaseController;
import com.dgtly.framework.util.ShiroUtils;
import com.dgtly.system.service.ISysMenuService;


/**
 * 首页 业务处理
 * 
 * @author ruoyi
 */
@Controller
public class SysIndexController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysModelLayoutService modelLayoutService;
    @Autowired
    private ISysThemeInfoService themeInfoServiceService;


    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap)
    {
        // 取身份信息
        SysUser user = ShiroUtils.getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("copyrightYear", Global.getCopyrightYear());
        mmap.put("demoEnabled", Global.isDemoEnabled());
        return "index";
    }

    // 访客页面
    @RequiresPermissions("youtu:visitor:view")
    @GetMapping("/visitor")
    public String visitor()
    {
        return "visitor/youtuVisitorList";
    }



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

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

    /*========================oneportal门户改造=================================*/

    //门户访问
    @GetMapping("/homeIndex")
    public String homeIndex(ModelMap mmap)  {
        try{
            // 取身份信息
            SysUser user = ShiroUtils.getSysUser();
            if(user==null){
                return "redirect:/login";
            }
            mmap.put("user", user);
            return "homeIndex";
        } catch (Exception e){
            logger.error("跳转门户出错！",e);
            e.printStackTrace();
            return "error/500";
        }
    }

    // 系统首页
    @GetMapping("/appIndex")
    public String appIndex(ModelMap mmap,String menuId)
    {
        // 取身份信息
        SysUser user = ShiroUtils.getSysUser();
        // 根据用户id以及menu取出菜单
        List<SysMenu> menus = menuService.selectMenusByUserMenu(user,Integer.parseInt(menuId));
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("copyrightYear", Global.getCopyrightYear());
        return "appIndex";
    }




    /**
     * 查询磁贴和背景图片背景颜色
     * @return
     */
    @PostMapping("/homeIndex/getThemeAndLayout")
    @ResponseBody
    public Object getThemeAndLayout()  {
        Map<String,Object> resultMap=new HashMap<>();
        try{
            // 取身份信息
            SysUser user = ShiroUtils.getSysUser();
            if(user==null){
                return error("用户未登录");
            }
            resultMap.put("magnets",getModel(user));
            SysThemeInfo sti = themeInfoServiceService.selectSysThemeInfoByUserId(user.getUserId());
            resultMap.put("themeInfo",sti);
            return AjaxResult.success(resultMap);
        } catch (Exception e){
            logger.error("跳转门户出错！",e);
            e.printStackTrace();
            return error();
        }
    }

    /**
     * 保存背景图片背景颜色
     * @return
     */
    @PostMapping("/homeIndex/saveThemeInfo")
    @ResponseBody
    public Object saveThemeInfo(SysThemeInfo sysThemeInfo)  {
        try{
            // 取身份信息
            SysUser user = ShiroUtils.getSysUser();
            if(user==null){
                return error("用户未登录");
            }
            //判断是否有sysThemInfo 有就更新 没有就新增
            SysThemeInfo sti = themeInfoServiceService
                    .selectSysThemeInfoByUserId(user.getUserId());

            if(sti==null){
                sysThemeInfo.setUserId(ShiroUtils.getUserId().toString());
                return themeInfoServiceService.insertSysThemeInfo(sysThemeInfo)==1?success():error();
            }else{
                return themeInfoServiceService.updateSysThemeInfo(sysThemeInfo)==1?success():error();
            }
        } catch (Exception e){
            logger.error("跳转门户出错！",e);
            e.printStackTrace();
            return error();
        }
    }


    /**
     * 保存磁贴布局信息
     * @param sysModelLayout
     * @return
     */
    @PostMapping("/homeIndex/saveModelLayout")
    @ResponseBody
    public Object saveModelLayout(SysModelLayout sysModelLayout){
        // 取身份信息
        SysUser user = ShiroUtils.getSysUser();
        if(user==null){
            return error("未登录");
        }
        SysModelLayout sml = modelLayoutService.
                selectSMLByUserIdMenuId(user.getUserId(),sysModelLayout.getMenuId());
        int i = 0;
        if(sml!=null){
             i= modelLayoutService.updateSysModelLayout(sysModelLayout);
        }else{
            sysModelLayout.setUserId(user.getUserId());
            i = modelLayoutService.insertSysModelLayout(sysModelLayout);

        }
        if(i>0){
            return success();
        }else{
            return error("保存磁贴信息失败");
        }
    }


    public List<Map<String,Object>> getModel(SysUser user) throws Exception {
        List<Map<String,Object>> rs = new ArrayList<>();
        //根据用户取出 菜单类型为应用的应用
        List<SysMenu> menusApps = menuService.selectMenusAsApp(user);

        //根据用户取出磁贴布局信息
        List<Map<String,Object>> models=modelLayoutService.selectModelMenu(user.getUserId());

        List<String> removeSysModelIds =new ArrayList<>();
        //便利所有menuMap为A的 菜单。
        for(int n = 0;n<menusApps.size();n++){
            Map<String,Object>  map = new HashMap<>();
            SysMenu sysMenu = menusApps.get(n);
            map.put("icon",sysMenu.getIcon());
            map.put("menuName",sysMenu.getMenuName());
            map.put("appType",sysMenu.getAppType());
            map.put("target",sysMenu.getTarget());
            map.put("isrefresh",sysMenu.getIsrefresh());
            map.put("url",sysMenu.getUrl());
            map.put("menuId",sysMenu.getMenuId());
            for(int m = 0;m<models.size();m++){
                //如果查询出的磁贴中包含应用的menuid
                if(models.get(m).get("menuId").toString().equals(menusApps.get(n).getMenuId().toString())){
                    //将磁贴的相关信息放入
                    map.putAll(models.get(m));
                    models.remove(m);
                    break;
                }
            }

            rs.add(map);
        }
        for (Map map :models) {
            removeSysModelIds.add(map.get("menuId").toString());
        }
        //删除多余的磁贴信息;
        if(removeSysModelIds.size()>0){
            modelLayoutService.deleteSMLArray(removeSysModelIds,user.getUserId());
        }
        return rs;
    }




}
