package com.liang.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liang.common.JsonTool;
import com.liang.common.base.BaseResult;
import com.liang.common.annotation.LogAround;
import com.liang.common.base.BaseController;
import com.liang.entity.SysRoleInfo;
import com.liang.service.SysDictInfoService;
import com.liang.service.SysRoleInfoService;
import com.liang.service.SysRolePermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (SysRoleInfo)表控制层
 *
 * @author makejava
 * @since 2023-02-19 21:37:39
 */
@Controller
@RequestMapping("/roleinfo")
public class SysRoleInfoController extends BaseController {
    final static Logger logger = LoggerFactory.getLogger(SysRoleInfoController.class);
    /**
     * 服务对象
     */
    @Resource
    private SysRoleInfoService sysRoleInfoService;
    @Resource
    private SysDictInfoService sysDictInfoService;
    @Resource
    private SysRolePermissionService sysRolePermissionService;


    /**
     * 分页查询
     *
     * @param sysRoleInfo 筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<SysRoleInfo>> queryByPage(SysRoleInfo sysRoleInfo, PageRequest pageRequest) {
        return ResponseEntity.ok(this.sysRoleInfoService.queryByPage(sysRoleInfo, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<SysRoleInfo> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.sysRoleInfoService.queryById(id));
    }


    /**
     * 查询页面初始化
     *
     * @return
     */
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public String   init(Model model) {
        // 获取下拉栏枚举值
        List<Map<String, String>> baseDictList = sysDictInfoService.queryByCode("role_status");
        model.addAttribute("baseDictList", baseDictList);
        return "roleinfo/list";
    }

    /**
     * 角色菜单
     *
     * @return
     */
    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd() {
        return "roleinfo/add";
    }


    /**
     * 角色修改页面初始化
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate/{roleId}", method = RequestMethod.GET)
    public String forUpdate(Model model, @PathVariable Integer roleId) {
        SysRoleInfo roleInfo = sysRoleInfoService.queryById(roleId);
        model.addAttribute("roleInfo", roleInfo);
        return "roleinfo/update";
    }

    /**
     * 角色修改页面初始化
     *
     * @return
     */
    @RequestMapping(value = "/forView/{roleId}", method = RequestMethod.GET)
    public String forView(Model model, @PathVariable Integer roleId) {
        SysRoleInfo roleInfo = sysRoleInfoService.queryById(roleId);
        model.addAttribute("roleInfo", roleInfo);
        return "roleinfo/view";
    }

    /**
     * 角色授权页面
     *
     * @return
     */
    @RequestMapping(value = "/authorize/{roleId}", method = RequestMethod.GET)
    public String authorize(Model model,
                            @PathVariable Integer roleId) {
        SysRoleInfo roleInfo = sysRoleInfoService.queryById(roleId);
        model.addAttribute("roleInfo", roleInfo);
        return "roleinfo/auth";
    }

    /**
     * 角色新增
     *
     * @return
     */
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult doAdd(SysRoleInfo roleInfo) {
        if (logger.isInfoEnabled()) {
            logger.info("doAdd -- name =  {}：" + roleInfo.getName());
        }
        roleInfo.setCreateUser(getSysUserId());

        int num = sysRoleInfoService.insert(roleInfo);
        if (num > 0) {
            return BaseResult.success("新增角色成功!");
        } else if (num == -1) {
            return BaseResult.failure("该角色已存在!");
        } else {
            return BaseResult.failure("新增角色失败!");
        }
    }

    /**
     * 删除一个系统角色（这里用逻辑删除）
     *
     * @return
     */
    @RequestMapping(value = "/delete/{roleId}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult delete(@PathVariable Integer roleId) {
        int updateUser = getSysUserId();
        boolean flag = sysRoleInfoService.deleteById(roleId, updateUser);
        if (flag) {
            return BaseResult.success("删除成功!");
        } else {
            return BaseResult.failure("删除失败!");
        }
    }

