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.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreBookingCategory;
import shop.alien.entity.store.dto.StoreBookingCategoryDTO;
import shop.alien.entity.store.dto.StoreBookingCategorySortDTO;
import shop.alien.store.service.StoreBookingCategoryService;

/**
 * 预订服务分类管理 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"预订服务-分类管理"})
@ApiSort(15)
@CrossOrigin
@RestController
@RequestMapping("/store/booking/category")
@RequiredArgsConstructor
public class StoreBookingCategoryController {

    private final StoreBookingCategoryService storeBookingCategoryService;

    @ApiOperationSupport(order = 1)
    @ApiOperation("查询预订服务分类列表（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "pageSize", value = "页容", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/list")
    public R<IPage<StoreBookingCategory>> getCategoryList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam Integer storeId) {
        log.info("StoreBookingCategoryController.getCategoryList?pageNum={}, pageSize={}, storeId={}", 
                pageNum, pageSize, storeId);
        
        if (storeId == null) {
            return R.fail("门店ID不能为空");
        }
        
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        
        try {
            IPage<StoreBookingCategory> page = storeBookingCategoryService.getCategoryListPage(pageNum, pageSize, storeId);
            return R.data(page);
        } catch (Exception e) {
            log.error("查询预订服务分类列表失败", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation("查询预订服务分类详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "分类ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/detail")
    public R<StoreBookingCategory> getCategoryDetail(@RequestParam Integer id) {
        log.info("StoreBookingCategoryController.getCategoryDetail?id={}", id);
        
        if (id == null) {
            return R.fail("分类ID不能为空");
        }
        
        try {
            StoreBookingCategory category = storeBookingCategoryService.getById(id);
            if (category == null) {
                return R.fail("分类不存在");
            }
            return R.data(category);
        } catch (Exception e) {
            log.error("查询预订服务分类详情失败", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation("新增预订服务分类")
    @PostMapping("/add")
    public R<StoreBookingCategory> addCategory(@RequestBody StoreBookingCategoryDTO dto) {
        log.info("StoreBookingCategoryController.addCategory?dto={}", dto);
        try {
            StoreBookingCategory category = new StoreBookingCategory();
            BeanUtils.copyProperties(dto, category);
            storeBookingCategoryService.addCategory(category);
        } catch (Exception e) {
            log.error("新增预订服务分类失败", e);
            // 如果是名称已存在的错误，直接返回友好提示
            return R.fail(e.getMessage());
        }
        return R.success("新增成功");
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation("编辑预订服务分类")
    @PostMapping("/update")
    public R<String> updateCategory(@RequestBody StoreBookingCategoryDTO dto) {
        log.info("StoreBookingCategoryController.updateCategory?dto={}", dto);
        
        if (dto.getId() == null) {
            return R.fail("分类ID不能为空");
        }
        
        try {
            StoreBookingCategory category = new StoreBookingCategory();
            category.setId(dto.getId());
            if (StringUtils.hasText(dto.getCategoryName())) {
                category.setCategoryName(dto.getCategoryName());
            }
            if (StringUtils.hasText(dto.getFloorPlanImages())) {
                category.setFloorPlanImages(dto.getFloorPlanImages());
            }
            if (dto.getIsDisplay() != null) {
                category.setIsDisplay(dto.getIsDisplay());
            }
            if (dto.getMaxBookingTime() != null) {
                category.setMaxBookingTime(dto.getMaxBookingTime());
            }
            if (dto.getSort() != null) {
                category.setSort(dto.getSort());
            }
            
            boolean result = storeBookingCategoryService.updateCategory(category);
            if (result) {
                return R.success("更新成功");
            } else {
                return R.fail("更新失败");
            }
        } catch (Exception e) {
            log.error("更新预订服务分类失败", e);
            // 如果是名称已存在的错误，直接返回友好提示
            if (e.getMessage() != null && e.getMessage().contains("此名称已存在")) {
                return R.fail("此名称已存在");
            }
            return R.fail("更新失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation("删除预订服务分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "分类ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/delete")
    public R<String> deleteCategory(@RequestParam Integer id) {
        log.info("StoreBookingCategoryController.deleteCategory?id={}", id);
        
        if (id == null) {
            return R.fail("分类ID不能为空");
        }
        
        try {
            boolean result = storeBookingCategoryService.deleteCategory(id);
            if (result) {
                return R.success("删除成功");
            } else {
                return R.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除预订服务分类失败", e);
            return R.fail("删除失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 6)
    @ApiOperation("更新预订服务分类排序")
    @PostMapping("/updateSort")
    public R<String> updateCategorySort(@RequestBody StoreBookingCategorySortDTO dto) {
        log.info("StoreBookingCategoryController.updateCategorySort?dto={}", dto);
        
        if (dto.getStoreId() == null || dto.getCategoryIds() == null || dto.getCategoryIds().isEmpty()) {
            return R.fail("门店ID和分类ID列表不能为空");
        }
        
        try {
            boolean result = storeBookingCategoryService.updateCategorySort(dto.getStoreId(), dto.getCategoryIds());
            if (result) {
                return R.success("更新排序成功");
            } else {
                return R.fail("更新排序失败");
            }
        } catch (Exception e) {
            log.error("更新预订服务分类排序失败", e);
            return R.fail("更新排序失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 7)
    @ApiOperation("设置预订服务分类显示状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "分类ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "isDisplay", value = "显示状态（0:隐藏, 1:显示）", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/updateDisplayStatus")
    public R<String> updateDisplayStatus(@RequestParam Integer id, @RequestParam Integer isDisplay) {
        log.info("StoreBookingCategoryController.updateDisplayStatus?id={}&isDisplay={}", id, isDisplay);
        
        if (id == null) {
            return R.fail("分类ID不能为空");
        }
        
        if (isDisplay == null) {
            return R.fail("显示状态不能为空");
        }
        
        if (isDisplay != 0 && isDisplay != 1) {
            return R.fail("显示状态值无效，必须为0（隐藏）或1（显示）");
        }
        
        try {
            boolean result = storeBookingCategoryService.updateDisplayStatus(id, isDisplay);
            if (result) {
                String message = isDisplay == 1 ? "设置显示成功" : "设置隐藏成功";
                return R.success(message);
            } else {
                return R.fail("更新显示状态失败");
            }
        } catch (Exception e) {
            log.error("更新预订服务分类显示状态失败", e);
            return R.fail("更新显示状态失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 8)
    @ApiOperation("查询分类下是否有预订信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/hasReservation")
    public R<Boolean> hasReservationInCategory(@RequestParam Integer categoryId, @RequestParam Integer storeId) {
        log.info("StoreBookingCategoryController.hasReservationInCategory?categoryId={}, storeId={}", categoryId, storeId);
        
        if (categoryId == null) {
            return R.fail("分类ID不能为空");
        }
        
        if (storeId == null) {
            return R.fail("门店ID不能为空");
        }
        
        try {
            boolean hasReservation = storeBookingCategoryService.hasReservationInCategory(categoryId, storeId);
            return R.data(hasReservation);
        } catch (Exception e) {
            log.error("查询分类下是否有预订信息失败", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }
}
