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.AuthRole;
import com.sw.mes.auth.domain.AuthRoleFactory;
import com.sw.mes.auth.domain.AuthRolePermission;
import com.sw.mes.auth.domain.AuthRoleWarehouse;
import com.sw.mes.auth.service.AuthRolePermissionService;
import com.sw.mes.auth.service.AuthRoleService;
import com.sw.mes.auth.service.impl.AuthRoleFactoryServiceImpl;
import com.sw.mes.auth.service.impl.AuthRoleWarehouseServiceImpl;
import com.sw.mes.core.annotation.Jinko;
import com.sw.mes.core.dto.auth.RoleDto;
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 io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
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.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/role")
@Slf4j
@Api(description = "角色信息接口")
public class RoleController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private AuthRoleService authRoleService;

    @Autowired
    private AuthRolePermissionService authRolePermissionService;

    @Autowired
    private AuthRoleWarehouseServiceImpl authRoleWarehouseService;
    @Autowired
    private AuthRoleFactoryServiceImpl authRoleFactoryService;

    @ApiOperation(value = "分页查询角色信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_name", value = "角色名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_type", value = "角色类型", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<RoleDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        LambdaQueryWrapper<AuthRole> queryWrapper = new LambdaQueryWrapper<>();
        if (request.getParameter("search_LIKE_name") != null) {
            queryWrapper.like(AuthRole::getName, request.getParameter("search_LIKE_name"));
        }
        if (request.getParameter("search_EQ_type") != null) {
            queryWrapper.eq(AuthRole::getType, request.getParameter("search_EQ_type"));
        }
        Page<AuthRole> listPage = authRoleService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);

        List<RoleDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);

    }

    @ApiOperation(value = "下拉框查询角色信息列表")
    @GetMapping("/listAll")
    public Result<List<RoleDto>> listAll(ServletRequest request) {
        List<AuthRole> roles = authRoleService.list();
        List<RoleDto> roleDtos = roles.stream()
                .map(role -> toLazyDto(role))
                .collect(Collectors.toList());
        return ResultGenerator.success(roleDtos);

    }

    @ApiOperation(value = "角色信息详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色信息id", paramType = "path", dataType = "Integer"),
    })
    @GetMapping("/{id}")
    public Result<RoleDto> get(@PathVariable Integer id) {
        AuthRole role = authRoleService.getById(id);
        if (null == role)
            return ResultGenerator.fail("角色不存在");
        RoleDto dto = toEagerDto(role);

        return ResultGenerator.success(dto);
    }

    @ApiOperation(value = "创建角色信息")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "角色信息对象") RoleDto roleDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        AuthRole role = fromDto(roleDto);
        role.setCreateTime(new Date());
        authRoleService.saveOrUpdate(role);
        if (!StringUtils.isBlank(roleDto.getPermissionIds()))
            authRoleService.updatePermission(role.getId(), roleDto.getPermissionIds());
        return ResultGenerator.success();
    }

    @ApiOperation(value = "分配功能权限")
    @PostMapping("/editPermission")
    public Result editPermission(@ApiParam(value = "角色Id") @RequestParam Integer roleId, @ApiParam(value = "权限id集合,逗号分隔,如1,3") @RequestParam String permissionIds) {
        authRoleService.updatePermission(roleId, permissionIds);
        return ResultGenerator.success();
    }

    @Jinko(value = "新增分配数据权限接口",author = "liangfeng")
    @ApiOperation(value = "分配数据权限")
    @PostMapping("/editDataPermission")
    public Result editDataPermission(@ApiParam(value = "角色Id") @RequestParam Integer roleId,
                                     @ApiParam(value = "工厂模型id集合,逗号分隔,如1,3") @RequestParam(required=false) String factoryModelIds,
                                     @ApiParam(value = "仓库权限id集合,逗号分隔,如1,3") @RequestParam(required=false) String warehouseIds) {
        authRoleService.updateDataPermission(roleId, factoryModelIds, warehouseIds);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新角色信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "角色信息") RoleDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        AuthRole entity = authRoleService.getById(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            AuthRole entityfromFto = fromDto(dto);
            PropertyUtils.copyProperties(entity, entityfromFto);
            authRoleService.saveOrUpdate(entity);
            if (!StringUtils.isBlank(dto.getPermissionIds()))
                authRoleService.updatePermission(entity.getId(), dto.getPermissionIds());
            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) {
            authRoleService.removeById(id);
        }
        return ResultGenerator.success();
    }

    public RoleDto toLazyDto(AuthRole entity) {
        return modelMapper.map(entity, RoleDto.class);
    }

    public RoleDto toEagerDto(AuthRole entity) {
        RoleDto dto = modelMapper.map(entity, RoleDto.class);
        List<AuthRolePermission> rolePermissions = authRolePermissionService.findByRoleId(entity.getId());
        if (CollectionUtils.isNotEmpty(rolePermissions)) {
            dto.setPermissionIds(String.join(",", rolePermissions.stream().map(permission -> permission.getPermissionId().toString()).collect(Collectors.toList())));
        }
        List<AuthRoleFactory> authRoleFactoryList = authRoleFactoryService.findAuthRoleFactoryByRoleId(entity.getId());
        if (CollectionUtils.isNotEmpty(authRoleFactoryList)){
            dto.setFactoryModelIds(String.join(",",authRoleFactoryList.stream().map(item->item.getFactoryModelId().toString()).collect(Collectors.toList())));
        }
        List<AuthRoleWarehouse> authRoleWarehouseList = authRoleWarehouseService.findAuthRoleWarehouseByRoleId(entity.getId());
        if (CollectionUtils.isNotEmpty(authRoleWarehouseList)){
            dto.setWarehouseIds(String.join(",",authRoleWarehouseList.stream().map(item->item.getWarehouseId().toString()).collect(Collectors.toList())));
        }
        return dto;
    }

    public AuthRole fromDto(RoleDto dto) {
        return modelMapper.map(dto, AuthRole.class);
    }

    @ApiOperation(value = "获取当前角色关联的工厂")
    @PostMapping("/getRoleFactory")
    public Result<List<AuthRoleFactory>> getRoleFactory(@RequestParam Integer roleId){
        List<AuthRoleFactory> authRoleFactory = authRoleFactoryService.findAuthRoleFactoryByRoleId(roleId);
        return ResultGenerator.success(authRoleFactory);
    }
    @ApiOperation(value = "获取当前角色关联的仓库")
    @PostMapping("/getRoleWarehouse")
    public Result<List<AuthRoleWarehouse>> getRoleWarehouse(@RequestParam Integer roleId){
        List<AuthRoleWarehouse> authRoleWarehouse = authRoleWarehouseService.findAuthRoleWarehouseByRoleId(roleId);
        return ResultGenerator.success(authRoleWarehouse);
    }

}
