package com.ruoyi.app.mendian;

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

import com.ruoyi.app.user.dto.StoreOutput;
import com.ruoyi.system.mapper.PosFoodMapper;
import jakarta.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.utils.MessageUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.ruoyi.common.annotation.Anonymous;
import com.ruoyi.system.domain.PosFood;
import com.ruoyi.system.domain.PosStore;
import com.ruoyi.system.service.IPosStoreService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PosCollect;
import com.ruoyi.system.service.IPosCollectService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * collectController
 *
 * @author ruoyi
 * @date 2023-06-21
 */
@RestController
@RequestMapping("/system/collect")
public class PosCollectController extends BaseController
{
    @Autowired
    private IPosCollectService posCollectService;
    @Autowired
    private IPosStoreService posStoreService;
    @Autowired
    private PosFoodMapper posFoodMapper;
    /**
     * 我的收藏门店列表
     */
    @Anonymous
    @Auth
    @GetMapping("/getcollectlist")
    public AjaxResult getcollectlist(@RequestHeader String token,
                                     @RequestParam Integer page,
                                     @RequestParam Integer size){
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        IPage<PosCollect> pageInput = new Page<>(page,size);
        QueryWrapper<PosCollect> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        IPage<PosCollect> list = posCollectService.page(pageInput,queryWrapper);
        List<PosCollect> pos = list.getRecords();

        // 收集所有门店ID（Integer类型）
        List<Long> storeIds = pos.stream()
                .map(PosCollect::getMdId)
                .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(x->x)
                    .collect(Collectors.toList());

            // 使用MyBatis Plus的Mapper方法，在数据库查询时就限制每个门店只返回6条商品
            List<PosFood> allFoods = posFoodMapper.selectFoodsByStoreIdsWithLimit(storeIdsLong, "3", 6);

            // 按门店ID分组（查询结果已经限制为每个门店最多6条）
            foodMap = allFoods.stream()
                    .collect(Collectors.groupingBy(food -> food.getMdid().intValue()));
        }

        // 转换为StoreOutput并设置每个门店的商品列表（每个门店最多6条）
        List<StoreOutput> storeOutputList = new ArrayList<>();
        for (PosCollect collect : pos) {
            PosStore store=posStoreService.getById(collect.getMdId());
            if(store!=null){
                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(list.getTotal());
        result.setRecords(storeOutputList);
        return success(result);
    }

    /**
     * 收藏或取消收藏门店
     */

    @Anonymous
    @Auth
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @GetMapping("/addcollect")
    public AjaxResult addcollect(@RequestHeader String token,@RequestParam Long mdid){
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        QueryWrapper<PosCollect> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        queryWrapper.eq("md_id",mdid);
        List<PosCollect> posCollect = posCollectService.list(queryWrapper);
        if(posCollect.isEmpty()){
            PosCollect collect = new PosCollect();
            collect.setUserId(Long.valueOf(id));
            collect.setMdId(mdid);
            posCollectService.saveOrUpdate(collect);
            return success(MessageUtils.message("no.collection.success"));
        }else {
            posCollectService.remove(queryWrapper);
//            posCollectService.removeById(posCollect.getId());
            return success(MessageUtils.message("no.collection.cancel"));
        }
    }

    /**
     * 查询collect列表
     */
    @PreAuthorize("@ss.hasPermi('system:collect:list')")
    @GetMapping("/list")
    public TableDataInfo list(PosCollect posCollect)
    {
        startPage();
        List<PosCollect> list = posCollectService.selectPosCollectList(posCollect);
        return getDataTable(list);
    }

    /**
     * 导出collect列表
     */
    @PreAuthorize("@ss.hasPermi('system:collect:export')")
    @Log(title = "collect", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PosCollect posCollect)
    {
        List<PosCollect> list = posCollectService.selectPosCollectList(posCollect);
        ExcelUtil<PosCollect> util = new ExcelUtil<PosCollect>(PosCollect.class);
        util.exportExcel(response, list, MessageUtils.message("no.export.excel.collection"));
    }

    /**
     * 获取collect详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:collect:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(posCollectService.selectPosCollectById(id));
    }

    /**
     * 新增collect
     */
    @PreAuthorize("@ss.hasPermi('system:collect:add')")
    @Log(title = "collect", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PosCollect posCollect)
    {
        return toAjax(posCollectService.insertPosCollect(posCollect));
    }

    /**
     * 修改collect
     */
    @PreAuthorize("@ss.hasPermi('system:collect:edit')")
    @Log(title = "collect", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PosCollect posCollect)
    {
        return toAjax(posCollectService.updatePosCollect(posCollect));
    }

    /**
     * 删除collect
     */
    @PreAuthorize("@ss.hasPermi('system:collect:remove')")
    @Log(title = "collect", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(posCollectService.deletePosCollectByIds(ids));
    }
}