    /**
     * 角色更新
     *
     * @return
     */
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult doUpdate(SysRoleInfo sysRoleInfo) {
        if (logger.isInfoEnabled()) {
            logger.info("doUpdate -- name =  {}：" + sysRoleInfo.getName());
        }
        sysRoleInfo.setUpdateUser(getSysUserId()); //需更换为登录用户

        int num = sysRoleInfoService.update(sysRoleInfo);
        if (num > 0) {
            return BaseResult.success("角色更新成功!");
        } else if (num == -1) {
            return BaseResult.failure("该角色已存在!");
        } else {
            return BaseResult.failure("角色更新失败!");
        }
    }

    /**
     * 禁用一个系统角色
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/forbid/{roleId}", method = RequestMethod.GET)
    public BaseResult forbid(@PathVariable Integer roleId) {
        int num = sysRoleInfoService.forbid(roleId);
        if (num > 0) {
            return BaseResult.success("禁用成功!");
        } else {
            return BaseResult.failure("禁用失败!");
        }
    }

    /**
     * 启用一个系统角色
     *
     * @return
     */
    @RequestMapping(value = "/enable/{roleId}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult enable(@PathVariable Integer roleId) {
        int num = sysRoleInfoService.enable(roleId);
        if (num > 0) {
            return BaseResult.success("启用成功!");
        } else {
            return BaseResult.failure("启用失败!");
        }
    }

    /**
     * 角色管理页面分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @LogAround("角色管理页面分页查询")
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public BaseResult list(@RequestParam("page") Integer pageNum,
                           @RequestParam("limit") Integer pageSize,
                           @RequestParam(required = false, defaultValue = "", value = "sign") String sign,
                           @RequestParam(required = false, defaultValue = "", value = "name") String name,
                           @RequestParam(required = false, defaultValue = "", value = "status") String status,
                           @RequestParam(required = false, defaultValue = "", value = "sortName") String sortName,
                           @RequestParam(required = false, defaultValue = "", value = "sortOrder") String sortOrder) {
        //分页查询
        PageHelper.startPage(pageNum, pageSize);
        if (logger.isInfoEnabled()) {
            logger.info("getSysRoleInfoList -- 页面大小：" + pageSize + "--页码:" + pageNum);
        }

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("sign", sign);
        paraMap.put("name", name);
        paraMap.put("status", status);
        paraMap.put("sortName", sortName);
        paraMap.put("sortOrder", sortOrder);

        List<SysRoleInfo> roleList = sysRoleInfoService.getSysRoleInfoList(paraMap);

        PageInfo<SysRoleInfo> pageinfo = new PageInfo<>(roleList);
        //取出查询结果
        List<SysRoleInfo> rows = pageinfo.getList();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, pageinfo.getTotal());

        return BaseResult.success(result);
    }


    /**
     * 根据角色roleId查询菜单权限树
     *
     * @param roleId
     * @return
     */
    @RequestMapping(value = "/listPermissionByRoleId/{roleId}", method = RequestMethod.GET)
    @ResponseBody
    public Object listPermissionForTree(@PathVariable Integer roleId) {
        return sysRolePermissionService.listPermissionByRoleId(roleId);
    }

    /**
     * 角色权限更新
     *
     * @return
     */
    @RequestMapping(value = "/doAuthorize", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult doAuthorize(@RequestParam(value = "roleId") Integer roleId,
                                  @RequestParam(value = "permIds") String permIds) {
        if (logger.isInfoEnabled()) {
            logger.info("doAuthorize -- permIds =  {}：" + permIds);
        }
        int num = sysRolePermissionService.doAuthorize(roleId, permIds);
        if (num > 0) {
            return BaseResult.success("菜单权限更新成功!");
        } else {
            return BaseResult.failure("菜单权限更新失败!");
        }
    }

    /**
     * 批量删除
     *
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult batchDelete(@RequestBody String data) {
        if (logger.isInfoEnabled()) {
            logger.info("SysRoleInfoController -- batchDelete -- data：{}", data);
        }

        List<Integer> roleIdList = JsonTool.parseArray(data, Integer.class);
        int num = sysRoleInfoService.batchDelete(roleIdList, getSysUserId());
        if (num > 0) {
            return BaseResult.success("批量删除成功!");
        } else {
            return BaseResult.failure("批量删除失败!");
        }
    }
}

