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

import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.clerk.module.entity.PlayClerkLevelInfoEntity;
import com.starry.admin.modules.clerk.module.vo.PlayClerkLevelAddVo;
import com.starry.admin.modules.clerk.module.vo.PlayClerkLevelEditVo;
import com.starry.admin.modules.clerk.service.IPlayClerkLevelInfoService;
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 org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 店员等级Controller
 *
 * @author admin
 * @since 2024-03-30
 */
@RestController
@RequestMapping("/clerk/level")
public class PlayClerkLevelInfoController {
    @Resource
    private IPlayClerkLevelInfoService playClerkLevelInfoService;

    /**
     * 查询店员等级列表
     */
    @GetMapping("/listAll")
    public R listAll() {
        return R.ok(playClerkLevelInfoService.selectAll());
    }

    /**
     * 获取店员等级详细信息
     */
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") String id) {
        return R.ok(playClerkLevelInfoService.selectPlayClerkLevelInfoById(id));
    }

    /**
     * 新增店员等级
     */
    @Log(title = "店员等级", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public R create(@RequestBody PlayClerkLevelAddVo vo) {
        PlayClerkLevelInfoEntity entity = ConvertUtil.entityToVo(vo, PlayClerkLevelInfoEntity.class);
        int level = playClerkLevelInfoService.selectMaxLevel();
        entity.setLevel(level + 1);
        boolean success = playClerkLevelInfoService.create(entity);
        if (success) {
            return R.ok();
        }
        return R.error("添加失败");
    }

    /**
     * 修改店员等级
     */
    @Log(title = "店员等级", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update")
    public R update(@Validated @RequestBody PlayClerkLevelEditVo vo) {
        PlayClerkLevelInfoEntity entity = ConvertUtil.entityToVo(vo, PlayClerkLevelInfoEntity.class);
        boolean success = playClerkLevelInfoService.update(entity);
        if (success) {
            return R.ok();
        }
        return R.error("修改失败");
    }

    /**
     * 删除店员等级
     */
    @Log(title = "店员等级", businessType = BusinessType.DELETE)
    @DeleteMapping("delMaxLevel")
    public R remove() {
        int level = playClerkLevelInfoService.selectMaxLevel();
        if (level <= 1) {
            throw new CustomException("最后一级,不允许删除");
        }
        playClerkLevelInfoService.delMaxLevelByLevel(level);
        return R.ok();
    }
}
