package cn.estsh.i3plus.core.apiservice.controller.base;

import cn.estsh.i3plus.core.apiservice.serviceimpl.busi.SysLocaleLanguageService;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SessionUser;
import cn.estsh.i3plus.pojo.platform.bean.SysLocaleLanguage;
import cn.estsh.i3plus.pojo.platform.bean.SysMenu;
import cn.estsh.i3plus.pojo.platform.bean.SysUser;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.jasper.tagplugins.jstl.core.If;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Description : 用户权限服务
 * @Reference :
 * @Author : wei.peng
 * @Date : 2018-10-25 21:01
 * @Modify :
 **/
@RestController
@Api(description="用户所有权限操作服务")
@RequestMapping(PlatformConstWords.BASE_URL + "/auth")
public class AuthController extends CoreBaseController {

    public static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private SysLocaleLanguageService localeLanguageService;

    /**
     *
     * @return
     */
    @GetMapping(value="/get-user-info")
    @ApiOperation(value="获取登录用户信息",notes="获取当前登录用户详细信息")
    public ResultBean getUserInfo(){
        LOGGER.info("获取用户信息...lang:{}",AuthUtil.getSessionAttribute("languageCode"));
        try {
            SessionUser sUser = AuthUtil.getSessionUser();
            LOGGER.info("用户：{}",sUser);
            return new ResultBean(true,"",sUser.getUserInfo());
        } catch (ImppBusiException e) {
            return new ResultBean(false,e.getErrorDetail() + "-[解决]" + e.getErrorSolution());
        }
    }

    /**
     *
     * @return
     */
    @GetMapping(value="/get-user")
    @ApiOperation(value="获取登录用户信息",notes="获取当前登录用户账号详细信息")
    public ResultBean getUser(){
        LOGGER.info("获取用户信息...lang:{}",AuthUtil.getSessionAttribute("languageCode"));
        try {
            SessionUser sUser = AuthUtil.getSessionUser();
            LOGGER.info("用户：{}",sUser);
            return new ResultBean(true,"",sUser.getUser());
        } catch (ImppBusiException e) {
            return new ResultBean(false,e.getErrorDetail() + "-[解决]" + e.getErrorSolution());
        }
    }

    @GetMapping(value="/menu/find-home-list")
    @ApiOperation(value="获取登录用户功能权限信息",notes="获取首页权限信息")
    public ResultBean findHomeList(){
        List<SysMenu> list = new ArrayList<>();
        SysUser user = getSessionUser().getUser();

        if(user != null){
            List<SysMenu> menus = user.getMenuList();
            if(menus != null){
                for (SysMenu menu : menus) {
                    if(menu != null){
                        if(menu.getMenuType().equals(CommonEnumUtil.METHOD_LEVEL.PLUGIN.getValue())
                                && menu.getParentId().longValue() != -1){
                            list.add(menu);
                        }
                    }
                }
            }
        }

        if(list != null && list.size() > 0){
            // 内存排序  Sort 降序 code 升序
            list.sort(Comparator.comparing(SysMenu::getMenuSort).reversed().thenComparing(SysMenu::getMenuCode));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(list);
        }else {
            return ResultBean.fail("操作失败").setCode(ResourceEnumUtil.MESSAGE.FAIL.getCode()).setErrorMsg("菜单信息不存在");
        }

    }

    @GetMapping(value="/menu/find-module-list/{parentId}")
    @ApiOperation(value="获取登录用户功能权限信息",notes="获取首页权限信息")
    public ResultBean findModuleList(@PathVariable("parentId") String parentId){
        List<SysMenu> list = new ArrayList<>();
        SysUser user = getSessionUser().getUser();

        if(user != null){
            List<SysMenu> menus = user.getMenuList();
            if(menus != null){
                // 封装模块信息
                for (SysMenu menu : menus) {
                    if(menu != null && menu.getMenuType().equals(CommonEnumUtil.METHOD_LEVEL.MODULE.getValue())
                            && parentId.equals(menu.getParentId().toString())){

                        // 封装 功能信息
                        for (SysMenu sysMenu : menus) {
                            if (sysMenu != null && sysMenu.getMenuType().equals(CommonEnumUtil.METHOD_LEVEL.METHOD.getValue())
                                    && menu.getId().longValue() == sysMenu.getParentId().longValue()){
                                if(!menu.getChildList().contains(sysMenu)){
                                    menu.getChildList().add(sysMenu);
                                }
                            }
                        }

                        menu.getChildList().sort(Comparator.comparing(SysMenu::getMenuSort).reversed().thenComparing(SysMenu::getMenuCode));
                        list.add(menu);
                    }
                }
            }
        }

        if(list != null && list.size() > 0){
            // 内存排序  Sort 降序 code 升序
            list.sort(Comparator.comparing(SysMenu::getMenuSort).reversed().thenComparing(SysMenu::getMenuCode));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(list);
        }else {
            return ResultBean.fail("操作失败").setCode(ResourceEnumUtil.MESSAGE.FAIL.getCode()).setErrorMsg("菜单信息不存在");
        }

    }

    @PutMapping(value = "/update-language")
    @ApiOperation(value="修改语言",notes="修改用户会话语言")
    public ResultBean updateLanguage(String code){
        try {
            SysLocaleLanguage language = localeLanguageService.getSysLocaleLanguageByCode(code);
            if(language != null){
                AuthUtil.setSessionLanguage(language.getLanguageCode());
                return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else {
                return ResultBean.fail("操作失败").setCode(ResourceEnumUtil.MESSAGE.FAIL.getCode()).setErrorMsg("语言信息不存在");
            }
        }catch(ImppBusiException busExcep){
            LOGGER.error(busExcep.getErrorMsg() + "：{}",busExcep.getErrorDetail(),busExcep);
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            LOGGER.error(ImppExceptionEnum.SYSTEM_EXCEPTION.getDescription() + "：{}",e.getMessage(),e);
            return ResultBean.fail().setCode(ImppExceptionEnum.SYSTEM_EXCEPTION.getCode());
        }
    }



//    /**
//     * 根据递归获取所有父节点 ID 获取所有 菜单
//     * @param list
//     * @param parentId
//     * @return
//     */
//    private List<SysMenu> findSysMenuChildList(List<SysMenu> list,Long parentId){
//        List<SysMenu> result = new ArrayList<>();
//        if(list != null && list.size() > 0){
//            for (SysMenu menu : list) {
//                if(menu.getParentId().equals(parentId)){
//                    result.add(menu);
//                }
//
//                List<SysMenu> childList = findSysMenuChildList(menu.getChildList(), parentId);
//                result.addAll( childList);
//            }
//        }
//        return result;
//    }

}
