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.StoreTable;
import shop.alien.entity.store.dto.BatchQueryTableStatusDTO;
import shop.alien.entity.store.dto.StoreTableChangeDTO;
import shop.alien.entity.store.dto.StoreTableDTO;
import shop.alien.entity.store.vo.StoreTableStatusVO;
import shop.alien.store.service.StoreTableService;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 桌号管理 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"商家端点餐管理-桌号管理"})
@ApiSort(13)
@CrossOrigin
@RestController
@RequestMapping("/storeTable")
@RequiredArgsConstructor
public class StoreTableController {

    private final StoreTableService storeTableService;

    @ApiOperationSupport(order = 1)
    @ApiOperation("分页查询桌号列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页容", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "状态（0:空闲, 1:就餐中, 2:其他）", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getTablePage")
    public R<IPage<StoreTable>> getTablePage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam Integer storeId,
            @RequestParam(required = false) Integer status) {
        log.info("StoreTableController.getTablePage?pageNum={}&pageSize={}&storeId={}&status={}", pageNum, pageSize, storeId, status);
        return R.data(storeTableService.getTablePage(pageNum, pageSize, storeId, status));
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation("查询桌号详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "桌号ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getTableDetail")
    public R<StoreTable> getTableDetail(@RequestParam Integer id) {
        log.info("StoreTableController.getTableDetail?id={}", id);
        StoreTable table = storeTableService.getById(id);
        if (table == null) {
            return R.fail("桌号不存在");
        }
        return R.data(table);
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation("批量创建桌号")
    @PostMapping("/batchCreateTables")
    public R<Boolean> batchCreateTables(@RequestBody StoreTableDTO dto) {
        log.info("StoreTableController.batchCreateTables?dto={}", dto);
        
        if (dto.getStoreId() == null || !StringUtils.hasText(dto.getTableNumbers())) {
            return R.fail("门店ID和桌号列表不能为空");
        }

        // 解析桌号列表
        List<String> tableNumberList = Arrays.stream(dto.getTableNumbers().split(","))
                .map(String::trim)
                .filter(StringUtils::hasText)
                .distinct()
                .collect(Collectors.toList());

        if (tableNumberList.isEmpty()) {
            return R.fail("桌号列表不能为空");
        }

        try {
            boolean result = storeTableService.batchCreateTables(dto.getStoreId(), tableNumberList);
            if (result) {
                return R.success("批量创建桌号成功");
            } else {
                return R.fail("批量创建桌号失败");
            }
        } catch (Exception e) {
            log.error("批量创建桌号失败", e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation("编辑桌号")
    @PostMapping("/updateTable")
    public R<Boolean> updateTable(@RequestBody StoreTableDTO dto) {
        log.info("StoreTableController.updateTable?dto={}", dto);
        
        if (dto.getId() == null || !StringUtils.hasText(dto.getTableNumber())) {
            return R.fail("桌号ID和桌号名称不能为空");
        }
        
        try {
            boolean result = storeTableService.updateTable(dto);
            if (result) {
                return R.success("更新桌号成功");
            } else {
                return R.fail("更新桌号失败");
            }
        } catch (Exception e) {
            log.error("更新桌号失败", e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation("删除桌号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "桌号ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/deleteTable")
    public R<Boolean> deleteTable(@RequestParam Integer id) {
        log.info("StoreTableController.deleteTable?id={}", id);
        
        try {
            boolean result = storeTableService.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("换桌")
    @PostMapping("/changeTable")
    public R<Boolean> changeTable(@RequestBody StoreTableChangeDTO dto) {
        log.info("StoreTableController.changeTable?dto={}", dto);
        
        if (dto.getOrderId() == null || dto.getFromTableId() == null || dto.getToTableId() == null) {
            return R.fail("订单ID、原桌号ID和目标桌号ID不能为空");
        }
        
        try {
            boolean result = storeTableService.changeTable(dto);
            if (result) {
                return R.success("换桌成功");
            } else {
                return R.fail("换桌失败");
            }
        } catch (Exception e) {
            log.error("换桌失败", e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperationSupport(order = 7)
    @ApiOperation("批量查询桌号状态")
    @PostMapping("/batchQueryTableStatus")
    public R<List<StoreTableStatusVO>> batchQueryTableStatus(@RequestBody BatchQueryTableStatusDTO dto) {
        log.info("StoreTableController.batchQueryTableStatus?dto={}", dto);
        
        if (dto.getTableIds() == null || dto.getTableIds().isEmpty()) {
            return R.fail("桌号ID列表不能为空");
        }
        
        try {
            List<StoreTableStatusVO> tables = storeTableService.batchQueryTableStatus(dto.getTableIds());
            return R.data(tables);
        } catch (Exception e) {
            log.error("批量查询桌号状态失败", e);
            return R.fail(e.getMessage());
        }
    }

}
