package com.unis.crk.basic.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.unis.crk.basic.entity.RoleInfo;
import com.unis.crk.basic.entity.UserRole;
import com.unis.crk.basic.entity.vo.RoleInfoVo;
import com.unis.crk.basic.service.IRoleInfoService;
import com.unis.crk.basic.service.IUserRoleService;
import com.unis.crk.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色信息表 前端控制器
 * </p>
 *
 * @author ghh
 * @since 2021-09-26
 */
@Api(value = "角色信息表",tags = {"角色信息表"})
@RestController
@RequestMapping("roleInfo")
@CrossOrigin
public class RoleInfoController {

    private final static Logger LOGGER = LoggerFactory.getLogger(RoleInfoController.class);

    @Autowired
    private IRoleInfoService roleInfoService;

    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 查找角色信息
     * @param roleInfoVo

     * @return
     */
    @RequestMapping(value="/getRole", method = RequestMethod.POST)
    @ApiOperation(value="角色信息分页查询", notes = "传入角色名称或者父角色编号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父角色编号", paramType = "query"),
            @ApiImplicitParam(name = "roleName", value = "角色名称", paramType = "query")
    })
    public ResultUtil<IPage<RoleInfo>> getRoleInfo(@RequestBody RoleInfoVo roleInfoVo) {
        ResultUtil<IPage<RoleInfo>> data = new ResultUtil<>();
        QueryWrapper<RoleInfo> queryWrapper = new QueryWrapper<>();
//        if (roleInfoVo.getParentId() != null) {
        if (StrUtil.isNotBlank(roleInfoVo.getParentId())) {
            queryWrapper.eq("parent_id",roleInfoVo.getParentId());
        }
        if (StrUtil.isNotBlank(roleInfoVo.getRoleName())) {
            queryWrapper.like("role_name",roleInfoVo.getRoleName());
        }
        Page<RoleInfo>  objectPage = new Page<>(roleInfoVo.getPageNum(), roleInfoVo.getPageSize());
        IPage<RoleInfo> page = roleInfoService.page(objectPage, queryWrapper);
        ObjectMapper mapper = new ObjectMapper();
        data.success(page);
        return data;
    }


    /**
     * 根据角色ID查询数据
     * @param roleId
     * @return
     */
    @ApiOperation(value="查询", notes="根据角色ID查询数据")
    @GetMapping("getOne/{id}")
    public RoleInfo getRoleInfobyId(@PathVariable("roleId") String roleId) {
        RoleInfo roleInfo = new RoleInfo();
        if (StrUtil.isNotBlank(roleId)) {
            roleInfo = roleInfoService.getById(roleId);
        }
        return roleInfo;
    }



    /**
     * 根据用户编号查找角色信息
     * @param UserId
     * @return
     */
    @ApiOperation(value="查询", notes="根据角色ID查询角色信息")
    @GetMapping("getOne/{UserId}")
    public String getRoleIdByUserId(@PathVariable("UserId") String UserId) {
        String roleId = null;
        String roleName ="";
        RoleInfo roleInfo = new RoleInfo();
        QueryWrapper<RoleInfo> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(UserId)) {
            List<UserRole> userRole = userRoleService.getUserRole(UserId);
            if(userRole!=null && userRole.size()>0){
                roleId=userRole.get(0).getRoleId();
            }
        }
        if (StrUtil.isNotBlank(roleId)) {
            roleInfo = roleInfoService.getById(roleId);
            roleName = roleInfo.getRoleName();
            if (roleName.equals("保管员")){
                roleId = roleInfo.getRoleId();
            }

        }

        return roleId;
    }




    @ApiOperation(value="查询", notes="根据角色名检查是否存在相同的角色名称")
    @GetMapping("getOne/{roleName}")
    public Boolean validRoleName(@PathVariable("roleName") String roleName) {
        QueryWrapper<RoleInfo> queryWrapper = new QueryWrapper<>();
            return roleInfoService.validRoleName(roleName);

    }


    /**
     * 获取角色树
     * @return
     */
    @ApiOperation(value="获取角色树", notes="获取角色树")
    @GetMapping("getRoleTree")
    public Map<String, Object> getRoleTree() {
        ResultUtil<List<RoleInfo>> data = new ResultUtil<>();
        List<RoleInfo> list = this.roleInfoService.list();

        Map<String, Object> modelMap = new HashMap<>();
        List<RoleInfoVo> voList = new ArrayList<RoleInfoVo>();
        Map<String, String> roleNameObj = new HashMap<String, String>();
        for (RoleInfo roleInfo : list) {
            RoleInfoVo roleInfoVo = new RoleInfoVo();
            roleInfoVo.setRoleId(roleInfo.getRoleId());
            roleInfoVo.setRoleName(roleInfo.getRoleName());
            roleInfoVo.setParentId(roleInfo.getParentId());
            voList.add(roleInfoVo);
            roleNameObj.put(roleInfo.getRoleId(), roleInfo.getRoleName());
        }
        modelMap.put("roleList", voList);
        modelMap.put("roleNameObj", roleNameObj);
        modelMap.put("roleId", 0);
        return modelMap;
    }


    /**
     * 获取角色按钮权限列表
     * @return	List<FuncInfo>	功能列表
     */
    @ApiOperation(value="查询", notes="获取角色按钮权限列表")
    @GetMapping("getRoleTreeByOrg/{orgId}")
    public Map<String, Object> getRoleTreeByOrg(@PathVariable("orgId") String orgId ) {
        QueryWrapper<RoleInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id",orgId);
        queryWrapper.orderByAsc("createtime");
        List<RoleInfo> list = roleInfoService.list(queryWrapper);
        Map<String, Object> modelMap = new HashMap<>();
        List<RoleInfoVo> voList = new ArrayList<RoleInfoVo>();
        Map<String, String> roleNameObj = new HashMap<String, String>();
        for (RoleInfo roleInfo : list) {
            RoleInfoVo roleInfoVo = new RoleInfoVo();
            roleInfoVo.setRoleId(roleInfo.getRoleId());
            roleInfoVo.setRoleName(roleInfo.getRoleName());
            roleInfoVo.setParentId(roleInfo.getParentId());
            voList.add(roleInfoVo);
            roleNameObj.put(roleInfo.getRoleId(), roleInfo.getRoleName());
        }
        modelMap.put("roleList", voList);
        modelMap.put("roleNameObj", roleNameObj);
        modelMap.put("roleId", "0");
        return modelMap;
    }


    /**
     * 查询全部数据
     * @return
     */
    @ApiOperation(value="查询", notes="查询全部数据")
    @GetMapping("getAll")
    public ResultUtil getAll(){
        ResultUtil<List<RoleInfo>> data = new ResultUtil<>();
        data.success(this.roleInfoService.list());
        return data;
    }


    /**
     * 新增一条数据
     * @param param
     * @return
     */
    @ApiOperation(value="新增", notes="新增一条数据")
    @PostMapping("add")
    public ResultUtil add(@RequestBody RoleInfo param){
        LOGGER.info("入参为:{}", param);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(param)){
            data.failed("所接收对象为null");
            return data;
        }
        data.success(this.roleInfoService.save(param));
        return data;
    }


    /**
     * 修改一条数据
     * @param param
     * @return
     */
    @ApiOperation(value="修改", notes="修改一条数据")
    @PatchMapping("edit")
    public ResultUtil edit(@RequestBody RoleInfo param){
        LOGGER.info("入参为:{}", param);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(param)){
            data.failed("所接收对象为null");
            return data;
        }
        data.success(this.roleInfoService.updateById(param));
        return data;
    }


    /**
     * 根据ID删除数据
     * @param id
     * @return
     */
    @ApiOperation(value="删除", notes="根据ID删除数据")
    @DeleteMapping("delete/{id}")
    public ResultUtil delete(@PathVariable("id") String id){
        LOGGER.info("入参为:{}", id);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (StringUtils.isEmpty(id)){
            data.failed("所接收id为null");
            return data;
        }
        data.success(this.roleInfoService.removeById(id));
        return data;
    }


}

