package shop.alien.store.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeClassManage;
import shop.alien.entity.store.LifeLikeRecord;
import shop.alien.entity.store.StoreImg;
import shop.alien.entity.store.StoreMenu;
import shop.alien.entity.store.vo.StoreMenuVo;
import shop.alien.mapper.LifeLikeRecordMapper;
import shop.alien.mapper.StoreMenuMapper;
import shop.alien.store.service.StoreImgService;
import shop.alien.store.service.StoreMenuService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 二期-门店推荐 服务实现类
 *
 * @author ssk
 * @since 2024-12-05
 */
@Service
@RequiredArgsConstructor
public class StoreMenuServiceImpl extends ServiceImpl<StoreMenuMapper, StoreMenu> implements StoreMenuService {

    private final StoreMenuMapper storeMenuMapper;

    private final LifeLikeRecordMapper lifeLikeRecordMapper;

    private final StoreImgService storeImgService;


    /**
     * 获取门店菜单
     *
     * @param storeId  门店id
     * @param dishType 菜品类型, 0:菜单, 1:推荐
     * @param phoneId  消息标识
     * @return list
     */
    @Override
    public List<StoreMenuVo> getStoreMenu(Integer storeId, Integer dishType, String phoneId) {

        if (dishType == 0) {
            List<StoreMenuVo> collect = storeMenuMapper.getStoreMenuList(storeId, null);
            return collect.stream().sorted(Comparator.comparing(StoreMenuVo::getSort)).collect(Collectors.toList());
        } else {
            List<StoreMenuVo> collect = storeMenuMapper.getStoreMenuList(storeId, dishType);
            collect.forEach(item -> {
                if (StringUtils.isNotEmpty(phoneId)) {
                    LambdaQueryWrapper<LifeLikeRecord> query = new LambdaQueryWrapper<>();
                    query.eq(LifeLikeRecord::getDianzanId, phoneId).eq(LifeLikeRecord::getHuifuId, item.getId());
                    Integer i = lifeLikeRecordMapper.selectCount(query);
                    if (i > 0) {
                        item.setIsLike(1);
                    } else {
                        item.setIsLike(0);
                    }
                }
            });
            return collect.stream().sorted(Comparator.comparing(StoreMenuVo::getSort)).collect(Collectors.toList());
        }
    }

    /**
     * 获取菜品详情
     *
     * @param id 菜品id
     * @return StoreMenuVo
     */
    @Override
    public StoreMenuVo getMenuInfo(Integer id) {
        return storeMenuMapper.getMenuInfo(id);
    }

    /**
     * 新增或修改门店菜品
     *
     * @param storeMenu
     * @return
     */
    @Override
    public R<String> saveOrUpdateMenu(StoreMenu storeMenu) {
        boolean flag = false;
        LambdaQueryWrapper<StoreMenu> storeMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //修改菜品
        if (storeMenu.getId() != null) {
            flag = this.updateById(storeMenu);
            if (!flag) {
                log.error("菜单修改失败");
                return R.fail("菜单修改失败");
            }
            return R.success("菜单修改成功");
        } else {//新增菜品
            if (StringUtils.isEmpty(storeMenu.getDishName())) {
                return R.fail("请输入菜品名称");
            }
            storeMenuLambdaQueryWrapper.eq(StoreMenu::getStoreId, storeMenu.getStoreId());
            List<StoreMenu> menuList = this.list(storeMenuLambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(menuList)) {
                int maxSort = menuList.stream().map(StoreMenu::getSort).reduce(Integer::max).get();
                storeMenu.setSort(maxSort + 1);
            } else {
                storeMenu.setSort(1);
            }
            //保存菜品
            flag = this.save(storeMenu);
            if (!flag) {
                return R.fail("菜品新增失败");
            }
        }
        return R.success("新增菜品成功");
    }

