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.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.service.IPlayClerkUserInfoService;
import com.starry.admin.modules.personnel.module.entity.PlayPersonnelGroupInfoEntity;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoEditAddInfoVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoEditBaseInfoVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoQueryVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoReturnVo;
import com.starry.admin.modules.personnel.service.IPlayPersonnelGroupInfoService;
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 com.starry.common.utils.IdUtils;
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 java.util.List;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 店员分组信息Controller
 *
 * @author admin
 * @since 2024-05-31
 */
@Api(tags = "店员分组管理", description = "店员分组信息管理相关接口，包括查询、新增、修改和删除等操作")
@RestController
@RequestMapping("/personnel/group")
public class PlayPersonnelGroupInfoController {

    @Resource
    private IPlayPersonnelGroupInfoService playClerkGroupInfoService;

    @Resource
    private IPlayClerkUserInfoService playClerkUserInfoService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserRoleService userRoleService;

    /**
     * 查询店员分类信息列表
     */
    @ApiOperation(value = "分页查询分组列表", notes = "分页查询店员分组信息列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = PlayPersonnelGroupInfoReturnVo.class, responseContainer = "Page")})
    @PostMapping("/listByPage")
    public R listByPage(
            @ApiParam(value = "查询条件", required = true) @Validated @RequestBody PlayPersonnelGroupInfoQueryVo vo) {
        IPage<PlayPersonnelGroupInfoReturnVo> list = playClerkGroupInfoService.selectByPage(vo);
        for (PlayPersonnelGroupInfoReturnVo record : list.getRecords()) {
            List<PlayClerkUserInfoEntity> clerkUserInfoEntities = playClerkUserInfoService
                    .listAllByGroupId(record.getId());
            record.setTotalEmployeesNumber(clerkUserInfoEntities.size());
            Integer listingEmployeesNumber = 0;
            for (PlayClerkUserInfoEntity clerkUserInfoEntity : clerkUserInfoEntities) {
                if ("1".equals(clerkUserInfoEntity.getListingState())) {
                    listingEmployeesNumber++;
                }
            }
            record.setListingEmployeesNumber(listingEmployeesNumber);
        }
        return R.ok(list);
    }

    /**
     * 新增店员分组信息
     */
    @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 PlayPersonnelGroupInfoEditAddInfoVo vo) {
        // 校验对应用户是否存在
        SysUserEntity sysUserEntity = sysUserService.selectUserById(vo.getSysUserId());
        // 校验当前用户是否已经是组长
        PlayPersonnelGroupInfoEntity groupInfoEntity = playClerkGroupInfoService.selectByUserId(vo.getSysUserId());
        if (groupInfoEntity != null) {
            throw new CustomException("当前账号已经是组长,无法重复添加");
        }
        // 添加组长配置
        PlayPersonnelGroupInfoEntity entity = ConvertUtil.entityToVo(vo, PlayPersonnelGroupInfoEntity.class);
        entity.setId(IdUtils.getUuid());
        entity.setSysUserCode(sysUserEntity.getUserCode());
        entity.setAddTime(LocalDateTime.now());
        boolean success = playClerkGroupInfoService.create(entity);
        if (success) {
            // 新建组长后，添加对应的用户角色权限
            userRoleService.addUserRole(vo.getSysUserId(), sysRoleService.selectByRoleKey("leader").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 PlayPersonnelGroupInfoEditBaseInfoVo vo) {
        SysUserEntity sysUserEntity = sysUserService.selectUserById(vo.getSysUserId());
        // 校验当前用户是否已经是组长
        PlayPersonnelGroupInfoEntity groupInfoEntity = playClerkGroupInfoService.selectByUserId(vo.getSysUserId());
        // 校验当前用户是否已经是组长，只有当前用户不为组长时
        if (groupInfoEntity != null && !groupInfoEntity.getId().equals(vo.getId())) {
            throw new CustomException("当前账号已经是组长,无法重复添加");
        }
        PlayPersonnelGroupInfoEntity entity = ConvertUtil.entityToVo(vo, PlayPersonnelGroupInfoEntity.class);
        entity.setSysUserCode(sysUserEntity.getUserCode());
        boolean success = playClerkGroupInfoService.update(entity);
        if (success) {
            // 新建组长后，添加对应的用户角色权限
            userRoleService.addUserRole(vo.getSysUserId(), sysRoleService.selectByRoleKey("leader").getRoleId());
            return R.ok("成功");
        }
        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 = "操作成功"), @ApiResponse(code = 500, message = "删除失败，包含详细错误信息")})
    @Log(title = "店员分组信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        for (String id : ids) {
            List<PlayClerkUserInfoEntity> clerkUserInfoEntities = playClerkUserInfoService.listAllByGroupId(id);
            if (!clerkUserInfoEntities.isEmpty()) {
                throw new CustomException("分组中存在店员,禁止删除");
            }
        }
        Long ruleId = sysRoleService.selectByRoleKey("leader").getRoleId();
        for (String id : ids) {
            // 判断数据是否存在
            PlayPersonnelGroupInfoEntity entity = playClerkGroupInfoService.selectPlayClerkGroupInfoById(id);
            // 删除组长
            playClerkGroupInfoService.deletePlayClerkGroupInfoById(id);
            // 删除对应的权限信息
            userRoleService.delUserRole(entity.getSysUserId(), ruleId);

        }
        return R.ok();
    }
}
