package com.hxhq.system.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.hxhq.business.domain.RoleChange;
import com.hxhq.business.domain.SystemLog;
import com.hxhq.business.form.common.SignForm;
import com.hxhq.business.service.IRoleChangeService;
import com.hxhq.business.service.ISystemLogService;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.ServletUtils;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.system.domain.SysMenu;
import com.hxhq.system.domain.SysRoleMenu;
import com.hxhq.system.domain.SysUserRole;
import com.hxhq.system.domain.vo.TreeSelect;
import com.hxhq.system.dto.RoleMenuExportDto;
import com.hxhq.system.form.RoleSaveForm;
import com.hxhq.system.form.RoleUserSaveForm;
import com.hxhq.system.service.ISysDeptService;
import com.hxhq.system.service.ISysMenuService;
import com.hxhq.system.service.ISysRoleService;
import com.hxhq.system.service.ISysUserService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hxhq.common.core.utils.poi.ExcelUtil;
import com.hxhq.common.core.web.controller.BaseController;
import com.hxhq.common.core.web.domain.AjaxResult;
import com.hxhq.common.core.web.page.TableDataInfo;
import com.hxhq.common.log.annotation.Log;
import com.hxhq.common.log.enums.BusinessType;
import com.hxhq.common.security.annotation.RequiresPermissions;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.api.domain.SysDept;
import com.hxhq.system.api.domain.SysRole;
import com.hxhq.system.api.domain.SysUser;

/**
 * 角色信息
 * 
 * @author hxhq
 */
