package shop.alien.store.controller;

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.StoreMenu;
import shop.alien.entity.store.vo.StoreMenuVo;
import shop.alien.store.service.StoreMenuService;

import java.util.List;
import java.util.Map;

/**
 * 二期-门店菜单Controller
 *
 * @author ssk
 * @since 2024-12-05
 */
@Slf4j
@Api(tags = {"二期-门店菜单"})
@ApiSort(4)
@CrossOrigin
@RestController
@RequestMapping("/menu")
@RequiredArgsConstructor
public class StoreMenuController {

    private final StoreMenuService storeMenuService;

    @ApiOperation("获取门店菜单")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "dishType", value = "菜品类型, 0:非推荐, 1:推荐", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "phoneId", value = "用户手机号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dishMenuType", value = "菜单类型：1-菜单，2-酒水", dataType = "String", paramType = "query")
    })
    @GetMapping("/getMenuByStoreId")
    public R<List<StoreMenuVo>> getMenuByStoreId(
            @RequestParam(value = "storeId", required = true) Integer storeId,
            @RequestParam(value = "dishType", required = false) Integer dishType,
            @RequestParam(value = "phoneId", required = false) String phoneId,
            @RequestParam(value = "dishMenuType", required = false) Integer dishMenuType) {
        log.info("StoreMenuController.getMenuByStoreId?storeId={}&dishType={}&phoneId={}&dishMenuType={}",
                storeId, dishType, phoneId, dishMenuType);
        return R.data(storeMenuService.getStoreMenu(storeId, dishType, phoneId, dishMenuType));
    }

    @ApiOperation("新增或修改门店菜单")
    @ApiOperationSupport(order = 2)
    @PostMapping("/saveOrUpdate")
    public R<String> saveOrUpdate(@RequestBody StoreMenuVo storeMenuVo) {
        log.info("StoreRecommendController.saveOrUpdateMenu?storeMenu={}", storeMenuVo);
        return storeMenuService.saveOrUpdateMenus(storeMenuVo);
    }

    @ApiOperation(value = "删除门店菜单")
    @ApiOperationSupport(order = 3)
    @GetMapping("/delete")
    public R<String> delete(@RequestParam(value = "ids") List<Integer> ids, @RequestParam(value = "dishType") int dishType) {
        log.info("StoreRecommendController.delete?ids={}", ids);
        return storeMenuService.deleteMenu(ids, dishType);
    }

    @ApiOperation("获取菜品详情")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "菜品id", dataType = "Integer", paramType = "query")})
    @GetMapping("/getMenuInfo")
    public R<StoreMenuVo> getMenuInfo(Integer id) {
        log.info("StoreRecommendController.getMenuInfo?id={}", id);
        return R.data(storeMenuService.getMenuInfo(id));
    }

    @ApiOperation("菜品排序")
    @ApiOperationSupport(order = 5)
    @PostMapping("/getSortMenuInfo")
    public R<Boolean> getSortMenuInfo(@RequestBody StoreMenuVo storeMenuVo) {
        log.info("StoreRecommendController.getSortMenuInfo?storeMenuVo={}", storeMenuVo);
        Boolean flag = false;
        flag = storeMenuService.getSortMenuInfo(storeMenuVo);
        if (flag) {
            return R.success("已更新排序");
        } else {
            return R.fail("排序失败");
        }
    }

    @ApiOperation("保存菜品排序")
    @ApiOperationSupport(order = 6)
    @PostMapping("/saveMenuSort")
    public R<Boolean> saveMenuSort(@RequestBody List<StoreMenu> storeMenuList) {
        log.info("StoreRecommendController.saveMenuSort?storeMenuList={}", storeMenuList);
        Boolean flag = false;
        flag = storeMenuService.saveMenuSort(storeMenuList);
        if (flag) {
            return R.success("已更新排序");
        } else {
            return R.fail("排序失败");
        }
    }

    @ApiOperation("获取门店菜品推荐数量")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店id", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getMenuCountByStoreId")
    public R<StoreMenuVo> getMenuCountByStoreId(Integer storeId) {
        log.info("StoreRecommendController.getMenuCountByStoreId?id={}", storeId);
        return R.data(storeMenuService.getMenuCountByStoreId(storeId));
    }

    @ApiOperation("获取用户对该菜品是否点赞")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "menuId", value = "菜品id", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getMenuLikeStatus")
    public R<Boolean> getMenuLikeStatus(String userId, Integer menuId) {
        log.info("StoreRecommendController.getMenuLikeStatus?userId={}&menuId={}", userId, menuId);
        return R.data(storeMenuService.getMenuLikeStatus(userId, menuId));
    }


    /**
     * 获取菜单（用户端）
     * <p>
     * 根据门店ID获取菜单列表，支持按菜品类型、菜单类型筛选，并可查询用户点赞状态
     * 返回菜单列表以及按四种组合统计的数量：
     * 1. menu_all: dish_menu_type=1（菜单），dish_type=0（全部）
     * 2. menu_recommend: dish_menu_type=1（菜单），dish_type=1（推荐）
     * 3. drink_all: dish_menu_type=2（酒水），dish_type=0（全部）
     * 4. drink_recommend: dish_menu_type=2（酒水），dish_type=1（推荐）
     * </p>
     *
     * @param storeId      门店ID，必填，必须大于0
     * @param dishType     菜品类型，可选，0:非推荐, 1:推荐
     * @param phoneId      用户手机号，可选，用于查询点赞状态
     * @param dishMenuType 菜单类型，可选，1-菜单，2-酒水
     * @return 统一返回结果，包含菜单列表和统计信息（list:菜单列表，count:按四种组合统计的数量）
     * @throws IllegalArgumentException 当门店ID为空或小于等于0时抛出
     */
    @ApiOperation("获取菜单（用户端）")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "dishType", value = "菜品类型, 0:（推荐+非推荐）, 1:推荐", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "phoneId", value = "用户手机号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dishMenuType", value = "菜单类型：1-菜，2-酒，不传就是菜+酒（页面叫酒水）", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getClientMenuByStoreId")
    public R<Map<String, Object>> getClientMenuByStoreId(
            @RequestParam(value = "storeId", required = true) Integer storeId,
            @RequestParam(value = "dishType", required = false) Integer dishType,
            @RequestParam(value = "phoneId", required = true) String phoneId,
            @RequestParam(value = "dishMenuType", required = false) Integer dishMenuType) {
        // 记录请求入参
        log.info("获取用户端菜单，入参：storeId={}, dishType={}, phoneId={}, dishMenuType={}",
                storeId, dishType, phoneId, dishMenuType);

        // 参数校验
        if (storeId == null || storeId <= 0) {
            log.warn("获取用户端菜单失败，门店ID无效：storeId={}", storeId);
            return R.fail("门店ID不能为空且必须大于0");
        }

        try {
            // 调用服务层获取菜单列表和统计信息
            Map<String, Object> result = storeMenuService.getClientMenuByStoreId(
                    storeId, dishType, phoneId, dishMenuType);

            // 记录返回结果
            @SuppressWarnings("unchecked")
            List<StoreMenuVo> menuList = (List<StoreMenuVo>) result.get("list");
            log.info("获取用户端菜单成功，门店ID：{}，返回菜单数量：{}，统计信息：{}",
                    storeId, menuList != null ? menuList.size() : 0, result.get("count"));

            return R.data(result);
        } catch (Exception e) {
            log.error("获取用户端菜单异常，门店ID：{}，异常信息：{}", storeId, e.getMessage(), e);
            return R.fail("获取菜单失败：" + e.getMessage());
        }
    }

    @ApiOperation("获取门店菜单详情（用户端）")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "菜单ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "phoneId", value = "用户手机号", dataType = "String", paramType = "query")})
    @GetMapping("/getClientMenuInfoById")
    public R<StoreMenuVo> getClientMenuInfoById(@RequestParam(value = "id", required = true) Integer id,
                                                @RequestParam(value = "phoneId", required = true) String phoneId) {
        log.info("StoreRecommendController.getClientMenuInfoById?id={},phoneId={}", id, phoneId);
        return R.data(storeMenuService.getClientMenuInfoById(id, phoneId));
    }
}
