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.PlayPersonnelWaiterInfoEntity;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelWaiterInfoEditAddInfoVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelWaiterInfoEditBaseInfoVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelWaiterInfoQueryVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelWaiterInfoReturnVo;
import com.starry.admin.modules.personnel.service.IPlayPersonnelWaiterInfoService;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserRoleService userRoleService;

    /**
     * 查询客服信息列表
     */
    @ApiOperation(value = "分页查询客服列表", notes = "分页查询客服信息列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = PlayPersonnelWaiterInfoReturnVo.class, responseContainer = "Page")})
    @PostMapping("/listByPage")
    public R listByPage(
            @ApiParam(value = "查询条件", required = true) @Validated @RequestBody PlayPersonnelWaiterInfoQueryVo vo) {
        IPage<PlayPersonnelWaiterInfoReturnVo> list = playClerkWaiterInfoService.selectByPage(vo);
        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 PlayPersonnelWaiterInfoEditAddInfoVo vo) {
        // 校验对应用户是否存在
        SysUserEntity sysUserEntity = sysUserService.selectUserById(vo.getSysUserId());
        // 校验当前用户是否已经是组长
        PlayPersonnelWaiterInfoEntity waiterInfoEntity = playClerkWaiterInfoService.selectByUserId(vo.getSysUserId());
        if (waiterInfoEntity != null) {
            throw new CustomException("当前账号已经是客服,无法重复添加");
        }

        PlayPersonnelWaiterInfoEntity entity = ConvertUtil.entityToVo(vo, PlayPersonnelWaiterInfoEntity.class);
        entity.setSysUserCode(sysUserEntity.getUserCode());
        entity.setAddTime(LocalDateTime.now());
        boolean success = playClerkWaiterInfoService.create(entity);
        if (success) {
            // 新建客服后，添加对应的用户角色权限
            userRoleService.addUserRole(vo.getSysUserId(), sysRoleService.selectByRoleKey("waiter").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 PlayPersonnelWaiterInfoEditBaseInfoVo vo) {

        // 校验对应用户是否存在
        SysUserEntity sysUserEntity = sysUserService.selectUserById(vo.getSysUserId());
        // 校验当前用户是否已经是组长
        PlayPersonnelWaiterInfoEntity waiterInfoEntity = playClerkWaiterInfoService.selectByUserId(vo.getSysUserId());
        if (waiterInfoEntity != null && !waiterInfoEntity.getId().equals(vo.getId())) {
            throw new CustomException("当前账号已经是客服,无法重复添加");
        }

        PlayPersonnelWaiterInfoEntity entity = ConvertUtil.entityToVo(vo, PlayPersonnelWaiterInfoEntity.class);
        entity.setSysUserCode(sysUserEntity.getUserCode());
        boolean success = playClerkWaiterInfoService.update(entity);
        if (success) {
            // 新建客服后，添加对应的用户角色权限
            userRoleService.addUserRole(vo.getSysUserId(), sysRoleService.selectByRoleKey("waiter").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) {
        Long ruleId = sysRoleService.selectByRoleKey("operator").getRoleId();
        for (String id : ids) {
            // 判断数据是否存在
            PlayPersonnelWaiterInfoEntity entity = playClerkWaiterInfoService.selectPlayClerkWaiterInfoById(id);
            // 删除客服
            playClerkWaiterInfoService.deletePlayClerkWaiterInfoById(id);
            // 删除对应的权限信息
            userRoleService.delUserRole(entity.getSysUserId(), ruleId);

        }
        return R.ok();
    }
}
