package com.cm.common.plugin.oauth.controller.apis.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cm.common.annotation.CheckRequestBodyAnnotation;
import com.cm.common.base.AbstractController;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.ParamsException;
import com.cm.common.exception.SearchException;
import com.cm.common.exception.UpdateException;
import com.cm.common.plugin.oauth.service.user.IUserService;
import com.cm.common.plugin.pojo.bos.UserResourceBO;
import com.cm.common.pojo.ListPage;
import com.cm.common.result.ErrorResult;
import com.cm.common.result.SuccessResult;
import com.cm.common.result.SuccessResultList;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: UserController
 * @Description: 用户
 * @Author: WangGeng
 * @Date: 2019-07-29 21:30
 * @Version: 1.0
 **/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "用户管理")
@RestController
@RequestMapping(ISystemConstant.API_PREFIX + "/user")
public class UserController extends AbstractController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "部门人员列表", notes = "部门人员列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentId", value = "部门ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listdepartmentusers/{departmentId}")
    public JSONArray listDepartmentUsers(@PathVariable("departmentId") String departmentId) throws AccessTokenException, SearchException {
        Map<String, Object> params = getParams();
        params.put("departmentId", departmentId);
        return userService.listDepartmentUsers(params);
    }

    @ApiOperation(value = "角色人员列表", notes = "角色人员列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listroleusers/{roleId}")
    public JSONArray listRoleUsers(@PathVariable("roleId") String roleId) throws SearchException, AccessTokenException {
        Map<String, Object> params = getParams();
        params.put("roleId", roleId);
        return userService.listRoleUsers(params);
    }

    @ApiOperation(value = "组人员列表", notes = "组人员列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "组ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listgroupusers/{groupId}")
    public JSONArray listGroupUsers(@PathVariable("groupId") String groupId) throws SearchException, AccessTokenException {
        Map<String, Object> params = getParams();
        params.put("groupId", groupId);
        return userService.listGroupUsers(params);
    }

    @ApiOperation(value = "职位人员列表", notes = "职位人员列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "positionId", value = "职位ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpositionusers/{groupId}")
    public JSONArray listPositionUsers(@PathVariable("positionId") String positionId) throws SearchException, AccessTokenException {
        Map<String, Object> params = getParams();
        params.put("positionId", positionId);
        return userService.listPositionUsers(params);
    }

    @ApiOperation(value = "全部用户列表", notes = "全部用户列表接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listallusers")
    public JSONArray listAllUsers() throws AccessTokenException, SearchException {
        Map<String, Object> params = getParams();
        return userService.listAllUsers(params);
    }

    @ApiOperation(value = "获取用户所在部门用户列表（通过角色）", notes = "获取用户所在部门用户列表（通过角色）接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "path"),
            @ApiImplicitParam(name = "roleId", value = "角色ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listuserdepartmentuserbyrole/{userId}/{roleId}")
    public JSONArray listUserDepartmentUserByRole(@PathVariable("userId") String userId, @PathVariable("roleId") String roleId) throws SearchException, AccessTokenException {
        Map<String, Object> params = getParams();
        params.put("userId", userId);
        params.put("roleId", roleId);
        return userService.listUserDepartmentUserByRole(params);
    }

    @ApiOperation(value = "获取用户所在部门用户列表（通过职位）", notes = "获取用户所在部门用户列表（通过职位）接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "path"),
            @ApiImplicitParam(name = "positionId", value = "职位ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listuserdepartmentuserbyposition/{userId}/{positionId}")
    public JSONArray listUserDepartmentUserByPosition(@PathVariable("userId") String userId, @PathVariable("positionId") String positionId) throws SearchException, AccessTokenException {
        Map<String, Object> params = getParams();
        params.put("userId", userId);
        params.put("positionId", positionId);
        return userService.listUserDepartmentUserByPosition(params);
    }

    @ApiOperation(value = "用户详情", notes = "用户详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "path"),
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("getuserdetail/{userId}")
    public JSONObject getUserDetail(@PathVariable("userId") String userId) throws SearchException, AccessTokenException {
        Map<String, Object> params = getParams();
        params.put("userId", userId);
        return userService.getUserDetail(params);
    }

    @ApiOperation(value = "获取密码状态", notes = "获取密码状态接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("getpasswordstatus")
    public JSONObject getPasswordStatus() {
        return userService.getPasswordStatus();
    }

    @ApiOperation(value = "修改密码", notes = "修改密码接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("updateuserpassword")
    @CheckRequestBodyAnnotation
    public SuccessResult updateUserPassword(@RequestBody Map<String, Object> params) throws ParamsException, SearchException, UpdateException {
        return userService.updateUserPassword(params);
    }

    @ApiOperation(value = "通过用户和部门ID列表获取部门用户列表", notes = "通过用户和部门ID列表获取部门用户列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "selectedUsers", value = "用户和部门ID列表", paramType = "body")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("listdepartmentuserbyuserdepartmentid")
    public JSONArray listDepartmentUserByUserDepartmentId(@RequestBody JSONObject params) {
        JSONArray selectedUsers = params.getJSONArray("selectedUsers");
        if (selectedUsers == null || selectedUsers.isEmpty()) {
            throw new ParamsException("参数列表不能为空");
        }
        return userService.listDepartmentUserByUserDepartmentId(params);
    }

    @ApiOperation(value = "用户列表（简单格式）", notes = "用户列表（简单格式）接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "rows", value = "显示数量", paramType = "query", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpageusersimple")
    public SuccessResultList<List<UserResourceBO>> listPageUserSimple() {
        Map<String, Object> params = requestParams();
        return userService.listPageUserSimple(params);
    }

    @ApiOperation(value = "组织部门人员列表", notes = "组织部门人员列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentId", value = "部门ID", paramType = "path"),
            @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listselectdepartmentuser/{departmentId}")
    public JSONArray listSelectDepartmentUser(@PathVariable("departmentId") String departmentId) throws SearchException {
        return userService.listSelectDepartmentUser(departmentId);
    }

    @ApiOperation(value = "组织部门人员分页列表", notes = "组织部门人员分页列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentId", value = "部门ID", paramType = "path"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "rows", value = "显示数量", paramType = "query", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpageselectdepartmentuser/{departmentId}")
    public JSONObject listPageSelectDepartmentUser(@PathVariable("departmentId") String departmentId, ListPage page) throws SearchException {
        Map<String, Object> params = requestParams();
        page.setParams(params);
        return userService.listPageSelectDepartmentUserByDepartmentId(departmentId, page);
    }

    @ApiOperation(value = "通过ID列表获取用户列表", notes = "通过ID列表获取用户列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userIds", value = "用户ID列表，用下划线分隔，如：1_2_3", paramType = "body")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("listuserbyids")
    public JSONArray listUserByIds(@RequestBody Map<String, Object> params) throws SearchException, ParamsException {
        if (params.get("selectedUserIds") == null || StringUtils.isBlank(params.get("selectedUserIds").toString())) {
            throw new ParamsException("用户列表不能为空");
        }
        params.put("userIds", params.get("selectedUserIds"));
        params.remove("selectedUserIds");
        return userService.listUserByIds(params);
    }

}