package com.xhpc.system.controller;

import com.xhpc.common.core.utils.SecurityUtils;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.system.api.domain.SysRole;
import com.xhpc.system.domain.SysMenu;
import com.xhpc.system.domain.XhpcUserPrivilege;
import com.xhpc.system.domain.vo.TreeSelect;
import com.xhpc.system.service.ISysMenuService;
import com.xhpc.system.service.ISysRoleService;
import com.xhpc.system.service.IXhpcUserPrivilegeService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/user/privilege")
public class XhpcUserPrivilegeController extends BaseController {

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private IXhpcUserPrivilegeService iXhpcUserPrivilegeService;

    /**
     * 加载对应角色菜单列表树
     */
    //@PreAuthorize(hasPermi = "user:privilege:power")
    @GetMapping(value = "/power")
    public AjaxResult roleMenuTreeselect(@RequestParam Long userId) {
        Long SecurityUserId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(SecurityUserId);
        AjaxResult ajax = AjaxResult.success();
        SysRole sysRole = roleService.getRoleByUserID(userId);
        List<Integer> integers = new ArrayList<>();
        List<TreeSelect> treeSelectList = new ArrayList<>();
        if (null != sysRole) {
            integers = menuService.selectMenuListByRoleId(sysRole.getRoleId());
        }
        if (null != menus && menus.size() > 0) {
            treeSelectList = menuService.buildMenuTreeSelect(menus);
        }
        ajax.put("checkedKeys", integers);
        ajax.put("menus", treeSelectList);
        //选择用户拥有的数据权限
        ajax.put("dataCheckedKeys", iXhpcUserPrivilegeService.dataCheckedKeys(userId));
        //登录用户拥有的数据权限树
        //ajax.put("dataList", iXhpcUserPrivilegeService.dataList(SecurityUserId));
        return ajax;
    }
    /**
     * 新增数据权限
     */
    @ApiOperation("新增数据权限")
    //@PreAuthorize(hasPermi = "user:privilege:add")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody List<XhpcUserPrivilege> list) {
        if (null != list && list.size() > 0) {
            Long userId = list.get(0).getUserId();
            iXhpcUserPrivilegeService.deleteByIds(userId);
            for (XhpcUserPrivilege xhpcUserPrivilege : list) {
                if(xhpcUserPrivilege.getChargingStationId() !=null){
                    iXhpcUserPrivilegeService.insert(xhpcUserPrivilege);
                }
            }
        }
        return AjaxResult.success();
    }
}
