package com.rf.psychological.menu.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.menu.dao.dto.RoleMenuEntryDTO;
import com.rf.psychological.menu.dao.model.MenuEntry;
import com.rf.psychological.menu.dao.model.RoleMenuEntry;
import com.rf.psychological.menu.service.MenuService;
import com.rf.psychological.menu.service.RoleMenuService;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.HttpStatus;
import com.rf.psychological.utils.Result;
import com.rf.psychological.utils.Utils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:zzf
 * @Date:2022/7/6:17:59
 * @Description:
 */
@RestController
@Slf4j
@RequestMapping("/menu")
public class MenuController extends BaseController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleMenuService roleMenuService;

    /**
     * 查询顶级菜单
     * @return
     */
    @ApiOperation(value = "查询用户菜单权限——顶级菜单")
    @SafetyProcess
    @GetMapping("/find/user/{userId}")
    public Result find(@PathVariable String userId){
        return getResult(userId, null);
    }



    @ApiOperation(value = "查询用户菜单权限——下级菜单")
    @SafetyProcess
    @GetMapping("/find/user/{userId}/{menuNo}")
    public Result find(@PathVariable String userId,@PathVariable String menuNo){
        return getResult(userId, menuNo);
    }

    @ApiOperation(value = "查询菜单-角色关联关系")
    @SafetyProcess
    @GetMapping("/find/roleMenu/{menuNo}")
    public Result findRoleMenu(@PathVariable String menuNo){
        List<RoleMenuEntry> list = this.roleMenuService.findByMenuNo(menuNo);
        List<RoleMenuEntryDTO> roleMenuEntryDTOS = new ArrayList<>();
        if(list != null && list.size()>0){
            list.forEach(roleMenuEntry -> {
                RoleMenuEntryDTO entry = new RoleMenuEntryDTO(roleMenuEntry);
                MenuEntry menuEntry = this.menuService.findByMenuNo(menuNo);
                if(menuEntry == null) return;
                entry.setMenuName(menuEntry.getMenuName());
                entry.setRoleName(Utils.roleType2roleName(roleMenuEntry.getRole()));
                roleMenuEntryDTOS.add(entry);
            });
        }
        return success(roleMenuEntryDTOS);
    }

    @PostMapping("/roleMenu/{roleNo}")
    @ApiOperation("维护角色菜单关联关系")
    @SafetyProcess
    public Result updateRoleManu(@RequestBody String json, @PathVariable String roleNo) throws Exception {
        JSONArray jsonArray = JSONArray.parseArray(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
        List<String> menuNos = jsonArray.toJavaList(String.class);
        List<RoleMenuEntry> roleMenuEntryList = new ArrayList<>();
        if(menuNos != null && menuNos.size()>0){
            menuNos.forEach(menuNo -> {
                RoleMenuEntry roleMenuEntry = new RoleMenuEntry();
                roleMenuEntry.setRole(roleNo);
                roleMenuEntry.setMenuNo(menuNo);
                roleMenuEntryList.add(roleMenuEntry);
            });
        }
        if(roleMenuEntryList.size()>0){
            this.roleMenuService.deleteByRoleNo(roleNo);
            this.roleMenuService.saveBatch(roleMenuEntryList);
        }
        return success();
    }

    private Result getResult(@PathVariable String userId, String menuNo) {
        UserEntity user = this.userService.findOne(userId);
        if(user == null){
            return fail(HttpStatus.PARAMETER_ISNULL,null,"用户不存在");
        }
        String role = user.getRoleType();
        List<RoleMenuEntry> roleMenuEntryList = this.roleMenuService.findByRole(role);
        if(roleMenuEntryList==null || roleMenuEntryList.size() == 0) return success();
        List<MenuEntry> menuEntryList = this.menuService.findAll(roleMenuEntryList, menuNo);
        return success(menuEntryList);
    }
}
