package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreStaffTitle;
import shop.alien.store.service.StoreStaffTitleService;
import shop.alien.store.util.CommonConstant;

/**
 * 员工标题Controller
 * 提供员工标题的增删改查接口
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"员工标题管理"})
@CrossOrigin
@RestController
@RequestMapping("/storeStaffTitle")
@RequiredArgsConstructor
public class StoreStaffTitleController {

    private final StoreStaffTitleService storeStaffTitleService;

    /**
     * 分页查询员工标题列表
     * <p>
     * 根据店铺ID查询员工标题列表，支持分页
     * 只返回未删除的记录
     * </p>
     *
     * @param page    分页页数，默认1，必须大于0
     * @param size    分页条数，默认10，必须大于0且不超过100
     * @param storeId 店铺ID，可选
     * @return 员工标题列表分页结果
     */
    @ApiOperation("分页查询员工标题列表")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页页数", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "Integer", paramType = "query", required = false)
    })
    @GetMapping("/query")
    public R<IPage<StoreStaffTitle>> queryStaffTitleList(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "storeId", required = false) Integer storeId) {
        log.info("查询员工标题列表，参数：page={}, size={}, storeId={}", page, size, storeId);

        try {
            // 参数校验
            if (page != null && page < 1) {
                log.warn("查询员工标题列表参数校验失败，分页页数无效：page={}", page);
                return R.fail("分页页数必须大于0");
            }
            if (size != null && size < 1) {
                log.warn("查询员工标题列表参数校验失败，分页条数无效：size={}", size);
                return R.fail("分页条数必须大于0");
            }
            if (size != null && size > CommonConstant.MAX_PAGE_SIZE) {
                log.warn("查询员工标题列表参数校验失败，分页条数超过最大值：size={}", size);
                return R.fail("分页条数不能超过" + CommonConstant.MAX_PAGE_SIZE);
            }

            // 规范化分页参数
            Integer normalizedPage = (page == null || page < 1) ? CommonConstant.DEFAULT_PAGE_NUM : page;
            Integer normalizedSize;
            if (size == null || size < 1) {
                normalizedSize = CommonConstant.DEFAULT_PAGE_SIZE;
            } else if (size > CommonConstant.MAX_PAGE_SIZE) {
                normalizedSize = CommonConstant.MAX_PAGE_SIZE;
            } else {
                normalizedSize = size;
            }

            // 调用服务层查询
            IPage<StoreStaffTitle> result = storeStaffTitleService.queryStaffTitleList(
                    normalizedPage, normalizedSize, storeId);

            log.info("查询员工标题列表成功，共{}条记录，当前页{}条",
                    result.getTotal(), result.getRecords() != null ? result.getRecords().size() : 0);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            log.warn("查询员工标题列表参数错误，错误信息：{}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("查询员工标题列表异常，异常信息：{}", e.getMessage(), e);
            return R.fail("查询员工标题列表失败，请稍后重试");
        }
    }

    /**
     * 新增员工标题
     * <p>
     * 新增员工标题，自动计算员工数量
     * </p>
     *
     * @param storeStaffTitle 员工标题信息
     * @return 新增结果
     */
    @ApiOperation("新增员工标题")
    @ApiOperationSupport(order = 2)
    @PostMapping("/createTitle")
    public R<String> addStaffTitle(@RequestBody StoreStaffTitle storeStaffTitle) {
        log.info("新增员工标题，参数：{}", storeStaffTitle);

        try {
            Integer result = storeStaffTitleService.addStaffTitle(storeStaffTitle);

            if (result > 0) {
                log.info("新增员工标题成功，id={}", storeStaffTitle.getId());
                return R.data("新增员工标题成功");
            } else {
                log.warn("新增员工标题失败，插入记录数为0");
                return R.fail("新增员工标题失败");
            }
        } catch (IllegalArgumentException e) {
            log.warn("新增员工标题参数错误，错误信息：{}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("新增员工标题异常，异常信息：{}", e.getMessage(), e);
            return R.fail("新增员工标题失败，请稍后重试");
        }
    }

    /**
     * 更新员工标题
     * <p>
     * 更新员工标题信息，自动重新计算员工数量
     * </p>
     *
     * @param storeStaffTitle 员工标题信息
     * @return 更新结果
     */
    @ApiOperation("更新员工标题")
    @ApiOperationSupport(order = 3)
    @PostMapping("/updateTitle")
    public R<String> updateStaffTitle(@RequestBody StoreStaffTitle storeStaffTitle) {
        log.info("更新员工标题，参数：{}", storeStaffTitle);

        try {
            Integer result = storeStaffTitleService.updateStaffTitle(storeStaffTitle);

            if (result > 0) {
                log.info("更新员工标题成功，id={}", storeStaffTitle.getId());
                return R.data("更新员工标题成功");
            } else {
                log.warn("更新员工标题失败，更新记录数为0，id={}", storeStaffTitle.getId());
                return R.fail("更新员工标题失败，记录不存在或已被删除");
            }
        } catch (IllegalArgumentException e) {
            log.warn("更新员工标题参数错误，错误信息：{}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("更新员工标题异常，id={}，异常信息：{}", storeStaffTitle.getId(), e.getMessage(), e);
            return R.fail("更新员工标题失败，请稍后重试");
        }
    }

    /**
     * 删除员工标题（逻辑删除）
     * <p>
     * 根据ID逻辑删除员工标题
     * </p>
     *
     * @param id 员工标题ID，必填，必须大于0
     * @return 删除结果
     */
    @ApiOperation("删除员工标题")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "员工标题ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/deleteTitle")
    public R<String> deleteStaffTitle(@RequestParam(value = "id") Integer id) {
        log.info("删除员工标题，参数：id={}", id);

        try {
            // 参数校验
            if (id == null || id <= 0) {
                log.warn("删除员工标题参数校验失败，ID无效：id={}", id);
                return R.fail("员工标题ID不能为空且必须大于0");
            }

            Integer result = storeStaffTitleService.deleteStaffTitle(id);

            if (result > 0) {
                log.info("删除员工标题成功，id={}", id);
                return R.data("删除员工标题成功");
            } else {
                log.warn("删除员工标题失败，删除记录数为0，id={}", id);
                return R.fail("删除员工标题失败，记录不存在或已被删除");
            }
        } catch (IllegalArgumentException e) {
            log.warn("删除员工标题参数错误，id={}，错误信息：{}", id, e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("删除员工标题异常，id={}，异常信息：{}", id, e.getMessage(), e);
            return R.fail("删除员工标题失败，请稍后重试");
        }
    }

    /**
     * 查询员工标题详情
     * <p>
     * 根据门店ID查询员工标题详细信息（一个门店只能有一个标题）
     * </p>
     *
     * @param storeId 门店ID，必填，必须大于0
     * @return 员工标题详情
     */
    @ApiOperation("查询员工标题详情")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/detail")
    public R<StoreStaffTitle> getStaffTitleDetail(@RequestParam(value = "storeId") Integer storeId) {
        log.info("查询员工标题详情，参数：storeId={}", storeId);

        try {
            // 参数校验
            if (storeId == null || storeId <= 0) {
                log.warn("查询员工标题详情参数校验失败，门店ID无效：storeId={}", storeId);
                return R.fail("门店ID不能为空且必须大于0");
            }

            StoreStaffTitle result = storeStaffTitleService.getStaffTitleDetail(storeId);

            if (result == null) {
                log.info("查询员工标题详情失败，记录不存在：storeId={}", storeId);
                return R.success("该门店还没有创建标题");
            }

            log.info("查询员工标题详情成功，storeId={}，id={}，标题名称={}", storeId, result.getId(), result.getTitleName());
            return R.data(result);
        } catch (IllegalArgumentException e) {
            log.warn("查询员工标题详情参数错误，storeId={}，错误信息：{}", storeId, e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("查询员工标题详情异常，storeId={}，异常信息：{}", storeId, e.getMessage(), e);
            return R.fail("查询员工标题详情失败，请稍后重试");
        }
    }
}

