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

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
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.module.entity.PlayClerkUserQueryVo;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserReturnVo;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserTypeEditVo;
import com.starry.admin.modules.clerk.module.vo.PlayClerkUserEditVo;
import com.starry.admin.modules.clerk.module.vo.PlayClerkUserStateEditVo;
import com.starry.admin.modules.clerk.service.IPlayClerkUserInfoService;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.IPlayCustomUserInfoService;
import com.starry.admin.modules.weichat.entity.clerk.PlayClerkUserInfoQueryVo;
import com.starry.admin.modules.weichat.entity.clerk.PlayClerkUserInfoResultVo;
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.util.List;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 店员Controller
 *
 * @author admin
 * @since 2024-03-30
 */
@Api(tags = "店员管理", description = "店员信息管理相关接口，包括店员的增删改查、分类、分组以及状态管理等功能")
@RestController
@RequestMapping("/clerk/user")
public class PlayClerkUserInfoController {

    @Resource
    private IPlayCustomUserInfoService customUserInfoService;
    @Resource
    private IPlayClerkUserInfoService playClerkUserInfoService;

    /**
     * 查询店员列表
     */
    @ApiOperation(value = "分页查询店员列表", notes = "根据条件分页查询店员列表信息，支持多种筛选条件")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = PlayClerkUserReturnVo.class, responseContainer = "Page")})
    @PostMapping("listByPage")
    public R listByPage(@ApiParam(value = "查询条件", required = true) @Validated @RequestBody PlayClerkUserQueryVo vo) {
        IPage<PlayClerkUserReturnVo> list = playClerkUserInfoService.selectByPage(vo);
        return R.ok(list);
    }

    /**
     * 按照店员分类查询店员列表
     */
    @ApiOperation(value = "按分类查询店员列表", notes = "根据店员分类ID查询所有属于该分类的店员列表")
    @ApiImplicitParam(name = "id", value = "店员分类ID", required = true, paramType = "query", dataType = "String", example = "1")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = PlayClerkUserInfoEntity.class, responseContainer = "List")})
    @GetMapping("listAllByTypeId")
    public R listAllByTypeId(@RequestParam("id") String id) {
        List<PlayClerkUserInfoEntity> list = playClerkUserInfoService.listAllByTypeId(id);
        return R.ok(list);
    }

    /**
     * 按照店员分组查询店员列表
     */
    @ApiOperation(value = "按分组查询店员列表", notes = "根据店员分组ID查询所有属于该分组的店员列表")
    @ApiImplicitParam(name = "id", value = "店员分组ID", required = true, paramType = "query", dataType = "String", example = "1")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = PlayClerkUserInfoEntity.class, responseContainer = "List")})
    @GetMapping("listAllByGroupId")
    public R listAllByGroupId(@RequestParam("id") String id) {
        List<PlayClerkUserInfoEntity> list = playClerkUserInfoService.listAllByGroupId(id);
        return R.ok(list);
    }

    /**
     * 修改店员分类
     */
    @ApiOperation(value = "修改店员分类", notes = "将指定店员分配到指定分类中，会先清空该分类下所有店员，再重新分配")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = String.class)})
    @PostMapping("editClerkType")
    public R listByPage(
            @ApiParam(value = "店员分类修改参数", required = true) @Validated @RequestBody PlayClerkUserTypeEditVo vo) {
        // 先清空当前分类下店员
        List<PlayClerkUserInfoEntity> list = playClerkUserInfoService.listAllByTypeId(vo.getTypeId());
        for (PlayClerkUserInfoEntity clerkUserInfo : list) {
            PlayClerkUserInfoEntity entity = new PlayClerkUserInfoEntity();
            entity.setId(clerkUserInfo.getId());
            entity.setTypeId("");
            playClerkUserInfoService.update(entity);
        }
        for (String clerkUserId : vo.getClerkUserIds()) {
            PlayClerkUserInfoEntity entity = new PlayClerkUserInfoEntity();
            entity.setId(clerkUserId);
            entity.setTypeId(vo.getTypeId());
            playClerkUserInfoService.update(entity);
        }

        return R.ok("成功");
    }

    /**
     * 1、修改店员分组 2、将对应账号角色ID设为组长
     */
    @ApiOperation(value = "修改店员分组", notes = "将指定店员分配到指定分组中，会先清空该分组下所有店员，再重新分配，并可设置组长")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = String.class)})
    @PostMapping("editClerkGroup")
    public R editClerkGroup(
            @ApiParam(value = "店员分组修改参数", required = true) @Validated @RequestBody PlayClerkUserTypeEditVo vo) {
        // 先清空当前分类下店员
        List<PlayClerkUserInfoEntity> list = playClerkUserInfoService.listAllByGroupId(vo.getTypeId());
        for (PlayClerkUserInfoEntity clerkUserInfo : list) {
            PlayClerkUserInfoEntity entity = new PlayClerkUserInfoEntity();
            entity.setId(clerkUserInfo.getId());
            entity.setGroupId("");
            playClerkUserInfoService.update(entity);
        }
        for (String clerkUserId : vo.getClerkUserIds()) {
            PlayClerkUserInfoEntity entity = new PlayClerkUserInfoEntity();
            entity.setId(clerkUserId);
            entity.setGroupId(vo.getTypeId());
            playClerkUserInfoService.update(entity);
        }

        return R.ok("成功");
    }

    @ApiOperation(value = "获取简单列表", notes = "获取店员和客户的简单列表信息，用于下拉选择等场景")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = JSONObject.class)})
    @GetMapping("/simple/list")
    public R simpleList() {
        List<PlayClerkUserInfoEntity> clerkList = playClerkUserInfoService.simpleList();
        List<PlayCustomUserInfoEntity> customerList = customUserInfoService.simpleList();
        return R.ok(new JSONObject().fluentPut("clerkList", clerkList).fluentPut("customerList", customerList));
    }

    /**
     * 查询店员列表
     */
    @ApiOperation(value = "查询店员列表", notes = "分页查询店员信息列表，支持多种条件筛选，返回详细的店员信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = PlayClerkUserInfoResultVo.class, responseContainer = "Page")})
    @GetMapping("/list")
    public R list(@ApiParam(value = "查询条件") PlayClerkUserInfoQueryVo vo) {
        IPage<PlayClerkUserInfoResultVo> list = playClerkUserInfoService.selectPlayClerkUserInfoByPage(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 = PlayClerkUserInfoEntity.class)})
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") String id) {
        return R.ok(playClerkUserInfoService.selectById(id));
    }

    //
    // /**
    // * 微信端口新增店员
    // */
    // @Log(title = "店员", businessType = BusinessType.INSERT)
    // @PostMapping("/wx/add")
    // public R add(@Validated @RequestBody PlayClerkUserAddToWxVo vo) {
    // //微信申请成为店员，需要先创建账户。
    // PlayUserInfoEntity userInfoEntity = ConvertUtil.entityToVo(vo,
    // PlayUserInfoEntity.class);
    // userInfoEntity.setId(IdUtils.getUuid());
    // playUserInfoService.create(userInfoEntity);
    // //账号创建完成后，创建店员
    // PlayClerkUserInfoEntity clerkUserInfoEntity = ConvertUtil.entityToVo(vo,
    // PlayClerkUserInfoEntity.class);
    // clerkUserInfoEntity.setPlayUserId(userInfoEntity.getId());
    // boolean success = playClerkUserInfoService.create(clerkUserInfoEntity);
    // if (success) {
    // clerkCommodityService.initClerkCommodity(userInfoEntity.getId());
    // return R.ok();
    // }
    // return R.error("添加失败");
    // }

    // /**
    // * 新增店员
    // */
    // @Log(title = "店员", businessType = BusinessType.INSERT)
    // @PostMapping("/create")
    // public R create(@Validated @RequestBody PlayClerkUserAddVo vo) {
    // PlayClerkUserInfoEntity entity = ConvertUtil.entityToVo(vo,
    // PlayClerkUserInfoEntity.class);
    // boolean success = playClerkUserInfoService.create(entity);
    // if (success) {
    // clerkCommodityService.initClerkCommodity(vo.getPlayUserId());
    // return R.ok();
    // }
    // return R.error("添加失败");
    // }

    /**
     * 修改店员
     */
    // @PreAuthorize("@customSs.hasPermission('clerk:user:update')")
    @Log(title = "店员", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改店员信息", notes = "修改店员的基本信息，如昵称、头像、签名等")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "修改失败")})
    @PostMapping(value = "/update")
    public R update(@ApiParam(value = "店员信息", required = true) @Validated @RequestBody PlayClerkUserEditVo vo) {
        PlayClerkUserInfoEntity entity = ConvertUtil.entityToVo(vo, PlayClerkUserInfoEntity.class);
        if (StrUtil.isNotBlank(vo.getSex())) {
            throw new CustomException("性别修改需要提交资料审核");
        }
        boolean success = playClerkUserInfoService.update(entity);
        if (success) {
            return R.ok();
        }
        return R.error("修改失败");
    }

    /**
     * 修改店员状态
     */
    // @PreAuthorize("@customSs.hasPermission('clerk:user:update')")
    @Log(title = "店员", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改店员状态", notes = "修改店员的状态信息，如上下架状态、推荐状态、在线状态等")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "修改失败")})
    @PostMapping(value = "/updateState")
    public R updateState(
            @ApiParam(value = "店员状态信息", required = true) @Validated @RequestBody PlayClerkUserStateEditVo vo) {
        if (StrUtil.isNotBlank(vo.getSex())) {
            throw new CustomException("性别修改需要提交资料审核");
        }
        PlayClerkUserInfoEntity entity = ConvertUtil.entityToVo(vo, PlayClerkUserInfoEntity.class);
        boolean success = playClerkUserInfoService.update(entity);
        if (success) {
            return R.ok();
        }
        return R.error("修改失败");
    }

    /**
     * 删除店员
     */
    // @PreAuthorize("@customSs.hasPermission('clerk:user:remove')")
    @Log(title = "店员", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除店员", notes = "根据ID批量删除店员信息")
    @ApiImplicitParam(name = "ids", value = "店员ID数组", required = true, paramType = "path", dataType = "String[]", example = "1,2,3")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = Integer.class)})
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.ok(playClerkUserInfoService.deletePlayClerkUserInfoByIds(ids));
    }
}
