package shop.alien.store.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreImg;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.StoreInfoVo;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.store.annotation.TrackEvent;
import shop.alien.store.service.CommonRatingService;
import shop.alien.store.service.CommonRatingService;
import shop.alien.store.service.StoreImgService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

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


@Slf4j
@Api(tags = {"ai搜索"})
@CrossOrigin
@RestController
@RequestMapping("/aiSearch")
@RequiredArgsConstructor
@RefreshScope
public class AiSearchController {

    private final StoreImgMapper storeImgMapper;
    
    @Value("${third-party-ai-search.exact.base-url:http://124.93.18.180:7870/api/v1/search}")
    private String aiSearchExactUrl;
    
    @Value("${third-party-ai-search.fuzzy.base-url:http://124.93.18.180:7869/api/v1/search}")
    private String aiSearchFuzzyUrl;

    private final RestTemplate restTemplate;
    private final StoreImgService storeImgService;
    private final CommonRatingService commonRatingService;

    @TrackEvent(
            eventType = "SEARCH",
            eventCategory = "TRAFFIC",
            storeId = "",
            targetType = "STORE"
    )
    @RequestMapping("/search")
    public R search(@RequestBody Map<String,String> map) {


        // 初始化请求体Map
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("query", map.get("storeName"));
        requestBody.put("limit", map.get("pageSize"));
        requestBody.put("user_lat", map.get("lat"));
        requestBody.put("user_lng", map.get("lon"));
        requestBody.put("category", map.get("category"));
        requestBody.put("page", map.get("pageNum"));
        requestBody.put("sort_by", map.get("sortBy"));
        HttpHeaders aiHeaders = new HttpHeaders();
        aiHeaders.setContentType(MediaType.APPLICATION_JSON);
//        aiHeaders.set("Authorization", "Bearer " + accessToken);
//        aiHeaders.set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1cHN0b3JlQGFkbWluLmNvbSIsImlkIjo2LCJ0aW1lIjoxNzYyOTI1NDAzLjY1MTY5MjZ9.07lz8Ox2cGC28UCmqcKCt5R6Rfwtgs-Eiu0ttgWRxws");

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, null);
        try {
            
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(aiSearchExactUrl, request, String.class);
            String body = stringResponseEntity.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONObject jsonObject1 = new JSONObject();
            // 生活服务类别：转换为StoreInfoVo，确保返回的字段名按照StoreInfoVo定义
            // 模糊搜索：从related_results和matched_results字段获取数据
            List<StoreInfoVo> relatedResult = convertToStoreInfoList(jsonObject.getJSONArray("related_results"));
            List<StoreInfoVo> matchedResult = convertToStoreInfoList(jsonObject.getJSONArray("matched_results"));

            // 查找图片并设置到result中（图片类型1-入口图）
            fillStoreImages(relatedResult, 1);
            fillStoreImages(matchedResult, 1);

            // 合并两个列表
//            List<StoreInfoVo> relatedResults = new ArrayList<>();
//            List<StoreInfoVo> matchedResults = new ArrayList<>();
//            matchedResults.addAll(matchedResult);
//            relatedResults.addAll(relatedResult);
            jsonObject1.put("matchedRecords", matchedResult);
            jsonObject1.put("relatedRecords", relatedResult);


            jsonObject1.put("total", jsonObject.get("total"));
            jsonObject1.put("size", map.get("pageSize"));
            log.info("调用AI搜索接口 接口返回------{}", body);
            return R.data(jsonObject1);
        } catch (Exception e) {
            log.error("调用AI搜索接口 接口异常------", e);
        }
        return  R.fail("请求失败");
    }

    @RequestMapping("/fuzzySearch")
    public R fuzzySearch(@RequestBody Map<String,String> map) {
        // 初始化请求体Map
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("query", map.get("storeName"));
        requestBody.put("limit", map.get("pageSize"));
        requestBody.put("user_lat", map.get("lat"));
        requestBody.put("user_lng", map.get("lon"));
        requestBody.put("category", map.get("category"));
        requestBody.put("page", map.get("pageNum"));
        requestBody.put("sort_by", map.get("sortBy"));
        HttpHeaders aiHeaders = new HttpHeaders();
        aiHeaders.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, null);
        try {
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(aiSearchFuzzyUrl, request, String.class);
            String body = stringResponseEntity.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONObject jsonObject1 = new JSONObject();
            // 模糊搜索：从related_results和matched_results字段获取数据
            List<StoreInfoVo> result = convertToStoreInfoList(jsonObject.getJSONArray("results"));

            // 查找图片并设置到result中（图片类型1-入口图）
            fillStoreImages(result, 1);

            // 填充评论总数
            fillRatingCount(result);

            jsonObject1.put("records", result);

            jsonObject1.put("total", jsonObject.get("total"));
            jsonObject1.put("size", map.get("pageSize"));
            log.info("调用AI模糊搜索接口 接口返回------{}", body);
            return R.data(jsonObject1);
        } catch (Exception e) {
            log.error("调用AI模糊搜索接口 接口异常------", e);
        }
        return  R.fail("请求失败");
    }

    private List<StoreInfoVo> convertToStoreInfoList(JSONArray results) {
        List<StoreInfoVo> storeInfoList = new ArrayList<>();
        if (results != null) {
            for (int i = 0; i < results.size(); i++) {
                JSONObject item = results.getJSONObject(i);
                // 记录第一条数据的字段名和内容，用于调试
                if (i == 0) {
                    log.info("AI返回的JSON字段示例: {}", item.keySet());
                }
                
                // 创建新的JSONObject，将下划线命名转换为驼峰命名
                JSONObject camelCaseItem = new JSONObject();
                for (String key : item.keySet()) {
                    String camelKey = underscoreToCamelCase(key);
                    camelCaseItem.put(camelKey, item.get(key));
                }
                
                // 将"name"字段映射到"storeName"字段
                if (camelCaseItem.containsKey("name") && !camelCaseItem.containsKey("storeName")) {
                    camelCaseItem.put("storeName", camelCaseItem.get("name"));
                }

                // 使用JSON.parseObject方法进行转换
                StoreInfoVo storeInfo = JSON.parseObject(camelCaseItem.toJSONString(), StoreInfoVo.class);
                storeInfoList.add(storeInfo);
            }
        }
        return storeInfoList;
    }

    /**
     * 查找店铺图片并设置到StoreInfoVo列表中
     *
     * @param result StoreInfoVo列表
     * @param imgType 图片类型（1:入口图, 2:相册, 10:商家头像等）
     */
    private void fillStoreImages(List<StoreInfoVo> result, Integer imgType) {
        if (result == null || result.isEmpty()) {
            return;
        }
        
        // 从结果中提取所有的id，放到集合中
        List<Integer> storeIdList = result.stream()
                .map(StoreInfoVo::getId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());
        
        if (storeIdList.isEmpty()) {
            return;
        }
        
        // 批量查询图片
        QueryWrapper<StoreImg> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("store_id", storeIdList)
                .eq("img_type", imgType)
                .orderByAsc("img_sort");
        List<StoreImg> storeImgList = storeImgMapper.selectList(queryWrapper);
        
        // 将图片列表按照storeId分组
        Map<Integer, List<StoreImg>> storeImgMap = storeImgList.stream()
                .collect(Collectors.groupingBy(StoreImg::getStoreId));
        
        // 将图片列表设置到对应的StoreInfoVo中
        for (StoreInfoVo storeInfo : result) {
            if (storeInfo.getId() != null) {
                List<StoreImg> imgs = storeImgMap.get(storeInfo.getId());
                if (imgs != null && !imgs.isEmpty()) {
                    // 将图片列表转换为URL列表，按照imgSort排序
                    List<String> imgUrlList = imgs.stream()
                            .sorted(Comparator.comparing(StoreImg::getImgSort, Comparator.nullsLast(Comparator.naturalOrder())))
                            .map(StoreImg::getImgUrl)
                            .filter(url -> url != null)
                            .collect(Collectors.toList());
                    storeInfo.setStoreAlbumUrlList(imgUrlList);
                    // 如果第一个图片存在，也可以设置到imgUrl字段作为头像
                    if (!imgUrlList.isEmpty()) {
                        storeInfo.setImgUrl(imgUrlList.get(0));
                    }
                }
            }
        }
    }

    /**
     * 填充评论总数到StoreInfoVo列表中
     *
     * @param result StoreInfoVo列表
     */
    private void fillRatingCount(List<StoreInfoVo> result) {
        if (result == null || result.isEmpty()) {
            return;
        }

        for (StoreInfoVo storeInfo : result) {
            if (storeInfo.getId() != null) {
                try {
                    // 调用评论服务获取评论总数，businessId传id，businessType传1
                    Object ratingCountObj = commonRatingService.getRatingCount(storeInfo.getId(), 1);

                    // 将返回的Object转换为Map
                    if (ratingCountObj instanceof Map) {
                        Map<String, Object> ratingCountMap = (Map<String, Object>) ratingCountObj;
                        // 从map中取出totalCount字段
                        Object totalCount = ratingCountMap.get("totalCount");
                        if (totalCount != null) {
                            // 赋值给totalNum字段（转为String类型）
                            storeInfo.setTotalNum(String.valueOf(totalCount));
                        }
                    }
                } catch (Exception e) {
                    log.warn("获取评论总数失败，storeId: {}", storeInfo.getId(), e);
                    // 如果获取失败，继续处理下一个，不影响其他数据
                }
            }
        }
    }

    /**
     * 将下划线命名转换为驼峰命名
     * 例如: store_tel -> storeTel, created_time -> createdTime
     */
    private String underscoreToCamelCase(String underscore) {
        if (underscore == null || !underscore.contains("_")) {
            return underscore;
        }
        StringBuilder camelCase = new StringBuilder();
        boolean nextUpperCase = false;
        for (char c : underscore.toCharArray()) {
            if (c == '_') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    camelCase.append(Character.toUpperCase(c));
                    nextUpperCase = false;
                } else {
                    camelCase.append(c);
                }
            }
        }
        return camelCase.toString();
    }
























}
