package com.jeeplus.hotelorder.dish.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.hotelorder.dish.domain.HotelDish;
import com.jeeplus.hotelorder.dish.domain.HotelDishSpecGroup;
import com.jeeplus.hotelorder.dish.domain.HotelDishSpecOption;
import com.jeeplus.hotelorder.dish.mapper.HotelDishMapper;
import com.jeeplus.hotelorder.dish.mapper.HotelDishSpecGroupMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * 菜品规格组服务类
 * @author jeeplus
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class HotelDishSpecGroupService extends ServiceImpl<HotelDishSpecGroupMapper, HotelDishSpecGroup> {

    private static final Logger log = LoggerFactory.getLogger(HotelDishSpecGroupService.class);

    @Resource
    private HotelDishSpecGroupMapper hotelDishSpecGroupMapper;

    @Resource
    private HotelDishMapper hotelDishMapper;

    @Resource
    private HotelDishSpecOptionService hotelDishSpecOptionService;

    /**
     * 分页查询规格组
     * @param page 分页参数
     * @param specGroup 查询条件
     * @return 分页结果
     * @throws Exception 查询异常
     */
    public IPage<HotelDishSpecGroup> findPage(Page<HotelDishSpecGroup> page, HotelDishSpecGroup specGroup) throws Exception {
        // 处理菜品名称搜索（非DB字段，需先查菜品ID再过滤）
        String dishName = specGroup.getDishName();
        specGroup.setDishName(null); // 清除非DB字段，避免QueryWrapperGenerator处理
        QueryWrapper<HotelDishSpecGroup> queryWrapper = QueryWrapperGenerator.buildQueryCondition(specGroup, HotelDishSpecGroup.class);
        queryWrapper.eq("del_flag", 0);
        // 按菜品名称模糊搜索
        if (StringUtils.isNotBlank(dishName)) {
            QueryWrapper<HotelDish> dishQw = new QueryWrapper<>();
            dishQw.like("name", dishName).eq("del_flag", 0);
            List<HotelDish> dishes = hotelDishMapper.selectList(dishQw);
            if (dishes.isEmpty()) {
                // 没有匹配的菜品，返回空结果
                return new Page<>(page.getCurrent(), page.getSize(), 0);
            }
            List<String> matchedIds = new ArrayList<>();
            for (HotelDish dish : dishes) {
                matchedIds.add(dish.getId());
            }
            queryWrapper.in("dish_id", matchedIds);
        }
        queryWrapper.orderByAsc("sort_order");
        IPage<HotelDishSpecGroup> result = hotelDishSpecGroupMapper.selectPage(page, queryWrapper);
        // 填充菜品名称和选项列表
        fillDishName(result.getRecords());
        fillOptions(result.getRecords());
        return result;
    }

    /**
     * 根据菜品ID查询所有规格组（含选项）
     * @param dishId 菜品ID
     * @return 规格组列表（含选项）
     */
    public List<HotelDishSpecGroup> findByDishId(String dishId) {
        QueryWrapper<HotelDishSpecGroup> qw = new QueryWrapper<>();
        qw.eq("dish_id", dishId).eq("del_flag", 0).orderByAsc("sort_order");
        List<HotelDishSpecGroup> groups = hotelDishSpecGroupMapper.selectList(qw);
        // 填充每个规格组的选项列表
        for (HotelDishSpecGroup group : groups) {
            List<HotelDishSpecOption> options = hotelDishSpecOptionService.findByGroupId(group.getId());
            group.setOptions(options);
        }
        return groups;
    }

    /**
     * 根据ID查询规格组
     * @param id 规格组ID
     * @return 规格组信息
     */
    public HotelDishSpecGroup queryById(String id) {
        return hotelDishSpecGroupMapper.selectById(id);
    }

    /**
     * 保存规格组（新增/编辑）
     * @param specGroup 规格组信息
     * @return 操作结果
     */
    public String saveSpecGroup(HotelDishSpecGroup specGroup) {
        if (StringUtils.isBlank(specGroup.getId())) {
            specGroup.setId(UUID.randomUUID().toString().replace("-", ""));
            specGroup.setDelFlag(0);
            if (specGroup.getRequired() == null) {
                specGroup.setRequired(0);
            }
            if (specGroup.getSortOrder() == null) {
                specGroup.setSortOrder(0);
            }
            hotelDishSpecGroupMapper.insert(specGroup);
            log.info("新增规格组: {}", specGroup.getGroupName());
        } else {
            hotelDishSpecGroupMapper.updateById(specGroup);
            log.info("编辑规格组: {}", specGroup.getGroupName());
        }
        return "操作成功";
    }

    /**
     * 删除规格组（同时删除其下所有选项）
     * @param id 规格组ID
     */
    public void deleteSpecGroup(String id) {
        // 删除规格组
        hotelDishSpecGroupMapper.deleteById(id);
        // 删除关联的规格选项
        hotelDishSpecOptionService.deleteByGroupId(id);
        log.info("删除规格组及其选项: {}", id);
    }

    /**
     * 批量填充选项列表
     * @param groups 规格组列表
     */
    private void fillOptions(List<HotelDishSpecGroup> groups) {
        if (groups == null || groups.isEmpty()) {
            return;
        }
        for (HotelDishSpecGroup group : groups) {
            List<HotelDishSpecOption> options = hotelDishSpecOptionService.findByGroupId(group.getId());
            group.setOptions(options);
        }
    }

    /**
     * 批量填充菜品名称
     * @param groups 规格组列表
     */
    private void fillDishName(List<HotelDishSpecGroup> groups) {
        if (groups == null || groups.isEmpty()) {
            return;
        }
        // 收集所有菜品ID
        Set<String> dishIds = new HashSet<>();
        for (HotelDishSpecGroup group : groups) {
            if (StringUtils.isNotBlank(group.getDishId())) {
                dishIds.add(group.getDishId());
            }
        }
        if (dishIds.isEmpty()) {
            return;
        }
        // 批量查询菜品
        QueryWrapper<HotelDish> qw = new QueryWrapper<>();
        qw.in("id", dishIds).eq("del_flag", 0);
        List<HotelDish> dishes = hotelDishMapper.selectList(qw);
        Map<String, String> nameMap = new HashMap<>();
        for (HotelDish dish : dishes) {
            nameMap.put(dish.getId(), dish.getName());
        }
        // 填充名称
        for (HotelDishSpecGroup group : groups) {
            if (StringUtils.isNotBlank(group.getDishId())) {
                group.setDishName(nameMap.get(group.getDishId()));
            }
        }
    }
}
