package com.yzt.airconditionersystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.yzt.airconditionersystem.bean.Permission;
import com.yzt.airconditionersystem.bean.Role;
import com.yzt.airconditionersystem.bean.RolePermission;
import com.yzt.airconditionersystem.result.Result;
import com.yzt.airconditionersystem.service.PermissionService;
import com.yzt.airconditionersystem.service.RolePermissionService;
import com.yzt.airconditionersystem.service.RoleService;
import com.yzt.airconditionersystem.util.BasePageVoUtil;
import com.yzt.airconditionersystem.vo.BasePageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
import java.util.stream.Collectors;

/**
 * @author TzZach
 * @since 2022-05-09 12:26
 */
@Controller
public class RoleController {

    private static final String PREFIX = "role/";

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionService rolePermissionService;

    @GetMapping("/role/page")
    @ResponseBody
    public BasePageVo rolePage(@RequestParam("page") Long page,
                               @RequestParam("limit") Long limit) {
//        List<RolePermission> list = rolePermissionService.list();
//        Page<Role> pageInfo = new Page<>(page, limit);
//        pageInfo = roleService.page(pageInfo);
//        for (Role record : pageInfo.getRecords()) {
//            Integer id = record.getId();
//            permissionService.list();
//        }

        List<RolePermission> rolePermissions = rolePermissionService.list();
        Page<Role> pageInfo = new Page<>(page, limit);
        pageInfo = roleService.page(pageInfo);
        for (Role role : pageInfo.getRecords()) {
            Integer roleId = role.getId();
            for (RolePermission rolePermission : rolePermissions) {
                if (roleId.equals(rolePermission.getRoleId())) {
                    LambdaQueryWrapper<Permission> permissionLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    permissionLambdaQueryWrapper.eq(Permission::getId, rolePermission.getPermissionId());
                    Permission permission = permissionService.getOne(permissionLambdaQueryWrapper);
                    if (!StringUtils.hasLength(role.getPermissionName())) {
                        role.setPermissionName(permission.getName());
                    } else {
                        String permissionName = role.getPermissionName() + "," + permission.getName();
                        role.setPermissionName(permissionName);
                    }
                }
            }
        }
        return BasePageVoUtil.getPageVo(pageInfo);
    }

    @PostMapping("/role/delete")
    @ResponseBody
    public Result roleDelete(@RequestBody Role role) {
        roleService.removeById(role);
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, role.getId());
        rolePermissionService.remove(queryWrapper);
        return Result.success("删除成功");
    }

    @GetMapping("/role/index")
    public String roleAdd() {
        return PREFIX + "role-add";
    }

    @PostMapping("/role/add")
    @ResponseBody
    public Result addRole(@RequestBody Role role) {
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(Role::getName, role.getName());
        Role fromDb = roleService.getOne(roleLambdaQueryWrapper);
        if (fromDb != null) {
            return Result.error("该角色名称已存在!");
        }
        roleService.save(role);
        Map<String, Object> data = new HashMap<>(2);
        data.put("data", "添加成功");
        data.put("roleId", role.getId());
        return Result.success(data);
    }

//    @PostMapping("/role/permission/add")
//    @ResponseBody
//    public Result rolePermissionAdd(@RequestBody RolePermission rolePermission) {
//        rolePermissionService.save(rolePermission);
//        return Result.success("添加角色相关权限成功");
//    }

    @PostMapping("/role/batchDelete")
    @ResponseBody
    public Result roleBatchDelete(@RequestBody List<String> ids) {
        roleService.removeBatchByIds(ids);
        return Result.success("删除成功");
    }

    @GetMapping("/role-edit")
    public String roleEdit(@RequestParam("id") Integer roleId,
                           Model model) {
        Role role = roleService.getById(roleId);
        model.addAttribute("role", role);
        return PREFIX + "role-edit";
    }

    @PostMapping("/role/edit")
    @ResponseBody
    public Result editRole(@RequestBody Role role) {
        Integer roleId = role.getId();
        Role roleFromDb = roleService.getById(roleId);
        if (role.getName().equals(roleFromDb.getName())) {
            return Result.success(roleId);
        }
        roleService.updateById(role);
        return Result.success(roleId);
    }

    @PostMapping("/role/tree")
    @ResponseBody
    public Result rolePermissionTree(@RequestBody Integer roleId) {
        LambdaQueryWrapper<RolePermission> rolePermissionLambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        rolePermissionLambdaQueryWrapper.eq(RolePermission::getRoleId, roleId)
                .select(RolePermission::getPermissionId);
        List<Object> permissionIds = rolePermissionService.listObjs(rolePermissionLambdaQueryWrapper);
//        LambdaQueryWrapper<Permission> permissionLambdaQueryWrapper
//                = new LambdaQueryWrapper<>();
//        permissionLambdaQueryWrapper.in(Permission::getId, permissionIds);
//        List<Permission> permissions = permissionService.list(permissionLambdaQueryWrapper);
        List<Permission> permissions = permissionService.list();

        for (Permission permission : permissions) {
            if (permissionIds.contains(permission.getId())) {
                permission.setChecked(true);
            }
        }

        List<Permission> childrenList = permissions.stream()
                .filter(permission -> !permission.getParentId().equals(Permission.NO_PARENT))
                .collect(Collectors.toList());

        for (Permission parent : permissions) {
            parent.setTitle(parent.getName());
            List<Permission> children = new ArrayList<>();
            for (Permission child : childrenList) {
                if (parent.getId().equals(child.getParentId())) {
                    children.add(child);
                }
            }
            parent.setChildren(children);
        }

        permissions = permissions.stream()
                .filter(permission -> permission.getParentId().equals(Permission.NO_PARENT))
                .collect(Collectors.toList());

        return Result.success(permissions);
    }

    @PostMapping("/role/tree/all")
    @ResponseBody
    public Result rolePermissionTree() {
//        LambdaQueryWrapper<RolePermission> rolePermissionLambdaQueryWrapper
//                = new LambdaQueryWrapper<>();
//        rolePermissionLambdaQueryWrapper.eq(RolePermission::getRoleId, roleId)
//                .select(RolePermission::getPermissionId);
//        List<Object> permissionIds = rolePermissionService.listObjs(rolePermissionLambdaQueryWrapper);
//        LambdaQueryWrapper<Permission> permissionLambdaQueryWrapper
//                = new LambdaQueryWrapper<>();
//        permissionLambdaQueryWrapper.in(Permission::getId, permissionIds);
//        List<Permission> permissions = permissionService.list(permissionLambdaQueryWrapper);
        List<Permission> permissions = permissionService.list();

//        for (Permission permission : permissions) {
//            if (permissionIds.contains(permission.getId())) {
//                permission.setChecked(true);
//            }
//        }

        List<Permission> childrenList = permissions.stream()
                .filter(permission -> !permission.getParentId().equals(Permission.NO_PARENT))
                .collect(Collectors.toList());

        for (Permission parent : permissions) {
            parent.setTitle(parent.getName());
            List<Permission> children = new ArrayList<>();
            for (Permission child : childrenList) {
                if (parent.getId().equals(child.getParentId())) {
                    children.add(child);
                }
            }
            parent.setChildren(children);
        }

        permissions = permissions.stream()
                .filter(permission -> permission.getParentId().equals(Permission.NO_PARENT))
                .collect(Collectors.toList());

        return Result.success(permissions);
    }




}
