package com.ruoyi.app.user;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.alibaba.fastjson.JSONArray;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.PosStoreMapper;
import com.ruoyi.system.mapper.PosFoodMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.system.mapper.PosOrderMapper;
import com.ruoyi.app.user.dto.StoreOutput;
import org.springframework.beans.BeanUtils;

/**
 * 用户美食首页
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/user/index")
public class UserAppIndexController extends BaseController {

    @Autowired
    private IPosTypeService posTypeService;
    @Autowired
    private IPosFoodService posFoodService;
    @Autowired
    private IPosOrderService posOrderService;
    @Autowired
    private PosOrderMapper posOrderMapper;
    @Autowired
    private IFoodStatisticsService foodStatisticsService;

    @Autowired
    private PosStoreMapper posStoreMapper;
    @Autowired
    private PosFoodMapper posFoodMapper;
    @Autowired
    private IInfoUserService infoUserService;

    /**
     * 获取夜市列表
     * @return
     */
    @Anonymous
    @GetMapping("/getNightMarketList")
    public AjaxResult getNightMarketList(){
        LambdaQueryWrapper<InfoUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InfoUser::getUserType,"3");
        List<InfoUser> list = infoUserService.list(queryWrapper);
        List<Map<String,Object>> result = new ArrayList<>();
//        list.forEach(infoUser -> {
//            Map<String,Object> map = new JSONObject();
//            map.put("id",infoUser.getUserId());
//            map.put("name",infoUser.getUserName());
////            map.put("phone",infoUser.getPhone());
//            result.add(map);
//        });
        return success(list);
    }

    /**
     * 获取门店分页列表
     */
    @Anonymous
    @GetMapping("/getStoreList")
    public AjaxResult getFoodStoreList(@RequestParam String language,
                                       @RequestParam BigDecimal longitude,
                                        @RequestParam BigDecimal latitude,
                                        @RequestParam Integer page,
                                        @RequestParam(defaultValue = "0") Long flId) {
        List<PosStore> storeList = posStoreMapper.getjxStore(longitude,latitude,(page-1)*10,flId);
        int count = posStoreMapper.getjxStoreCount(longitude,latitude,flId);
        String lang="3";
        if ("zh-CN".equals(language)) {
            lang = "2";
        }
        if ("zh-TW".equals(language)) {
            lang = "3";
        }
        if ("en-US".equals(language)) {
            lang = "1";
        }
        
        // 收集所有门店ID（Integer类型）
        List<Integer> storeIds = storeList.stream()
                .map(PosStore::getId)
                .collect(Collectors.toList());
        
        // 使用MyBatis Plus一次性查询所有门店的商品（避免N+1查询问题）
        Map<Integer, List<PosFood>> foodMap = new java.util.HashMap<>();
        if (!storeIds.isEmpty()) {
            // 将Integer类型的门店ID转换为Long类型用于查询（因为mdid是Long类型）
            List<Long> storeIdsLong = storeIds.stream()
                    .map(Integer::longValue)
                    .collect(Collectors.toList());
            
            // 使用MyBatis Plus的Mapper方法，在数据库查询时就限制每个门店只返回6条商品
            List<PosFood> allFoods = posFoodMapper.selectFoodsByStoreIdsWithLimit(storeIdsLong, lang, 6);
            
            // 按门店ID分组（查询结果已经限制为每个门店最多6条）
            foodMap = allFoods.stream()
                    .collect(Collectors.groupingBy(food -> food.getMdid().intValue()));
        }
        
        // 转换为StoreOutput并设置每个门店的商品列表（每个门店最多6条）
        List<StoreOutput> storeOutputList = new ArrayList<>();
        for (PosStore store : storeList) {
            StoreOutput storeOutput = new StoreOutput();
            // 复制PosStore的所有属性
            BeanUtils.copyProperties(store, storeOutput);
            // 从分组结果中获取该门店的商品列表（已限制为最多6条）
            List<PosFood> foodList = foodMap.getOrDefault(store.getId(), new ArrayList<>());
            storeOutput.setFoodList(foodList);
            storeOutputList.add(storeOutput);
        }

        Page<StoreOutput> result = new Page<>(page, 10);
        result.setTotal(count);
        result.setRecords(storeOutputList);
        return success(result);
    }




}
