package cn.ibizlab.api.rest.extensions;

import cn.ibizlab.core.extensions.service.UAACoreService;
import cn.ibizlab.util.errors.BadRequestAlertException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;


@RestController
public class UAACoreResource {

    @Autowired
    private UAACoreService uaaCoreService;

    /**
     * 获取全部菜单列表和数据能力列表和统一资源列表
     *
     * @return
     */
    @GetMapping(value = "/sys_permissions/getallMenuAndPermissionAndUnires")
    public ResponseEntity<JSONArray> getallMenuAndPermissionAndUnires(@Validated @NotBlank(message = "roleid不允许为空")@RequestParam("roleid") String roleid) {
        JSONArray treeNode = new JSONArray();
        // 获取应用菜单
        treeNode.add(uaaCoreService.getAppMenu());
        // 获取数据能力
        treeNode.add(uaaCoreService.getDEOppriv());
        // 获取统一资源
        treeNode.add(uaaCoreService.getUnires());
        // 获取当前角色所有权限
        treeNode.add(uaaCoreService.getallPermissionByRoleid(roleid));

        return ResponseEntity.ok().body(treeNode);
    }


    /**
     * 删除当前角色的所有角色权限关系
     * @param param
     * @return
     */
    @PostMapping(value = "/sys_permissions/deleteRolePermissionByRoleid")
    public ResponseEntity<JSONObject> deleteRolePermissionByRoleid(@RequestBody JSONObject param) {
        JSONObject resObj = new JSONObject();
        String roleid = param.getString("roleid");
        if (StringUtils.isEmpty(roleid))
            new BadRequestAlertException("操作失败，未获取到当前角色标识!","","");
        uaaCoreService.clearRolePermissionByRoleid(roleid);

        return ResponseEntity.ok(resObj);
    }

    /**
     * 保存选中的权限信息
     * @param param
     * @return
     */
    @PostMapping(value = "/sys_permissions/saveRolePermissionByRoleid")
    public ResponseEntity<JSONObject> saveRolePermissionByRoleid(@RequestBody JSONObject param) {
        JSONObject resObj = new JSONObject();
        // 角色id
        String roleid = param.getString("roleid");
        if (StringUtils.isEmpty(roleid))
            new BadRequestAlertException("操作失败，未获取到当前角色标识!","","");
        // 选中的权限信息
        JSONArray checkedNodes = param.getJSONArray("checkedNodes");
        if (checkedNodes.size() > 0) {
            //　save操作
            uaaCoreService.saveRolePermissionByRoleid(roleid, checkedNodes);
        } else {
            new BadRequestAlertException("操作失败，未获取到选中数据!","","");
        }

        return ResponseEntity.ok(resObj);
    }

}
