package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.DrinkInfo;
import shop.alien.entity.store.StoreImg;
import shop.alien.entity.store.StoreMenu;
import shop.alien.entity.store.vo.DrinkInfoVo;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.StoreMenuMapper;
import shop.alien.store.service.DrinkInfoService;

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

/**
 * 酒水餐食信息 服务实现类
 * 基于 store_menu 表实现
 * dish_menu_type: 1=餐食（菜单/菜品），2=酒水
 * 注意：drink_info 表已废弃，现在使用 store_menu 表
 *
 * @author ssk
 * @since 2025-06-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class DrinkInfoServiceImpl implements DrinkInfoService {

    private final StoreMenuMapper storeMenuMapper;
    private final StoreImgMapper storeImgMapper;
    
    /**
     * 菜单类型常量
     * 1 = 餐食（菜单/菜品）
     * 2 = 酒水
     */
    private static final String MENU_TYPE_FOOD = "1";
    private static final String MENU_TYPE_DRINK = "2";
    
    /**
     * 菜单图片类型
     */
    private static final Integer IMG_TYPE_MENU = 7;

    @Override
    public IPage<DrinkInfoVo> getDrinkInfoPage(int page, int size, Integer storeId, Integer type, String category, String name, Integer createUserId) {
        LambdaQueryWrapper<StoreMenu> queryWrapper = new LambdaQueryWrapper<>();
        
        // type 参数：1=餐食，2=酒水
        if (type != null) {
            queryWrapper.eq(StoreMenu::getDishMenuType, type.toString());
        } else {
            // 不传则查询所有（餐食和酒水）
            queryWrapper.in(StoreMenu::getDishMenuType, MENU_TYPE_FOOD, MENU_TYPE_DRINK);
        }
        
        // 筛选条件
        if (createUserId != null) {
            queryWrapper.eq(StoreMenu::getCreatedUserId, createUserId);
        }
        if (storeId != null) {
            queryWrapper.eq(StoreMenu::getStoreId, storeId);
        }
        if (category != null && !category.isEmpty()) {
            queryWrapper.eq(StoreMenu::getCategory, category);
        }
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(StoreMenu::getDishName, name);
        }
        // 按排序和创建时间倒序
        queryWrapper.orderByAsc(StoreMenu::getSort);
        queryWrapper.orderByDesc(StoreMenu::getCreatedTime);

        IPage<StoreMenu> menuPage = storeMenuMapper.selectPage(new Page<>(page, size), queryWrapper);
        // 转换为Vo
        IPage<DrinkInfoVo> drinkInfoVoPage = new Page<>(page, size);
        drinkInfoVoPage.setTotal(menuPage.getTotal());
        List<DrinkInfoVo> drinkInfoVoList = menuPage.getRecords().stream()
                .map(this::convertMenuToVo)
                .collect(Collectors.toList());
        drinkInfoVoPage.setRecords(drinkInfoVoList);

        return drinkInfoVoPage;
    }

    @Override
    public DrinkInfoVo getDrinkInfoById(Integer id) {
        StoreMenu menu = storeMenuMapper.selectById(id);
        // 验证是否为餐食或酒水类型
        if (menu == null || 
            (!MENU_TYPE_FOOD.equals(menu.getDishMenuType()) && !MENU_TYPE_DRINK.equals(menu.getDishMenuType()))) {
            return null;
        }
        return convertMenuToVo(menu);
    }

    @Override
    public boolean saveDrinkInfo(DrinkInfo drinkInfo) {
        // 转换为 StoreMenu 对象
        StoreMenu menu = new StoreMenu();
        menu.setStoreId(drinkInfo.getStoreId());
        menu.setDishName(drinkInfo.getName());
        menu.setDishPrice(drinkInfo.getPrice());
        menu.setCostPrice(drinkInfo.getCostPrice());
        // type: 1=餐食，2=酒水，默认为酒水
        menu.setDishMenuType(drinkInfo.getType() != null ? drinkInfo.getType().toString() : MENU_TYPE_DRINK);
        menu.setCategory(drinkInfo.getCategory());
        menu.setAlcoholVolume(drinkInfo.getAlcoholVolume() != null ? drinkInfo.getAlcoholVolume().toString() : "0");
        menu.setFlavor(drinkInfo.getFlavor());
        menu.setDescription(drinkInfo.getDescription());
        menu.setDishType(drinkInfo.getIsRecommended() != null ? drinkInfo.getIsRecommended() : 0);
        menu.setSort(drinkInfo.getSort() != null ? drinkInfo.getSort() : 0);
        menu.setDishesUnit("份");
        menu.setLikeCount(0);
        
        // 保存菜单
        int result = storeMenuMapper.insert(menu);
        
        // 如果有图片URL，保存到 store_img 表
        if (result > 0 && StringUtils.hasText(drinkInfo.getPicUrl())) {
            StoreImg img = new StoreImg();
            img.setStoreId(menu.getStoreId());
            img.setImgType(IMG_TYPE_MENU);
            img.setImgUrl(drinkInfo.getPicUrl());
            img.setBusinessId(menu.getId());
            String typeDesc = MENU_TYPE_DRINK.equals(menu.getDishMenuType()) ? "酒水" : "餐食";
            img.setImgDescription(typeDesc + "图片-" + menu.getDishName());
            img.setImgSort(1);
            storeImgMapper.insert(img);
            
            // 更新菜单的 img_id
            menu.setImgId(img.getId());
            storeMenuMapper.updateById(menu);
        }
        
        return result > 0;
    }

    @Override
    public boolean updateDrinkInfo(DrinkInfo drinkInfo) {
        if (drinkInfo.getId() == null) {
            return false;
        }
        
        // 验证是否为餐食或酒水类型
        StoreMenu existMenu = storeMenuMapper.selectById(drinkInfo.getId());
        if (existMenu == null || 
            (!MENU_TYPE_FOOD.equals(existMenu.getDishMenuType()) && !MENU_TYPE_DRINK.equals(existMenu.getDishMenuType()))) {
            log.warn("该商品不是餐食/酒水类型，无法修改");
            return false;
        }
        
        // 构建更新对象
        StoreMenu menu = new StoreMenu();
        menu.setId(drinkInfo.getId());
        if (StringUtils.hasText(drinkInfo.getName())) {
            menu.setDishName(drinkInfo.getName());
        }
        if (drinkInfo.getPrice() != null) {
            menu.setDishPrice(drinkInfo.getPrice());
        }
        if (drinkInfo.getCostPrice() != null) {
            menu.setCostPrice(drinkInfo.getCostPrice());
        }
        if (StringUtils.hasText(drinkInfo.getCategory())) {
            menu.setCategory(drinkInfo.getCategory());
        }
        if (drinkInfo.getAlcoholVolume() != null) {
            menu.setAlcoholVolume(drinkInfo.getAlcoholVolume().toString());
        }
        if (StringUtils.hasText(drinkInfo.getFlavor())) {
            menu.setFlavor(drinkInfo.getFlavor());
        }
        if (StringUtils.hasText(drinkInfo.getDescription())) {
            menu.setDescription(drinkInfo.getDescription());
        }
        if (drinkInfo.getIsRecommended() != null) {
            menu.setDishType(drinkInfo.getIsRecommended());
        }
        if (drinkInfo.getSort() != null) {
            menu.setSort(drinkInfo.getSort());
        }
        if (drinkInfo.getType() != null) {
            menu.setDishMenuType(drinkInfo.getType().toString());
        }
        
        // 处理图片更新
        if (StringUtils.hasText(drinkInfo.getPicUrl())) {
            // 删除旧图片
            if (existMenu.getImgId() != null) {
                storeImgMapper.deleteById(existMenu.getImgId());
            }
            
            // 保存新图片
            StoreImg img = new StoreImg();
            img.setStoreId(existMenu.getStoreId());
            img.setImgType(IMG_TYPE_MENU);
            img.setImgUrl(drinkInfo.getPicUrl());
            img.setBusinessId(drinkInfo.getId());
            String typeDesc = MENU_TYPE_DRINK.equals(existMenu.getDishMenuType()) ? "酒水" : "餐食";
            String dishName = menu.getDishName() != null ? menu.getDishName() : existMenu.getDishName();
            img.setImgDescription(typeDesc + "图片-" + dishName);
            img.setImgSort(1);
            storeImgMapper.insert(img);
            
            menu.setImgId(img.getId());
        }
        
        return storeMenuMapper.updateById(menu) > 0;
    }

    @Override
    public boolean deleteDrinkInfo(Integer id) {
        // 验证是否为餐食或酒水类型
        StoreMenu menu = storeMenuMapper.selectById(id);
        if (menu == null || 
            (!MENU_TYPE_FOOD.equals(menu.getDishMenuType()) && !MENU_TYPE_DRINK.equals(menu.getDishMenuType()))) {
            log.warn("该商品不是餐食/酒水类型，无法删除");
            return false;
        }
        
        // 逻辑删除（由 @TableLogic 自动处理）
        return storeMenuMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateStatus(Integer id, Integer status) {
        // 注意：store_menu 表有 status 字段了，但 StoreMenu 实体类暂未映射
        LambdaUpdateWrapper<StoreMenu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StoreMenu::getId, id)
                .in(StoreMenu::getDishMenuType, MENU_TYPE_FOOD, MENU_TYPE_DRINK);  // 允许修改餐食和酒水
        // TODO: 在 StoreMenu 实体类中添加 status 字段映射后启用
        // .set(StoreMenu::getStatus, status);
        return true;  // 暂时返回 true
    }

    @Override
    public boolean updateIsRecommended(Integer id, Integer isRecommended) {
        LambdaUpdateWrapper<StoreMenu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StoreMenu::getId, id)
                .eq(StoreMenu::getDishMenuType, MENU_TYPE_DRINK)  // 只支持酒水
                .set(StoreMenu::getDishType, isRecommended);
        return storeMenuMapper.update(null, updateWrapper) > 0;
    }

    @Override
    public boolean updateSort(Integer id, Integer sort) {
        LambdaUpdateWrapper<StoreMenu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StoreMenu::getId, id)
                .eq(StoreMenu::getDishMenuType, MENU_TYPE_DRINK)  // 只支持酒水
                .set(StoreMenu::getSort, sort);
        return storeMenuMapper.update(null, updateWrapper) > 0;
    }

    @Override
    public List<DrinkInfoVo> getDrinkInfoListByStoreId(Integer storeId, Integer type) {
        LambdaQueryWrapper<StoreMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoreMenu::getStoreId, storeId);
        
        // type 参数：2=酒水，3=餐食
        if (type != null) {
            queryWrapper.eq(StoreMenu::getDishMenuType, type.toString());
        } else {
            // 不传则查询所有（餐食和酒水）
            queryWrapper.in(StoreMenu::getDishMenuType, MENU_TYPE_FOOD, MENU_TYPE_DRINK);
        }
        
        queryWrapper.orderByAsc(StoreMenu::getSort);
        queryWrapper.orderByDesc(StoreMenu::getCreatedTime);

        List<StoreMenu> menuList = storeMenuMapper.selectList(queryWrapper);
        return menuList.stream()
                .map(this::convertMenuToVo)
                .collect(Collectors.toList());
    }

    @Override
    public List<DrinkInfoVo> getRecommendedList(Integer storeId, Integer createUserId) {
        LambdaQueryWrapper<StoreMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(StoreMenu::getDishMenuType, MENU_TYPE_FOOD, MENU_TYPE_DRINK)  // 查询餐食和酒水
                .eq(StoreMenu::getDishType, 1);  // 推荐
        
        // 只查询指定用户创建的商品
        if (createUserId != null) {
            queryWrapper.eq(StoreMenu::getCreatedUserId, createUserId);
        }
        
        if (storeId != null) {
            queryWrapper.eq(StoreMenu::getStoreId, storeId);
        }
        queryWrapper.orderByAsc(StoreMenu::getSort);
        queryWrapper.orderByDesc(StoreMenu::getCreatedTime);

        List<StoreMenu> menuList = storeMenuMapper.selectList(queryWrapper);
        return menuList.stream()
                .map(this::convertMenuToVo)
                .collect(Collectors.toList());
    }

    @Override
    public boolean batchUpdateSort(List<DrinkInfo> drinkInfoList) {
        if (drinkInfoList == null || drinkInfoList.isEmpty()) {
            return false;
        }
        try {
            for (DrinkInfo drinkInfo : drinkInfoList) {
                if (drinkInfo.getId() != null && drinkInfo.getSort() != null) {
                    LambdaUpdateWrapper<StoreMenu> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(StoreMenu::getId, drinkInfo.getId())
                            .in(StoreMenu::getDishMenuType, MENU_TYPE_FOOD, MENU_TYPE_DRINK)  // 支持餐食和酒水
                            .set(StoreMenu::getSort, drinkInfo.getSort());
                    storeMenuMapper.update(null, updateWrapper);
                }
            }
            return true;
        } catch (Exception e) {
            log.error("批量更新排序失败", e);
            return false;
        }
    }
    /**
     * 将 StoreMenu 转换为 DrinkInfoVo
     *
     * @param menu StoreMenu对象
     * @return DrinkInfoVo对象
     */
    private DrinkInfoVo convertMenuToVo(StoreMenu menu) {
        DrinkInfoVo vo = new DrinkInfoVo();
        vo.setId(menu.getId());
        vo.setName(menu.getDishName());
        vo.setPrice(menu.getDishPrice());
        vo.setCostPrice(menu.getCostPrice());
        // 转换类型为数字：1=餐食，2=酒水
        vo.setType(menu.getDishMenuType() != null ? Integer.parseInt(menu.getDishMenuType()) : 2);
        vo.setCategory(menu.getCategory());
        vo.setAlcoholVolume(menu.getAlcoholVolume() != null ? new java.math.BigDecimal(menu.getAlcoholVolume()) : java.math.BigDecimal.ZERO);
        vo.setFlavor(menu.getFlavor());
        vo.setDescription(menu.getDescription());
        vo.setIsRecommended(menu.getDishType());
        vo.setStoreId(menu.getStoreId());
        vo.setCreateUserId(menu.getCreatedUserId());
        vo.setUpdateUserId(menu.getUpdatedUserId());
        vo.setSort(menu.getSort());
        vo.setStatus(1);  // 默认上架
        vo.setCreateTime(menu.getCreatedTime());
        vo.setUpdateTime(menu.getUpdatedTime());
        
        // 获取图片URL
        if (menu.getImgId() != null) {
            StoreImg img = storeImgMapper.selectById(menu.getImgId());
            if (img != null) {
                vo.setPicUrl(img.getImgUrl());
            }
        }
        
        return vo;
    }
}
