package com.sw.mes.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sw.mes.auth.domain.AuthPermission;
import com.sw.mes.auth.service.AuthPermissionService;
import com.sw.mes.core.dto.auth.PermissionDto;
import com.sw.mes.core.dto.auth.PermissionTree;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.core.utils.TreeUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/permission")
@Slf4j
@Api(description = "权限接口")
public class PermissionController {
    @Autowired
    ModelMapper modelMapper;


    @Autowired
    private AuthPermissionService authPermissionService;

    @ApiOperation(value = "分页查询权限列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query", required = false, readOnly = false),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query", required = false, readOnly = false),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<PermissionDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
       LambdaQueryWrapper<AuthPermission> queryWrapper=new LambdaQueryWrapper<>();
       Page<AuthPermission> listPage = authPermissionService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<PermissionDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos,listPage.getTotal());
        return ResultGenerator.success(responsePage);

    }

    @ApiOperation(value = "查询所有权限")
    @ApiImplicitParams({
    })
    @GetMapping("/listAll")
    public Result<List<PermissionDto>> listAll(ServletRequest request) {
        List<AuthPermission> permissions = authPermissionService.listAll();
        List<PermissionDto> dtos = permissions.stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());

        return ResultGenerator.success(dtos);
    }

    @GetMapping("/tree")
    @ApiOperation(value = "更新权限")
    public Result<List<PermissionTree>> tree() {
        List<AuthPermission> permissions = authPermissionService.listAll();
        List<PermissionTree> permissionTrees = getPermissionTree(permissions, 0);
        return ResultGenerator.success(permissionTrees);

    }

    @ApiOperation(value = "获取用户的权限集合")
    @GetMapping("/getByUserId")
    public Result<List<PermissionDto>> listUserPermission(ServletRequest request, Integer userId) {
        List<AuthPermission> permissions = authPermissionService.getByUserId(userId);
        List<PermissionDto> permissionDtos = permissions.stream()
                .map(permission -> toLazyDto(permission))
                .collect(Collectors.toList());
        return ResultGenerator.success(permissionDtos);
    }

    @ApiOperation(value = "权限详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限id", paramType = "path", dataType = "Integer"),
    })
    @GetMapping("/{id}")
    public Result<PermissionDto> get(@PathVariable Integer id) {
        AuthPermission permission = authPermissionService.getById(id);
        return ResultGenerator.success(toEagerDto(permission));
    }

    @ApiOperation(value = "创建权限")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "权限对象") PermissionDto permissionDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        AuthPermission permission = fromDto(permissionDto);
        authPermissionService.saveOrUpdate(permission);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新权限")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "权限") PermissionDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        AuthPermission entity = authPermissionService.getById(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            AuthPermission entityfromFto = fromDto(dto);
            PropertyUtils.copyProperties(entity,entityfromFto);
//            BeanUtils.copyProperties(entityfromFto, entity);
            authPermissionService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
        for (Integer id : ids) {
            authPermissionService.removeById(id);
        }
        return ResultGenerator.success();
    }


    private List<PermissionTree> getPermissionTree(List<AuthPermission> permissions, int root) {
        List<PermissionTree> trees = new ArrayList<PermissionTree>();
        PermissionTree node = null;
        for (AuthPermission permission : permissions) {
            node = new PermissionTree();
            BeanUtils.copyProperties(permission, node);
            trees.add(node);
        }
        List<PermissionTree> permissionTrees = TreeUtil.bulid(trees, root);
        permissionTrees.forEach(permissionTree -> setRank(permissionTree, 0));
        return permissionTrees;
    }

    private void setRank(PermissionTree permissionTree, Integer rank) {
        permissionTree.setRank(rank);
        if (permissionTree.getChildren() != null) {
            permissionTree.getChildren().forEach(treeNode -> {
                setRank((PermissionTree) treeNode, rank + 1);
            });
        }
    }

    public PermissionDto toLazyDto(AuthPermission entity) {
        return modelMapper.map(entity, PermissionDto.class);
    }

    public PermissionDto toEagerDto(AuthPermission entity) {
        return modelMapper.map(entity, PermissionDto.class);
    }

    public AuthPermission fromDto(PermissionDto dto) {
        return modelMapper.map(dto, AuthPermission.class);
    }

}
