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 com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.store.DrinkInfo;
import shop.alien.entity.store.vo.DrinkInfoVo;
import shop.alien.mapper.DrinkInfoMapper;
import shop.alien.store.service.DrinkInfoService;

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

/**
 * 酒水餐食信息表 服务实现类
 *
 * @author ssk
 * @since 2025-06-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class DrinkInfoServiceImpl extends ServiceImpl<DrinkInfoMapper, DrinkInfo> implements DrinkInfoService {

    private final DrinkInfoMapper drinkInfoMapper;

    @Override
    public IPage<DrinkInfoVo> getDrinkInfoPage(int page, int size, Integer storeId, String type, String category, String name, Integer createUserId) {
        LambdaQueryWrapper<DrinkInfo> queryWrapper = new LambdaQueryWrapper<>();
        // 软删除条件
        queryWrapper.eq(DrinkInfo::getIsDeleted, 0);
        // 筛选条件
        if (createUserId != null) {
            queryWrapper.eq(DrinkInfo::getCreateUserId, createUserId);
        }
        if (storeId != null) {
            queryWrapper.eq(DrinkInfo::getStoreId, storeId);
        }
        if (type != null && !type.isEmpty()) {
            queryWrapper.eq(DrinkInfo::getType, type);
        }
        if (category != null && !category.isEmpty()) {
            queryWrapper.eq(DrinkInfo::getCategory, category);
        }
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(DrinkInfo::getName, name);
        }
        // 按排序和创建时间倒序
        queryWrapper.orderByAsc(DrinkInfo::getSort);
        queryWrapper.orderByDesc(DrinkInfo::getCreateTime);

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

        return drinkInfoVoPage;
    }

    @Override
    public DrinkInfoVo getDrinkInfoById(Integer id) {
        DrinkInfo drinkInfo = drinkInfoMapper.selectById(id);
        if (drinkInfo == null || drinkInfo.getIsDeleted() == 1) {
            return null;
        }
        return convertToVo(drinkInfo);
    }

    @Override
    public boolean saveDrinkInfo(DrinkInfo drinkInfo) {
        // 设置默认值
        drinkInfo.setIsDeleted(0);
        drinkInfo.setStatus(1); // 默认上架
        drinkInfo.setSort(0); // 默认排序
        return this.save(drinkInfo);
    }

    @Override
    public boolean updateDrinkInfo(DrinkInfo drinkInfo) {
        return this.updateById(drinkInfo);
    }

    @Override
    public boolean deleteDrinkInfo(Integer id) {
        LambdaUpdateWrapper<DrinkInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DrinkInfo::getId, id)
                .set(DrinkInfo::getIsDeleted, 1);
        return this.update(updateWrapper);
    }

    @Override
    public boolean updateStatus(Integer id, Integer status) {
        LambdaUpdateWrapper<DrinkInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DrinkInfo::getId, id)
                .eq(DrinkInfo::getIsDeleted, 0)
                .set(DrinkInfo::getStatus, status);
        return this.update(updateWrapper);
    }

    @Override
    public boolean updateIsRecommended(Integer id, Integer isRecommended) {
        LambdaUpdateWrapper<DrinkInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DrinkInfo::getId, id)
                .eq(DrinkInfo::getIsDeleted, 0)
                .set(DrinkInfo::getIsRecommended, isRecommended);
        return this.update(updateWrapper);
    }

    @Override
    public boolean updateSort(Integer id, Integer sort) {
        LambdaUpdateWrapper<DrinkInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DrinkInfo::getId, id)
                .eq(DrinkInfo::getIsDeleted, 0)
                .set(DrinkInfo::getSort, sort);
        return this.update(updateWrapper);
    }

    @Override
    public List<DrinkInfoVo> getDrinkInfoListByStoreId(Integer storeId, String type) {
        LambdaQueryWrapper<DrinkInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DrinkInfo::getStoreId, storeId)
                .eq(DrinkInfo::getIsDeleted, 0)
                .eq(DrinkInfo::getStatus, 1); // 只查询上架的
        if (type != null && !type.isEmpty()) {
            queryWrapper.eq(DrinkInfo::getType, type);
        }
        queryWrapper.orderByAsc(DrinkInfo::getSort);
        queryWrapper.orderByDesc(DrinkInfo::getCreateTime);

        List<DrinkInfo> drinkInfoList = drinkInfoMapper.selectList(queryWrapper);
        return drinkInfoList.stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());
    }

    @Override
    public List<DrinkInfoVo> getRecommendedList(Integer storeId, Integer createUserId) {
        LambdaQueryWrapper<DrinkInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DrinkInfo::getIsRecommended, 1)
                .eq(DrinkInfo::getIsDeleted, 0)
                .eq(DrinkInfo::getStatus, 1); // 只查询上架的推荐商品
        
        // 只查询指定用户创建的商品
        if (createUserId != null) {
            queryWrapper.eq(DrinkInfo::getCreateUserId, createUserId);
        }
        
        if (storeId != null) {
            // 查询指定门店的商品，或者store_id为null的公共商品
            queryWrapper.and(wrapper -> wrapper.eq(DrinkInfo::getStoreId, storeId));
        }
        queryWrapper.orderByAsc(DrinkInfo::getSort);
        queryWrapper.orderByDesc(DrinkInfo::getCreateTime);

        List<DrinkInfo> drinkInfoList = drinkInfoMapper.selectList(queryWrapper);
        return drinkInfoList.stream()
                .map(this::convertToVo)
                .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<DrinkInfo> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(DrinkInfo::getId, drinkInfo.getId())
                            .eq(DrinkInfo::getIsDeleted, 0)
                            .set(DrinkInfo::getSort, drinkInfo.getSort());
                    this.update(updateWrapper);
                }
            }
            return true;
        } catch (Exception e) {
            log.error("批量更新排序失败", e);
            return false;
        }
    }

    @Override
    public java.util.Map<String, Long> getStatistics(Integer storeId) {
        LambdaQueryWrapper<DrinkInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DrinkInfo::getIsDeleted, 0)
                .eq(DrinkInfo::getStatus, 1); // 只统计上架的
        if (storeId != null) {
            queryWrapper.eq(DrinkInfo::getStoreId, storeId);
        }

        List<DrinkInfo> allList = drinkInfoMapper.selectList(queryWrapper);
        
        java.util.Map<String, Long> statistics = new java.util.HashMap<>();
        statistics.put("total", (long) allList.size());
        statistics.put("drink", allList.stream().filter(d -> "酒水".equals(d.getType())).count());
        statistics.put("food", allList.stream().filter(d -> "餐食".equals(d.getType())).count());
        statistics.put("recommended", allList.stream().filter(d -> d.getIsRecommended() == 1).count());
        
        return statistics;
    }

    @Override
    public boolean batchDelete(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        try {
            for (Integer id : ids) {
                deleteDrinkInfo(id);
            }
            return true;
        } catch (Exception e) {
            log.error("批量删除失败", e);
            return false;
        }
    }

    @Override
    public boolean batchUpdateStatus(List<Integer> ids, Integer status) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        try {
            for (Integer id : ids) {
                updateStatus(id, status);
            }
            return true;
        } catch (Exception e) {
            log.error("批量更新状态失败", e);
            return false;
        }
    }

    /**
     * 将DrinkInfo转换为DrinkInfoVo
     *
     * @param drinkInfo DrinkInfo对象
     * @return DrinkInfoVo对象
     */
    private DrinkInfoVo convertToVo(DrinkInfo drinkInfo) {
        DrinkInfoVo drinkInfoVo = new DrinkInfoVo();
        BeanUtils.copyProperties(drinkInfo, drinkInfoVo);
        // 确保图片字段正确映射
        drinkInfoVo.setPicUrl(drinkInfo.getPicUrl());
        return drinkInfoVo;
    }
}
