package com.jpsoft.shinestar.modules.sys.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.sys.dto.RoleRelatedDTO;
import com.jpsoft.shinestar.modules.sys.entity.Role;
import com.jpsoft.shinestar.modules.sys.entity.RoleMenu;
import com.jpsoft.shinestar.modules.sys.entity.RolePermission;
import com.jpsoft.shinestar.modules.sys.service.RoleMenuService;
import com.jpsoft.shinestar.modules.sys.service.RolePermissionService;
import com.jpsoft.shinestar.modules.sys.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/sys/role")
public class RoleController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<Role> create(){
        MessageResult<Role> msgResult = new MessageResult<>();

        Role role = new Role();

        msgResult.setData(role);
        msgResult.setResult(true);

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<Role> add(@RequestBody Role role,@RequestAttribute String subject){
        MessageResult<Role> msgResult = new MessageResult<>();

            try {
            role.setId(UUID.randomUUID().toString());
            role.setDelFlag(false);
            role.setCreateBy(subject);
            role.setCreateTime(new Date());
            
            int affectCount = roleService.insert(role);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(role);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<Role> edit(@PathVariable("id") String id){
        MessageResult<Role> msgResult = new MessageResult<>();

        try {
            Role role = roleService.get(id);

            if (role != null) {
                msgResult.setResult(true);
                msgResult.setData(role);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<Role> update(@RequestBody Role role,@RequestAttribute String subject){
        MessageResult<Role> msgResult = new MessageResult<>();

        try {
            role.setUpdateBy(subject);
            role.setUpdateTime(new Date());
            
            int affectCount = roleService.update(role);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(role);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            Role role = roleService.get(id);
            role.setDelFlag(true);
            role.setUpdateBy(subject);
            role.setUpdateTime(new Date());

            int affectCount = roleService.update(role);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                Role role = roleService.get(id);
                role.setDelFlag(true);
                role.setUpdateBy(subject);
                role.setUpdateTime(new Date());

                affectCount += roleService.update(role);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取所有角色")
    @GetMapping(value = "selectAll")
    public MessageResult<List> selectAll(){
        MessageResult<List> msgResult = new MessageResult<>();

        try {
            List<Role> roles = roleService.list();

            msgResult.setResult(true);
            msgResult.setData(roles);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String roleName,
            String roleDesc,
            @RequestParam(name="pageIndex",defaultValue = "1") int pageIndex,
            @RequestParam(name="pageSize",defaultValue = "10") int pageSize,
            @RequestParam(value="field",defaultValue="create_time") String field,
            @RequestParam(value="direction",defaultValue="asc") String direction,
            HttpServletRequest request){
        String subject = (String)request.getAttribute("subject");

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort(field,direction));

        if (StringUtils.isNotEmpty(roleName)) {
            searchParams.put("roleName","%" + roleName + "%");
        }

        if (StringUtils.isNotEmpty(roleDesc)) {
            searchParams.put("roleDesc","%" + roleDesc + "%");
        }

        Page<Role> page = roleService.pageSearch(searchParams,pageIndex,pageSize,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="获取已分配菜单列表")
    @GetMapping(value = "queryRelatedMenuList")
    public MessageResult<List> queryRelatedMenuList(String roleId){
        MessageResult<List> msgResult = new MessageResult<>();

        try {
            List<RoleMenu> list = roleMenuService.findByRoleId(roleId);

            msgResult.setResult(true);
            msgResult.setData(list);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="保存关联菜单")
    @PostMapping(value = "saveRelatedMenu")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult<Integer> saveRelatedMenu(@RequestBody RoleRelatedDTO dto,String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            roleMenuService.deleteByRoleId(dto.getRoleId());

            int affectCount = 0;

            for (String menuId : dto.getRelatedList()) {
                RoleMenu rm = new RoleMenu();
                rm.setId(UUID.randomUUID().toString());
                rm.setRoleId(dto.getRoleId());
                rm.setMenuId(menuId);
                rm.setDelFlag(false);
                rm.setCreateBy(subject);
                rm.setCreateTime(new Date());

                affectCount+= roleMenuService.insert(rm);
            }

            msgResult.setResult(true);
            msgResult.setData(affectCount);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取已分配接口权限列表")
    @GetMapping(value = "queryRelatedPerms")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult<List> queryRelatedPerms(String roleId){
        MessageResult<List> msgResult = new MessageResult<>();

        try {
            List<RolePermission> list = rolePermissionService.findByRoleId(roleId);

            msgResult.setResult(true);
            msgResult.setData(list);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="保存关联接口权限")
    @PostMapping(value = "saveRelatedPermission")
    public MessageResult<Integer> saveRelatedPermission(@RequestBody RoleRelatedDTO dto,String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            rolePermissionService.deleteByRoleId(dto.getRoleId());

            int affectCount = 0;

            for (String permissionId : dto.getRelatedList()) {
                RolePermission rp = new RolePermission();
                rp.setId(UUID.randomUUID().toString());
                rp.setRoleId(dto.getRoleId());
                rp.setPermId(permissionId);
                rp.setDelFlag(false);
                rp.setCreateBy(subject);
                rp.setCreateTime(new Date());

                affectCount+= rolePermissionService.insert(rp);
            }

            msgResult.setResult(true);
            msgResult.setData(affectCount);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }
}
