package com.hzs.system.sys.controller.manage;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.system.sys.SysMenu;
import com.hzs.common.domain.system.sys.SysRole;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.system.sys.param.SysUserMenuParam;
import com.hzs.system.sys.param.SysUserMenuQueryParam;
import com.hzs.system.sys.service.ISysMenuService;
import com.hzs.system.sys.service.ISysRoleService;
import com.hzs.system.sys.service.ISysUserMenuService;
import com.hzs.system.sys.vo.SysUserMenuDetailVO;
import com.hzs.system.sys.vo.SysUserMenuQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 用户菜单配置控制器
 * @Author: jiang chao
 * @Time: 2023/1/6 14:45
 * @Classname: SysUserMenuController
 * @PackageName: com.hzs.system.sys.controller.manage
 */
@RestController
@RequestMapping("/manage/user-menu")
public class SysUserMenuController extends BaseController {

    @Autowired
    private ISysUserMenuService iSysUserMenuService;
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysMenuService iSysMenuService;

    /**
     * 查询
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.AUTHORITY_CONFIG, business = EOperationBusiness.MENU_AUTHORITY_AFTER, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(SysUserMenuQueryParam param) {
        DateUtils.handTimeStartAndEnd(param.getCreationTime());
        startPage();
        List<SysUserMenuQueryVO> list = iSysUserMenuService.queryList(param);

        if (CollectionUtil.isNotEmpty(list)) {
            // 获取全部角色
            Map<Long, SysRole> roleMap = iSysRoleService.getAllRoleMap();
            // 获取全部菜单
            Map<Long, SysMenu> menuMap = iSysMenuService.getAllMenuMap();

            for (SysUserMenuQueryVO sysUserMenuQueryVO : list) {
                if (StringUtils.isNotEmpty(sysUserMenuQueryVO.getRoleIds())) {
                    // 处理角色
                    StringBuilder roleIdVal = new StringBuilder();
                    for (String roleId : sysUserMenuQueryVO.getRoleIds().split(",")) {
                        SysRole sysRole = roleMap.get(Long.parseLong(roleId));
                        if (null != sysRole) {
                            roleIdVal.append(sysRole.getRoleName()).append("/");
                        }
                    }
                    if (roleIdVal.length() > 0) {
                        sysUserMenuQueryVO.setRoleIdVal(roleIdVal.substring(0, roleIdVal.length() - 1));
                    } else {
                        sysUserMenuQueryVO.setRoleIdVal(roleIdVal.toString());
                    }
                }
                if (StringUtils.isNotEmpty(sysUserMenuQueryVO.getMenuIds())) {
                    // 处理菜单
                    StringBuilder menuIdVal = new StringBuilder();
                    for (String menuId : sysUserMenuQueryVO.getMenuIds().split(",")) {
                        SysMenu sysMenu = menuMap.get(Long.parseLong(menuId));
                        if (null != sysMenu) {
                            menuIdVal.append(sysMenu.getMenuName()).append("/");
                        }
                    }
                    if (menuIdVal.length() > 0) {
                        sysUserMenuQueryVO.setMenuIdVal(menuIdVal.substring(0, menuIdVal.length() - 1));
                    } else {
                        sysUserMenuQueryVO.setMenuIdVal(menuIdVal.toString());
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出
     *
     * @param response
     * @param param
     */
    @Log(module = EOperationModule.AUTHORITY_CONFIG, business = EOperationBusiness.MENU_AUTHORITY_AFTER, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserMenuQueryParam param) {
        DateUtils.handTimeStartAndEnd(param.getCreationTime());
        List<SysUserMenuQueryVO> list = iSysUserMenuService.queryList(param);

        if (CollectionUtil.isNotEmpty(list)) {
            // 获取全部角色
            Map<Long, SysRole> roleMap = iSysRoleService.getAllRoleMap();
            // 获取全部菜单
            Map<Long, SysMenu> menuMap = iSysMenuService.getAllMenuMap();

            for (SysUserMenuQueryVO sysUserMenuQueryVO : list) {
                if (StringUtils.isNotEmpty(sysUserMenuQueryVO.getRoleIds())) {
                    // 处理角色
                    StringBuilder roleIdVal = new StringBuilder();
                    for (String roleId : sysUserMenuQueryVO.getRoleIds().split(",")) {
                        SysRole sysRole = roleMap.get(Long.parseLong(roleId));
                        if (null != sysRole) {
                            roleIdVal.append(sysRole.getRoleName()).append("/");
                        }
                    }
                    if (roleIdVal.length() > 0) {
                        sysUserMenuQueryVO.setRoleIdVal(roleIdVal.substring(0, roleIdVal.length() - 1));
                    } else {
                        sysUserMenuQueryVO.setRoleIdVal(roleIdVal.toString());
                    }
                }
                if (StringUtils.isNotEmpty(sysUserMenuQueryVO.getMenuIds())) {
                    // 处理菜单
                    StringBuilder menuIdVal = new StringBuilder();
                    for (String menuId : sysUserMenuQueryVO.getMenuIds().split(",")) {
                        SysMenu sysMenu = menuMap.get(Long.parseLong(menuId));
                        if (null != sysMenu) {
                            menuIdVal.append(sysMenu.getMenuName()).append("/");
                        }
                    }
                    if (menuIdVal.length() > 0) {
                        sysUserMenuQueryVO.setMenuIdVal(menuIdVal.substring(0, menuIdVal.length() - 1));
                    } else {
                        sysUserMenuQueryVO.setMenuIdVal(menuIdVal.toString());
                    }
                }
            }
        }

        ExcelUtil<SysUserMenuQueryVO> util = new ExcelUtil<>(SysUserMenuQueryVO.class);
        util.exportExcel(response, list, "后台菜单权限导出");
    }

    /**
     * 获取详情
     */
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable Long userId) {
        SysUserMenuDetailVO sysUserMenuDetailVO = iSysUserMenuService.queryDetail(userId);
        if (null == sysUserMenuDetailVO) {
            // 数据不存在
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.HO_OBJECT_NOT_REPEAT));
        }
        if (StringUtils.isNotEmpty(sysUserMenuDetailVO.getRoleIds())) {
            // 处理角色
            List<Long> roleIdList = new ArrayList<>();
            for (String roleId : sysUserMenuDetailVO.getRoleIds().split(",")) {
                roleIdList.add(Long.parseLong(roleId));
            }
            sysUserMenuDetailVO.setRoleIdList(roleIdList);
        }
        if (StringUtils.isNotEmpty(sysUserMenuDetailVO.getMenuIds())) {
            // 处理菜单
            List<Long> menuIdList = new ArrayList<>();
            for (String menuId : sysUserMenuDetailVO.getMenuIds().split(",")) {
                menuIdList.add(Long.parseLong(menuId));
            }
            sysUserMenuDetailVO.setMenuIdList(menuIdList);
        }
        return AjaxResult.success(sysUserMenuDetailVO);
    }

    /**
     * 保存管理员菜单
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.AUTHORITY_CONFIG, business = EOperationBusiness.MENU_AUTHORITY_AFTER, method = EOperationMethod.CONFIRM)
    @PostMapping
    public AjaxResult save(@RequestBody SysUserMenuParam param) {
        if (CollectionUtil.isEmpty(param.getUserIdList()) ||
                CollectionUtil.isEmpty(param.getMenuIdList())) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        return toAjax(iSysUserMenuService.saveSysUserMenu(param, SecurityUtils.getUserId()));
    }

}
