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.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreBookingTable;
import shop.alien.entity.store.dto.StoreBookingTableBatchDTO;
import shop.alien.entity.store.dto.StoreBookingTableDTO;
import shop.alien.entity.store.vo.StoreBookingTableVo;
import shop.alien.store.service.StoreBookingTableService;

import java.util.List;

/**
 * 预订服务桌号管理 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"预订服务-桌号管理"})
@ApiSort(16)
@CrossOrigin
@RestController
@RequestMapping("/store/booking/table")
@RequiredArgsConstructor
public class StoreBookingTableController {

    private final StoreBookingTableService storeBookingTableService;

    @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),
            @ApiImplicitParam(name = "categoryId", value = "分类ID（可选，不传则查询全部）", dataType = "Integer", paramType = "query", required = false)
    })
    @GetMapping("/list")
    public R<IPage<StoreBookingTableVo>> getTableList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam Integer storeId,
            @RequestParam(required = false) Integer categoryId) {
        log.info("StoreBookingTableController.getTableList?pageNum={}, pageSize={}, storeId={}, categoryId={}", 
                pageNum, pageSize, storeId, categoryId);
        
        if (storeId == null) {
            return R.fail("门店ID不能为空");
        }
        
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        
        try {
            IPage<StoreBookingTableVo> page = storeBookingTableService.getTableListPage(pageNum, pageSize, storeId, categoryId);
            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<StoreBookingTable> getTableDetail(@RequestParam Integer id) {
        log.info("StoreBookingTableController.getTableDetail?id={}", id);
        
        if (id == null) {
            return R.fail("桌号ID不能为空");
        }
        
        try {
            StoreBookingTable table = storeBookingTableService.getById(id);
            if (table == null) {
                return R.fail("桌号不存在");
            }
            return R.data(table);
        } catch (Exception e) {
            log.error("查询预订服务桌号详情失败", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation("新增预订服务桌号（支持批量添加）")
    @PostMapping("/add")
    public R<String> addTable(@RequestBody StoreBookingTableBatchDTO dto) {
        log.info("StoreBookingTableController.addTable?dto={}", dto);
        
        // 参数验证
        if (dto.getStoreId() == null) {
            return R.fail("门店ID不能为空");
        }
        if (dto.getCategoryId() == null) {
            return R.fail("分类ID不能为空");
        }
        if (dto.getTables() == null || dto.getTables().isEmpty()) {
            return R.fail("桌号列表不能为空");
        }
        
        try {
            // 转换为 StoreBookingTable 列表
            List<StoreBookingTable> tables = dto.getTables().stream()
                    .map(item -> {
                        StoreBookingTable table = new StoreBookingTable();
                        table.setTableNumber(item.getTableNumber());
                        table.setSeatingCapacity(item.getSeatingCapacity());
                        return table;
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            boolean result = storeBookingTableService.batchAddTables(dto.getStoreId(), dto.getCategoryId(), tables);
            if (result) {
                return R.success("新增成功");
            } else {
                return R.fail("新增失败");
            }
        } catch (Exception e) {
            log.error("新增预订服务桌号失败", e);
            // 如果是桌号已存在的错误，直接返回友好提示
            if (e.getMessage() != null && (e.getMessage().contains("该桌号已存在不能添加") || 
                e.getMessage().contains("以下桌号已存在不能添加"))) {
                return R.fail(e.getMessage());
            }
            return R.fail(e.getMessage());
        }
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation("编辑预订服务桌号")
    @PostMapping("/update")
    public R<String> updateTable(@RequestBody StoreBookingTableDTO dto) {
        log.info("StoreBookingTableController.updateTable?dto={}", dto);
        
        if (dto.getId() == null) {
            return R.fail("桌号ID不能为空");
        }
        
        try {
            StoreBookingTable table = new StoreBookingTable();
            table.setId(dto.getId());
            if (dto.getCategoryId() != null) {
                table.setCategoryId(dto.getCategoryId());
            }
            if (StringUtils.hasText(dto.getTableNumber())) {
                table.setTableNumber(dto.getTableNumber());
            }
            if (dto.getSeatingCapacity() != null) {
                table.setSeatingCapacity(dto.getSeatingCapacity());
            }
            
            boolean result = storeBookingTableService.updateTable(table);
            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> deleteTable(@RequestParam Integer id) {
        log.info("StoreBookingTableController.deleteTable?id={}", id);
        
        if (id == null) {
            return R.fail("桌号ID不能为空");
        }
        
        try {
            boolean result = storeBookingTableService.deleteTable(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("查询桌号下是否有预订信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tableId", value = "桌号ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/hasReservation")
    public R<Boolean> hasReservationInTable(@RequestParam Integer tableId, @RequestParam Integer storeId) {
        log.info("StoreBookingTableController.hasReservationInTable?tableId={}, storeId={}", tableId, storeId);
        
        if (tableId == null) {
            return R.fail("桌号ID不能为空");
        }
        
        if (storeId == null) {
            return R.fail("门店ID不能为空");
        }
        
        try {
            boolean hasReservation = storeBookingTableService.hasReservationInTable(tableId, storeId);
            return R.data(hasReservation);
        } catch (Exception e) {
            log.error("查询桌号下是否有预订信息失败", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

}
