package com.starry.admin.modules.personnel.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.personnel.module.entity.PlayPersonnelAdminInfoEntity;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelAdminInfoEditAddInfoVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelAdminInfoEditBaseInfoVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelAdminInfoQueryVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelAdminInfoReturnVo;
import com.starry.admin.modules.personnel.service.IPlayPersonnelAdminInfoService;
import com.starry.admin.modules.system.module.entity.SysUserEntity;
import com.starry.admin.modules.system.service.SysRoleService;
import com.starry.admin.modules.system.service.SysUserRoleService;
import com.starry.admin.modules.system.service.SysUserService;
import com.starry.common.annotation.Log;
import com.starry.common.enums.BusinessType;
import com.starry.common.result.R;
import com.starry.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.time.LocalDateTime;
import javax.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 管理员管理Controller
 *
 * @author admin
 * @since 2024-06-14
 */
@Api(tags = "管理员管理", description = "管理员信息管理相关接口，包括查询、新增、修改和删除等操作")
@RestController
@RequestMapping("/personnel/admin")
public class PlayPersonnelAdminInfoController {
    @Resource
    private IPlayPersonnelAdminInfoService playPersonnelAdminInfoService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserRoleService userRoleService;

    /**
     * 查询管理员管理信息列表
     */
    @ApiOperation(value = "分页查询管理员列表", notes = "分页查询管理员信息列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = PlayPersonnelAdminInfoReturnVo.class, responseContainer = "Page")})
    @PostMapping("/listByPage")
    public R listByPage(
            @ApiParam(value = "查询条件", required = true) @Validated @RequestBody PlayPersonnelAdminInfoQueryVo vo) {
        IPage<PlayPersonnelAdminInfoReturnVo> list = playPersonnelAdminInfoService.selectByPage(vo);
        return R.ok(list);
    }

    /**
     * 获取管理员管理详细信息
     */
    @ApiOperation(value = "获取管理员详情", notes = "根据ID获取管理员详细信息")
    @ApiImplicitParam(name = "id", value = "管理员ID", required = true, paramType = "path", dataType = "String", example = "1")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = PlayPersonnelAdminInfoEntity.class)})
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") String id) {
        return R.ok(playPersonnelAdminInfoService.selectPlayPersonnelAdminInfoById(id));
    }

    /**
     * 新增管理员管理信息
     */
    @ApiOperation(value = "新增管理员信息", notes = "创建新的管理员信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "添加失败，包含详细错误信息")})
    @Log(title = "管理员管理信息", businessType = BusinessType.INSERT)
    @PostMapping("/createBaseInfo")
    public R createBaseInfo(
            @ApiParam(value = "管理员信息", required = true) @Validated @RequestBody PlayPersonnelAdminInfoEditAddInfoVo vo) {
        // 校验对应用户是否存在
        SysUserEntity sysUserEntity = sysUserService.selectUserById(vo.getSysUserId());
        // 校验当前用户是否已经是组长
        PlayPersonnelAdminInfoEntity groupInfoEntity = playPersonnelAdminInfoService.selectByUserId(vo.getSysUserId());
        if (groupInfoEntity != null) {
            throw new CustomException("当前账号已经是管理员,无法重复添加");
        }
        // 添加管理员
        PlayPersonnelAdminInfoEntity entity = ConvertUtil.entityToVo(vo, PlayPersonnelAdminInfoEntity.class);
        entity.setSysUserCode(sysUserEntity.getUserCode());
        entity.setAddTime(LocalDateTime.now());
        boolean success = playPersonnelAdminInfoService.create(entity);
        if (success) {
            // 新建管理员后，添加对应的用户角色权限
            userRoleService.addUserRole(vo.getSysUserId(), sysRoleService.selectByRoleKey("operator").getRoleId());
            return R.ok();
        }
        return R.error("添加失败");
    }

    /**
     * 修改管理员管理信息
     */
    @ApiOperation(value = "修改管理员信息", notes = "修改管理员基本信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "修改失败，包含详细错误信息")})
    @Log(title = "管理员管理信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/updateBaseInfo")
    public R updateBaseInfo(
            @ApiParam(value = "管理员信息", required = true) @Validated @RequestBody PlayPersonnelAdminInfoEditBaseInfoVo vo) {

        // 校验对应用户是否存在
        SysUserEntity sysUserEntity = sysUserService.selectUserById(vo.getSysUserId());
        // 校验当前用户是否已经是组长
        PlayPersonnelAdminInfoEntity adminInfoEntity = playPersonnelAdminInfoService.selectByUserId(vo.getSysUserId());
        if (adminInfoEntity != null && !adminInfoEntity.getId().equals(vo.getId())) {
            throw new CustomException("当前账号已经是管理员,无法重复添加");
        }
        PlayPersonnelAdminInfoEntity entity = ConvertUtil.entityToVo(vo, PlayPersonnelAdminInfoEntity.class);
        entity.setSysUserCode(sysUserEntity.getUserCode());
        boolean success = playPersonnelAdminInfoService.update(entity);
        if (success) {
            // 新建管理员后，添加对应的用户角色权限
            userRoleService.addUserRole(vo.getSysUserId(), sysRoleService.selectByRoleKey("operator").getRoleId());
        }
        return R.error("修改失败");
    }

    /**
     * 删除管理员管理
     */
    @ApiOperation(value = "删除管理员信息", notes = "根据ID批量删除管理员信息")
    @ApiImplicitParam(name = "ids", value = "管理员ID数组", required = true, paramType = "path", dataType = "String[]", example = "1,2,3")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("@customSs.hasPermission('play:info:remove')")
    @Log(title = "管理员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        Long ruleId = sysRoleService.selectByRoleKey("operator").getRoleId();
        for (String id : ids) {
            // 判断数据是否存在
            PlayPersonnelAdminInfoEntity entity = playPersonnelAdminInfoService.selectPlayPersonnelAdminInfoById(id);
            // 删除管理员
            playPersonnelAdminInfoService.deletePlayPersonnelAdminInfoById(id);
            // 删除对应的权限信息
            userRoleService.delUserRole(entity.getSysUserId(), ruleId);
        }
        return R.ok();
    }
}
