package cn.iocoder.yudao.module.system.service.dishestype;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.dishestype.vo.DishesTypeListRespVO;
import cn.iocoder.yudao.module.system.controller.admin.dishestype.vo.DishesTypePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.dishestype.vo.DishesTypeSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dishestype.DishesTypeDO;
import cn.iocoder.yudao.module.system.dal.dataobject.orderdetail.OrderDetail;
import cn.iocoder.yudao.module.system.dal.mysql.dishes.DishesMapper;
import cn.iocoder.yudao.module.system.dal.mysql.dishestype.DishesTypeMapper;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.system.enums.TimePeriodEnum;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 菜品分类 Service 实现类
 *
 * @author 开发账号
 */
@Service
@Validated
public class DishesTypeServiceImpl implements DishesTypeService {

    @Resource
    private DishesTypeMapper dishesTypeMapper;
    @Resource
    private DishesMapper dishesMapper;
    @Override
    public Long createDishesType(DishesTypeSaveReqVO createReqVO) {
        // 插入
        DishesTypeDO dishesType = BeanUtils.toBean(createReqVO, DishesTypeDO.class);
        dishesType.setDeleted(Boolean.FALSE);
        dishesTypeMapper.insert(dishesType);
        // 返回
        return dishesType.getId();
    }

    @Override
    public void updateDishesType(DishesTypeSaveReqVO updateReqVO) {
        // 校验存在
        validateDishesTypeExists(updateReqVO.getId());
        // 更新
        DishesTypeDO updateObj = BeanUtils.toBean(updateReqVO, DishesTypeDO.class);
        dishesTypeMapper.updateById(updateObj);
    }

    @Override
    public void deleteDishesType(Long id) {
        // 校验存在
        validateDishesTypeExists(id);
        // 删除
        dishesTypeMapper.deleteById(id);
    }

    private void validateDishesTypeExists(Long id) {
        if (dishesTypeMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstants.DISHES_TYPE_NOT_EXISTS);
        }
    }

    @Override
    public DishesTypeDO getDishesType(Long id) {
        return dishesTypeMapper.selectById(id);
    }

    @Override
    public PageResult<DishesTypeDO> getDishesTypePage(DishesTypePageReqVO pageReqVO) {
        return dishesTypeMapper.selectPage(pageReqVO);
    }

    /**
     * @param carteenId
     * @param startTime
     * @param endTime
     * @return
     * @Description: 通过门店编号 获得菜品分类以及菜品名称
     * @Author: qjq
     * @Date: 2024/4/15 下午3:13
     */
    @Override
    public List<DishesTypeListRespVO> getDishesTypeList(Long carteenId, LocalDateTime startTime, LocalDateTime endTime) {
        List<DishesTypeListRespVO> list=new ArrayList<>();
        //获取订单id
        List<Long> collect = dishesTypeMapper.selectOrderIds(carteenId, startTime, endTime);
        if(ObjUtil.isNotEmpty(collect)){
            List<OrderDetail> orderDetailDOS = dishesTypeMapper.selectByIdAmdTypeName(collect);
            orderDetailDOS.forEach(f-> f.setCreator(TimePeriodEnum.getTimePeriod(f.getCreateTime())));
            // 根据时间进行分组
            Map<String, List<OrderDetail>> map = orderDetailDOS.stream()
                    .collect(Collectors.groupingBy(OrderDetail::getCreator));
            for (Map.Entry<String, List<OrderDetail>> en : map.entrySet()) {
                DishesTypeListRespVO vo=new DishesTypeListRespVO();
                vo.setTime(en.getKey());
                //集合根据菜品名称去重
                List<OrderDetail> collect1 = new ArrayList<>(en.getValue().stream().collect(Collectors.toMap(
                        OrderDetail::getDishesName,
                        m -> m,
                        (oldValue, newValue) -> newValue
                )).values());
                //根据类型进行分组
                collect1.stream()
                        .collect(Collectors.groupingBy(OrderDetail::getDishUrl))
                        .forEach((v,k)-> {
                            Map<String, String> map1 = MapUtil.builder(new HashMap<String, String>())
                                    .put("dishesName", StrUtil.join(",",k.stream()
                                            .map(OrderDetail::getDishesName)
                                            .collect(Collectors.toList())))
                                    .put("typeName", v)
                                    .map();
                            vo.getDishesTypeName().add(map1);
                        });
                list.add(vo);
            }
            list.sort(Comparator.comparing(DishesTypeListRespVO::getTime));
        }
        return list;
    }

    @Override
    public List<DishesTypeDO> getList() {
        return dishesTypeMapper.selectList();
    }
}