    /**
     * 新增或修改门店菜品new
     *
     * @param storeMenuVo
     * @return
     */
    @Override
    public R<String> saveOrUpdateMenus(StoreMenuVo storeMenuVo) {
        boolean flag = false;
        LambdaQueryWrapper<StoreMenu> storeMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        int imgId = 0;
        if (storeMenuVo.getImgId() == null || storeMenuVo.getImgId() == 0) {
            StoreImg storeImg = new StoreImg();
            storeImg.setStoreId(storeMenuVo.getStoreId());
            storeImg.setImgType(7);
            storeImg.setImgUrl(storeMenuVo.getImgUrl());
            storeImg.setImgDescription(storeMenuVo.getDishName());
            storeImgService.saveOrUpdate(storeImg);
            imgId = storeImg.getId();
        } else {
            imgId = storeMenuVo.getImgId();
        }

        // 封装storeMenu参数
        StoreMenu storeMenu = new StoreMenu();
        BeanUtils.copyProperties(storeMenuVo, storeMenu);
        storeMenu.setImgId(imgId);

        //修改菜品
        if (storeMenu.getId() != null) {
            flag = this.updateById(storeMenu);
            if (!flag) {
                log.error("菜单修改失败");
                return R.fail("菜单修改失败");
            }
            return R.success("菜单修改成功");
        } else {
            //新增菜品
            // 校验菜品参数
            if (StringUtils.isEmpty(storeMenu.getDishName())) {
                return R.fail("请输入菜品名称");
            }

            storeMenuLambdaQueryWrapper.eq(StoreMenu::getStoreId, storeMenu.getStoreId());
            List<StoreMenu> menuList = this.list(storeMenuLambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(menuList)) {
                int maxSort = menuList.stream().map(StoreMenu::getSort).reduce(Integer::max).get();
                storeMenu.setSort(maxSort + 1);
            } else {
                storeMenu.setSort(1);
            }
            //保存菜品
            flag = this.save(storeMenu);
            if (!flag) {
                return R.fail("菜品新增失败");
            }
        }
        return R.success("新增菜品成功");
    }


    /**
     * 菜品排序信息
     *
     * @param storeMenuVo
     * @return
     */
    @Override
    public Boolean getSortMenuInfo(StoreMenuVo storeMenuVo) {
        boolean flag = false;
        if (CollectionUtil.isNotEmpty(storeMenuVo.getSortList())) {
            for (int i = 0; i < storeMenuVo.getSortList().size(); i++) {
                LambdaQueryWrapper<StoreMenu> lambdaQueryWrapper = new LambdaQueryWrapper();
                lambdaQueryWrapper.eq(StoreMenu::getId, storeMenuVo.getSortList().get(i).getId());
                StoreMenu storeMenu = this.getOne(lambdaQueryWrapper);
                storeMenu.setSort(i + 1);
                flag = this.updateById(storeMenu);
            }
        }
        return flag;
    }

    @Override
    public Boolean saveMenuSort(List<StoreMenu> storeMenuList) {
        return this.updateBatchById(storeMenuList);
    }

    /**
     * 删除菜品或推荐菜 根据类型区分
     *
     * @param ids
     * @param dishType 0:菜品 1:推荐菜
     * @return
     */
    @Override
    public Boolean deleteMenu(List<Integer> ids, int dishType) {
        QueryWrapper<StoreMenu> queryWrapperMenu = new QueryWrapper<>();
        boolean flag = false;
        if (dishType == 0) {
            flag = this.removeByIds(ids);
        } else {
            queryWrapperMenu.in("id", ids);
            List<StoreMenu> storeMenuList = baseMapper.selectList(queryWrapperMenu);
            storeMenuList.forEach(item -> {
                item.setDishType(0);
                this.updateById(item);
            });
            flag = true;
        }
        return flag;
    }

    @Override
    public StoreMenuVo getMenuCountByStoreId(int storeId) {
        StoreMenuVo storeMenuVo = new StoreMenuVo();
        LambdaUpdateWrapper<StoreMenu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StoreMenu::getStoreId, storeId);
        updateWrapper.eq(StoreMenu::getDeleteFlag, 0);
        List<StoreMenu> storeMenuList = storeMenuMapper.selectList(updateWrapper);
        if (CollectionUtils.isNotEmpty(storeMenuList)) {
            storeMenuVo.setMenuCount(storeMenuList.size());
            Map<Integer, List<StoreMenu>> groupByDishType = storeMenuList.stream()
                    .collect(Collectors.groupingBy(StoreMenu::getDishType));
            List<StoreMenu> suggestList = groupByDishType.get(1);
            if (CollectionUtils.isNotEmpty(suggestList)) {
                storeMenuVo.setSuggestCount(suggestList.size());
            } else {
                storeMenuVo.setSuggestCount(0);
            }
        } else {
            storeMenuVo.setMenuCount(0);
            storeMenuVo.setSuggestCount(0);
        }
        return storeMenuVo;
    }

    /**
     * 获取用户对该菜品是否点赞
     *
     * @param userId 用户id
     * @param menuId 菜品id
     * @return boolean
     */
    @Override
    public boolean getMenuLikeStatus(String userId, Integer menuId) {
        return lifeLikeRecordMapper.selectCount(new QueryWrapper<LifeLikeRecord>().eq("dianzan_id", userId).eq("huifu_id", menuId).eq("delete_flag", 0)) > 0;
    }
}
