package com.ruoyi.app.nightmarket;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.mendian.PosStoreEnrichService;
import com.ruoyi.app.user.dto.StoreOutput;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.LocaleUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.InfoUserMapper;
import com.ruoyi.system.mapper.PosFoodMapper;
import com.ruoyi.system.mapper.PosStoreMapper;
import com.ruoyi.system.service.IPosCollectService;
import com.ruoyi.system.service.IPosOrderService;
import com.ruoyi.system.service.IPosReviewService;
import com.ruoyi.system.service.IPosStoreService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 用户端夜市摊位Controller
 */
@RestController
@RequestMapping("/nightMarketStore")
public class NightMarketStoreController extends BaseController {

    @Autowired
    private PosStoreMapper posStoreMapper;

    @Autowired
    private PosStoreEnrichService posStoreEnrichService;

    @Autowired
    private IPosStoreService posStoreService;

    @Autowired
    private IPosCollectService posCollectService;

    @Autowired
    private IPosOrderService posOrderService;

    @Autowired
    private IPosReviewService posReviewService;

    @Autowired
    private PosFoodMapper posFoodMapper;

    @Autowired
    private InfoUserMapper infoUserMapper;

    /**
     * 获取夜市列表（已审核通过，按距离排序）
     */
    @Anonymous
    @GetMapping("/getNightMarketList")
    public AjaxResult getNightMarketList(@RequestParam BigDecimal longitude,
                                          @RequestParam BigDecimal latitude) {
        List<InfoUser> list = infoUserMapper.selectNightMarketListByDistance(longitude, latitude);
        return success(list);
    }

    /**
     * 夜市摊位列表
     */
    @Anonymous
    @GetMapping("/nightMarkteStores")
    public AjaxResult nightMarkteStores(@RequestParam Long nightMarketId,
                                   @RequestParam(defaultValue = "1") Integer page,
                                   @RequestParam(required = false) String keyword,
                                   @RequestParam(defaultValue = "zh-TW", required = false) String language) {
        int offset = (page - 1) * 20;
        List<PosStore> list = posStoreMapper.getNightMarketStalls(nightMarketId, keyword, offset);
        posStoreEnrichService.enrichStoreList(list);
        int total = posStoreMapper.getNightMarketStallsCount(nightMarketId, keyword);
        Page<StoreOutput> result = posStoreEnrichService.buildStoreOutputPage(list, language, page, total);
        return success(result);
    }

    /**
     * 夜市关注的摊位列表
     */
    @Anonymous
    @Auth
    @GetMapping("/followed")
    public AjaxResult followedStores(@RequestHeader String token,
                                     @RequestParam Long nightMarketId,
                                     @RequestParam BigDecimal longitude,
                                     @RequestParam BigDecimal latitude,
                                     @RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "zh-TW", required = false) String language) {
        JwtUtil jwtUtil = new JwtUtil();
        String userId = jwtUtil.getusid(token);
        int offset = (page - 1) * 20;
        List<PosStore> list = posStoreMapper.getFollowedStalls(longitude, latitude, nightMarketId, Long.valueOf(userId), offset);
        posStoreEnrichService.enrichStoreList(list);
        Page<StoreOutput> result = posStoreEnrichService.buildStoreOutputPage(list, language, page, list.size());
        return success(result);
    }

    /**
     * 夜市常购的摊位列表
     */
    @Anonymous
    @Auth
    @GetMapping("/frequent")
    public AjaxResult frequentStores(@RequestHeader String token,
                                      @RequestParam Long nightMarketId,
                                      @RequestParam BigDecimal longitude,
                                      @RequestParam BigDecimal latitude,
                                      @RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "zh-TW", required = false) String language) {
        JwtUtil jwtUtil = new JwtUtil();
        String userId = jwtUtil.getusid(token);
        int offset = (page - 1) * 20;
        List<PosStore> list = posStoreMapper.getFrequentStalls(longitude, latitude, nightMarketId, Long.valueOf(userId), offset);
        posStoreEnrichService.enrichStoreList(list);
        Page<StoreOutput> result = posStoreEnrichService.buildStoreOutputPage(list, language, page, list.size());
        return success(result);
    }

    /**
     * 夜市摊位详情（含商品分类列表）
     */
    @Anonymous
    @GetMapping("/store/detail")
    public AjaxResult storeDetail(@RequestParam Long storeId,
                                   @RequestHeader(defaultValue = "") String token,
                                   @RequestParam(defaultValue = "zh-TW", required = false) String language) {
        PosStore store = posStoreService.getById(storeId);
        if (store == null || !"0".equals(store.getDelFlag()) || store.getIsStall() == null || store.getIsStall() != 1) {
            return error("摊位不存在");
        }

        boolean collected = false;
        if (token != null && !token.isEmpty()) {
            try {
                JwtUtil jwtUtil = new JwtUtil();
                String userId = jwtUtil.getusid(token);
                QueryWrapper<PosCollect> qw = new QueryWrapper<>();
                qw.eq("user_id", userId).eq("md_id", storeId);
                collected = posCollectService.count(qw) > 0;
            } catch (Exception ignored) {}
        }

        QueryWrapper<PosReview> reviewQw = new QueryWrapper<>();
        reviewQw.eq("md_id", storeId);
        List<PosReview> reviews = posReviewService.list(reviewQw);
        double rating = reviews.isEmpty() ? 4.5d :
                Math.round(reviews.stream().mapToDouble(PosReview::getScore).average().orElse(4.5d) * 2.0) / 2.0;

        QueryWrapper<PosOrder> orderQw = new QueryWrapper<>();
        orderQw.eq("md_id", storeId).apply("DATE_FORMAT(cretim,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m')");
        long monthlySales = posOrderService.count(orderQw);

        String langCode = LocaleUtils.toLangCode(language);
        List<PosFood> foods = posFoodMapper.selectFoodsByStoreId(storeId, langCode);

        JSONObject result = new JSONObject();
        result.put("id", store.getId());
        result.put("posName", store.getPosName());
        result.put("image", store.getImage());
        result.put("logo", store.getLogo());
        result.put("address", store.getAddress());
        result.put("longitude", store.getLongitude());
        result.put("latitude", store.getLatitude());
        result.put("briefIntroduction", store.getBriefIntroduction());
        result.put("telephone", store.getTelephone());
        result.put("openBusiness", store.getOpenBusiness());
        result.put("windingUp", store.getWindingUp());
        result.put("rating", rating);
        result.put("monthlySales", monthlySales);
        result.put("collected", collected ? 1 : 0);
        result.put("foodList", foods);
        result.put("nightMarketId", store.getNightMarketId());

        return success(result);
    }
}