@RestController
@RequestMapping("/role")
public class SysRoleController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISystemLogService systemLogService;

    @Autowired
    private IRoleChangeService roleChangeService;

    @Autowired
    private ISysMenuService menuService;

    @RequiresPermissions("system:role:list")
    @GetMapping("/list")
    public TableDataInfo list(SysRole role)
    {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRole role)
    {
        List<SysRole> list = roleService.selectRoleList(role);
        for(SysRole l : list){
            l.setStatusText("0".endsWith(l.getStatus())?("zh_CN".equals(ServletUtils.getRequest().getHeader("lang"))?"启用":"Enabled"):("zh_CN".equals(ServletUtils.getRequest().getHeader("lang"))?"禁用":"Disabled"));
        }
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        util.exportExcel(response, list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @RequiresPermissions("system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody RoleSaveForm form)
    {
        SysRole role = form.getRole();
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!roleService.checkRoleKeyUnique(role))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色编码已存在");
        }
        if(StringUtils.isBlank(role.getRoleKey())){
            role.setRoleKey(UUID.randomUUID().toString());
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(form));

    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody RoleSaveForm form)
    {
        SysRole role = form.getRole();
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!roleService.checkRoleKeyUnique(role))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色编码已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRole(form));
    }

    /**
     * 修改保存数据权限
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:role:enable")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody RoleSaveForm form)
    {
        SysRole role = form.getRole();
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(form));
    }

    /**
     * 删除角色
     */
    @RequiresPermissions("system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds)
    {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @RequiresPermissions("system:role:list")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        return success(roleService.selectRoleAll());
    }
    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("system:role:allocate")
    @GetMapping("/authUser/allocatedList")
    public AjaxResult allocatedList(Long roleId)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("selected", userService.selectAllocatedListSimple(roleId));
        ajax.put("list", userService.selectTransferAllList());
        return ajax;
    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("system:role:allocate")
    @GetMapping("/authUser/unallocatedList")
    public TableDataInfo unallocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList(user);
        return getDataTable(list);
    }

    /**
     * 取消授权用户
     */
    @RequiresPermissions("system:role:allocate")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
    {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @RequiresPermissions("system:role:allocate")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
    {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @RequiresPermissions("system:role:allocate")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds)
    {
        roleService.checkRoleDataScope(roleId);
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }

    /**
     * 批量设置角色的用户
     */
    @RequiresPermissions("system:role:allocate")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/setAll")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult setAll(@RequestBody RoleUserSaveForm form)
    {
        SignForm sign = form.getSign();
        if(sign==null){
            throw new ServiceException("签名参数有误");
        }
        if(StringUtils.isBlank(sign.getQmrmm())){
            throw new ServiceException("签名密码不能为空");
        }
        userService.checkPassword(SecurityUtils.getLoginUser().getSysUser(),sign.getQmrmm(),false);

        SysRole sysRole = roleService.selectRoleById(form.getRoleId());
        List<Long> existsUserIds =  userService.selectAllocatedListSimple(form.getRoleId());
        List<Long> deleteIds = existsUserIds.stream().filter(o->!form.getUserIdList().contains(o)).collect(Collectors.toList());
        List<Long> addList = form.getUserIdList().stream().filter(o->!existsUserIds.contains(o)).collect(Collectors.toList());

        //角色变更历史
        List<RoleChange> roleChangelist = new ArrayList<>();
        if(addList.size()>0){
            for(Long addId :addList){
                List<String> oldNameList = roleService.selectRoleNameListByUserId(addId);
                RoleChange roleChange = new RoleChange();
                roleChange.setUserId(addId);
                roleChange.setBgq(oldNameList.size()>0?String.join(",",oldNameList):"");
                roleChange.setBgh(roleChange.getBgq()+","+sysRole.getRoleName());
                roleChange.setRemark(sign.getRemark());
                roleChangelist.add(roleChange);
            }
        }
        if(deleteIds.size()>0){
            for(Long deleteId :deleteIds){
                List<String> oldNameList = roleService.selectRoleNameListByUserId(deleteId);
                RoleChange roleChange = new RoleChange();
                roleChange.setUserId(deleteId);
                roleChange.setBgq(oldNameList.size()>0?String.join(",",oldNameList):"");
                roleChange.setBgh(roleChange.getBgq().replace(","+sysRole.getRoleName(),"").replace(","+sysRole.getRoleName()+",","").replace(sysRole.getRoleName()+",",""));
                roleChange.setRemark(sign.getRemark());
                roleChangelist.add(roleChange);
            }
        }

        List<String> deleteUserNames = new ArrayList<>();
        List<String> addUserNames = new ArrayList<>();
        if(deleteIds.size()>0){
            roleService.deleteAuthUsers(form.getRoleId(), deleteIds.toArray(new Long[0]));
            deleteUserNames = userService.selectNamesByIdList(deleteIds);
        }
        if(addList.size()>0){
            roleService.insertAuthUsers(form.getRoleId(), addList.toArray(new Long[0]));
            addUserNames = userService.selectNamesByIdList(addList);
        }

        if(addUserNames.size()>0 || deleteUserNames.size()>0){
            SystemLog log = new SystemLog();
            log.setName(sysRole.getRoleName());
            log.setNameEn(sysRole.getRoleName());
            log.setJcmc("分配用户");
            log.setJcmcEn("Add User");
            log.setQmrId(SecurityUtils.getUserId());
            log.setQmrMc(SecurityUtils.getNickName());
            log.setQmrMcEn(SecurityUtils.getUsername());

            log.setJcnr((addUserNames.size()>0?("新增用户："+String.join(",",addUserNames)):"")+(deleteUserNames.size()>0?("；删除用户："+String.join(",",deleteUserNames)):"")+(StringUtils.isBlank(sign.getRemark())?"":"；备注："+sign.getRemark()));
            log.setJcnrEn((addUserNames.size()>0?("Add User："+String.join(",",addUserNames)):"")+(deleteUserNames.size()>0?("；Remove User："+String.join(",",deleteUserNames)):"")+(StringUtils.isBlank(sign.getRemark())?"":"；Comment："+sign.getRemark()));
            systemLogService.save(log);
        }
        if(roleChangelist.size()>0){
            roleChangeService.saveList(roleChangelist);
        }

        return AjaxResult.success("操作成功");
    }

    /**
     * 获取对应角色部门树列表
     */
    @RequiresPermissions("system:role:list")
    @GetMapping(value = "/deptTree/{roleId}")
    public AjaxResult deptTree(@PathVariable("roleId") Long roleId)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return ajax;
    }

    @RequiresPermissions("system:role:export")
    @PostMapping("/exportMenu")
    public void exportMenu(HttpServletResponse response, SysRole role) throws IOException {
        //角色列表
        List<SysRole> roleList = roleService.selectRoleList(role);
        if(roleList.size()==0){
            throw new ServiceException("没有数据");
        }
        //角色菜单列表
        List<SysRoleMenu> roleMenuList = roleService.selectRoleMenuByRoleIdList(roleList.stream().map(o->o.getRoleId()).collect(Collectors.toList()));

        SysMenu sysMenu = new SysMenu();
        List<TreeSelect> menuTree = menuService.buildMenuTreeSelect(menuService.selectMenuList(sysMenu, SecurityUtils.getUserId()));
        List<RoleMenuExportDto> menuList = new ArrayList<>();
        transferTreeToList(menuList,menuTree,1);
        Integer maxLevel = Collections.max(menuList,
                Comparator.comparingInt(RoleMenuExportDto::getLevel)).getLevel();

        // 设置响应
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("角色权限", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 动态表头：假设我们有一个动态的表头列表，这里用字符串列表表示
        List<String> headList = new ArrayList<>();
        for(int i=0;i<maxLevel;i++){
            headList.add("菜单");
        }

        for(SysRole info : roleList){
            headList.add(info.getRoleName());
        }

        // 但是EasyExcel的多级表头是List<List<String>>，所以我们需要转换
        List<List<String>> head = new ArrayList<>();
        for (String h : headList) {
            List<String> hh = new ArrayList<>();
            hh.add(h);
            head.add(hh);
        }

        // 数据部分：每一行是一个List<Object>，顺序与表头对应
        List<List<Object>> data = new ArrayList<>();
        for(RoleMenuExportDto dto : menuList){
            List<Object> row = new ArrayList<>();
            for(Integer i=1;i<=maxLevel;i++){
                row.add(dto.getLevel().equals(i)?dto.getMenuName():"");
            }

            for(SysRole info : roleList){
                row.add(roleMenuList.stream().filter(o->o.getMenuId().equals(dto.getMenuId()) && o.getRoleId().equals(info.getRoleId())).count()>0?"✓":"");
            }
            data.add(row);
        }

        EasyExcel.write(response.getOutputStream())
                // 设置表头
                .head(head)
                // 设置sheet名称
                .sheet("Sheet1")
                // 写入数据
                .doWrite(data);
    }

    void transferTreeToList(List<RoleMenuExportDto> list,List<TreeSelect> tree,Integer level){
        for(TreeSelect t : tree){
            RoleMenuExportDto item = new RoleMenuExportDto();
            item.setMenuId(t.getId());
            item.setMenuName(t.getLabel());
            item.setLevel(level);
            list.add(item);
            if(t.getChildren()!=null && t.getChildren().size()>0){
                transferTreeToList(list,t.getChildren(),level+1);
            }
        }
    }

}
