package shop.alien.second.service.impl;

import cn.hutool.core.collection.CollectionUtil;
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.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import shop.alien.entity.second.vo.SecondCommentVo;
import shop.alien.entity.second.vo.SecondGoodsRecommendVo;
import shop.alien.entity.store.LifeFans;
import shop.alien.entity.store.StoreComment;
import shop.alien.entity.store.StoreImg;
import shop.alien.mapper.LifeFansMapper;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.second.SecondRecommendMapper;
import shop.alien.second.service.SecondRecommendService;
import shop.alien.util.common.JwtUtil;
import shop.alien.util.type.LifeCollectIdentityQuery;
import shop.alien.util.type.LifeFansIdentityQuery;
import shop.alien.util.type.TypeUtil;

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

/**
 * 二手商品服务实现类
 */
@Slf4j
@Service
public class SecondRecommendServiceImpl extends ServiceImpl<SecondRecommendMapper, SecondGoodsRecommendVo> implements SecondRecommendService {

    @Autowired
    private SecondRecommendMapper mapper;

    @Autowired
    private StoreImgMapper storeImgMapper;

    @Autowired
    private LifeFansMapper lifeFansMapper;

    @Autowired
    private TypeUtil typeUtil;
    /**
     * 获取二手商品推荐列表
     * @param page 分页信息
     * @return 推荐列表
     */
    @Override
    public IPage<SecondGoodsRecommendVo> getSecondRecommendByPage(
            IPage<SecondGoodsRecommendVo> page, String longitude, String latitude, Integer typeId, String radiusKm) throws Exception {
        try{
            JSONObject data = JwtUtil.getCurrentUserInfo();
            Integer userId = null;
            String phoneId = null;
            if (data != null) {
                userId = data.getInteger("userId");
                phoneId = data.getString("phone");
                log.info("获取用户ID：userId={}", userId);
            }
            if (userId == null) {
                return null;
            }
            IPage<SecondGoodsRecommendVo> result = mapper.getSecondRecommendByPage(page, userId, longitude + "," + latitude, typeId, "user_" + phoneId, radiusKm);
            for (SecondGoodsRecommendVo row : result.getRecords()) {
                // 价格保留两位小数
                row.setPrice(row.getAmount() != null ? row.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toString() : null);
                // 距离拼接
                if (StringUtil.isNotBlank(row.getDist())) {
                    row.setPosition("距离" + row.getDist() + "km");
                }
            }
            return result;
        } catch (Exception e) {
            log.error("SecondRecommendServiceImpl.getSecondRecommendByPage Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    /**
     * 获取二手商品关注列表
     * @param page 分页信息
     * @return 关注列表
     */
    public IPage<SecondGoodsRecommendVo> querySecondConcernByPage(
            IPage<SecondGoodsRecommendVo> page, String position) throws Exception {
        try {
            JSONObject data = JwtUtil.getCurrentUserInfo();
            String phoneId = null;
            Integer userId = null;
            if (data != null) {
                phoneId = data.getString("phone");
                userId = data.getInteger("userId");
            }
            if (StringUtil.isBlank(phoneId)) {
                return null;
            }
            LifeCollectIdentityQuery.Scope collectScope = resolveCollectScope(phoneId, userId);
            LifeFansIdentityQuery.Scope fansScope = LifeFansIdentityQuery.resolve("user_" + phoneId, typeUtil);
            IPage<SecondGoodsRecommendVo> list = mapper.querySecondConcernByPage(page, userId, "user_" + phoneId, position,
                    collectScope.getUserType(), collectScope.getRefId(),
                    fansScope.getUserType(), fansScope.getRefId());
            List<Integer> idList = list.getRecords().stream() // 创建流
                    .map(obj -> obj.getId())   // 提取每个元素的 ID
                    .collect(Collectors.toList());
            if (CollectionUtil.isEmpty(idList)) {
                return list;
            }
            List<SecondCommentVo> commentList =mapper.querySecondCommentInfo(idList);
            list.getRecords().forEach(item -> {
                // 距离拼接
                if (StringUtil.isNotBlank(item.getDist())) {
                    item.setPosition("距离" + item.getDist() + "km");
                }
                // 价格保留两位小数
                item.setPrice(item.getAmount() != null ? item.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toString() : null);

                // 评论列表
                List<SecondCommentVo> cList = new ArrayList<>();
                commentList.forEach(comment -> {
                    if (item.getId().equals(comment.getBusinessId())) {
                        cList.add(comment);
                    }
                });
                if (cList.size() > 0) {
                    item.setCommentList(cList);
                }
            });
            return list;
        } catch (Exception e){
            log.error("SecondRecommendServiceImpl.querySecondConcernByPage Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }


    /**
     * 获取二手商品新品列表
     * @param page 分页信息
     * @return 关注列表
     */
    public IPage<SecondGoodsRecommendVo> querySecondNewGoodsByPage(
            IPage<SecondGoodsRecommendVo> page, String position, String radiusKm, Integer timeRange) throws Exception {
        try {
            JSONObject data = JwtUtil.getCurrentUserInfo();
            String phoneId = null;
            String userId = null;
            Integer lifeUserId = null;
            if (data != null) {
                phoneId = data.getString("phone");
                userId = data.getString("userId");
                lifeUserId = data.getInteger("userId");
            }
            if (StringUtil.isBlank(phoneId)) {
                return null;
            }
            LifeCollectIdentityQuery.Scope collectScope = resolveCollectScope(phoneId, lifeUserId);
            IPage<SecondGoodsRecommendVo> list = mapper.querySecondNewGoodsByPage(page, userId,"user_" + phoneId, position, radiusKm, timeRange, collectScope.getUserType(), collectScope.getRefId());
            List<Integer> idList = list.getRecords().stream() // 创建流
                    .map(obj -> obj.getId())   // 提取每个元素的 ID
                    .collect(Collectors.toList());
            if (CollectionUtil.isEmpty(idList)) {
                return list;
            }
            List<SecondCommentVo> commentList = mapper.querySecondCommentInfo(idList);
            list.getRecords().forEach(item -> {
                // 距离拼接
                if (StringUtil.isNotBlank(item.getDist())) {
                    item.setPosition("距离" + item.getDist() + "km");
                }
                // 价格保留两位小数
                item.setPrice(item.getAmount() != null ? item.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toString() : null);

                // 评论列表
                List<SecondCommentVo> cList = new ArrayList<>();
                commentList.forEach(comment -> {
                    if (item.getId().equals(comment.getBusinessId())) {
                        cList.add(comment);
                    }
                });
                if (cList.size() > 0) {
                    item.setCommentList(cList);
                }
            });
            return list;
        } catch (Exception e) {
            log.error("SecondRecommendServiceImpl.querySecondNewGoodsByPage Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    public SecondGoodsRecommendVo querySecondGoodsDetail(Integer goodsId, String position) throws Exception {
        try {
            JSONObject data = JwtUtil.getCurrentUserInfo();
            String phoneId = null;
            if (data != null) {
                phoneId = data.getString("phone");
            }
            if (StringUtil.isBlank(phoneId)) {
                return null;
            }
            String collectUserId = toLifeCollectUserId(phoneId);
            LifeCollectIdentityQuery.Scope collectScope = LifeCollectIdentityQuery.resolve(collectUserId, typeUtil);
            SecondGoodsRecommendVo item = StringUtil.isBlank(position)
                    ? mapper.querySecondGoodsDetailWithoutPosition(goodsId, collectUserId, collectScope.getUserType(), collectScope.getRefId())
                    : mapper.querySecondGoodsDetail(goodsId, collectUserId, position, collectScope.getUserType(), collectScope.getRefId());
            applySecondGoodsDetailEnrichment(item, phoneId, goodsId);
            return item;
        } catch (Exception e) {
            log.error("SecondRecommendServiceImpl.querySecondGoodsDetail Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public SecondGoodsRecommendVo querySecondGoodsDetailWithOutJWT(String phoneId, Integer goodsId, String position) throws Exception {
        try {
            if (StringUtil.isBlank(phoneId)) {
                return null;
            }
            String collectUserId = toLifeCollectUserId(phoneId);
            LifeCollectIdentityQuery.Scope collectScope = LifeCollectIdentityQuery.resolve(collectUserId, typeUtil);
            SecondGoodsRecommendVo item = mapper.querySecondGoodsDetail(goodsId, collectUserId, position, collectScope.getUserType(), collectScope.getRefId());
            applySecondGoodsDetailEnrichment(item, phoneId, goodsId);
            return item;
        } catch (Exception e) {
            log.error("SecondRecommendServiceImpl.querySecondGoodsDetailWithOutJWT Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    /**
     * 与 {@code alienStore/collect/addCollect}、表 {@code life_collect.user_id} 一致：普通用户收藏键为 {@code user_手机号}。
     *
     * @param phoneOrUserId 裸手机号或已带 {@code user_} 的前端入参
     */
    static String toLifeCollectUserId(String phoneOrUserId) {
        if (StringUtil.isBlank(phoneOrUserId)) {
            return "";
        }
        String t = phoneOrUserId.trim();
        return t.startsWith("user_") ? t : "user_" + t;
    }

    private LifeCollectIdentityQuery.Scope resolveCollectScope(String phoneId, Integer lifeUserId) {
        if (lifeUserId != null) {
            return LifeCollectIdentityQuery.fromLifeUserId(lifeUserId);
        }
        return LifeCollectIdentityQuery.resolve(toLifeCollectUserId(phoneId), typeUtil);
    }

    /**
     * 二手商品详情公共填充：图片列表（含视频排序）、关注状态、距离文案、价格展示；收藏状态由 SQL 已带出，此处补默认「未收藏」。
     */
    private void applySecondGoodsDetailEnrichment(SecondGoodsRecommendVo item, String phoneId, Integer goodsId) {
        if (item == null) {
            return;
        }
        QueryWrapper<StoreImg> query = new QueryWrapper<>();
        query.lambda()
                .eq(StoreImg::getImgType, 18) // 商品 图片
                .eq(StoreImg::getDeleteFlag, 0)
                .eq(StoreImg::getStoreId, goodsId);
        List<StoreImg> storeImgs = storeImgMapper.selectList(query);
        if (storeImgs.size() > 0) {
            // 先按视频后缀排序，再按ImgSort排序
            String[] imgArr = storeImgs.stream()
                    .sorted((o1, o2) -> {
                        boolean o1IsMp4 = isVideoUrl(o1.getImgUrl());
                        boolean o2IsMp4 = isVideoUrl(o2.getImgUrl());
                        if (o1IsMp4 && o2IsMp4 || !o1IsMp4 && !o2IsMp4) {
                            return o1.getImgSort().compareTo(o2.getImgSort());
                        }
                        return o1IsMp4 ? -1 : 1;
                    }).map(StoreImg::getImgUrl).toArray(String[]::new);
            item.setImgList(imgArr);
        }

        LifeFansIdentityQuery.Scope fanScope = LifeFansIdentityQuery.resolve(toLifeCollectUserId(phoneId), typeUtil);
        LifeFansIdentityQuery.Scope followedScope = LifeFansIdentityQuery.resolve(item.getUserPhone(), typeUtil);
        LambdaQueryWrapper<LifeFans> fansQuery = new LambdaQueryWrapper<>();
        fansQuery.eq(LifeFans::getDeleteFlag, 0);
        LifeFansIdentityQuery.applyFansSide(fansQuery, fanScope);
        LifeFansIdentityQuery.applyFollowedSide(fansQuery, followedScope);
        List<LifeFans> lifeFans = lifeFansMapper.selectList(fansQuery);
        if (lifeFans.size() > 0) {
            item.setFansStatus(1);
        }

        if (StringUtil.isNotBlank(item.getDist())) {
            item.setPosition("距离" + item.getDist() + "km");
        }
        item.setPrice(item.getAmount() != null ? item.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toString() : null);
        if (StringUtil.isBlank(item.getCollectStatus())) {
            item.setCollectStatus("0");
        }
    }

    public static void main(String[] args) {
        List<StoreImg> storeImgs = new ArrayList<>();
        StoreImg storeImg = new StoreImg();
        storeImg.setImgSort(4);
        storeImg.setImgUrl("11111.mp4");
        storeImgs.add(storeImg);
        StoreImg storeImg1 = new StoreImg();
        storeImg1.setImgSort(3);
        storeImg1.setImgUrl("22222.jpg");
        storeImgs.add(storeImg1);
        StoreImg storeImg2 = new StoreImg();
        storeImg2.setImgSort(2);
        storeImg2.setImgUrl("33333.jpg");
        storeImgs.add(storeImg2);
        StoreImg storeImg3 = new StoreImg();
        storeImg3.setImgSort(1);
        storeImg3.setImgUrl("44444.mp4");
        storeImgs.add(storeImg3);

        // 先按视频后缀排序，再按ImgSort排序
        String[] items = storeImgs.stream()
                .sorted((o1, o2) -> {
                    boolean o1IsMp4 = isVideoUrl(o1.getImgUrl());
                    boolean o2IsMp4 = isVideoUrl(o2.getImgUrl());
                    // 如果都是.mp4或都不是.mp4，则按ImgSort排序
                    if (o1IsMp4 && o2IsMp4 || !o1IsMp4 && !o2IsMp4) {
                        return o1.getImgSort().compareTo(o2.getImgSort());
                    }
                    // 否则，.mp4的排在前面
                    return o1IsMp4 ? -1 : 1;
                }).map(StoreImg::getImgUrl).toArray(String[]::new);

        System.out.println(items);
    }

    private static boolean isVideoUrl(String url) {
        if (url == null) return false;
        url = url.toLowerCase();
        return url.endsWith(".mp4") ||
                url.endsWith(".avi") ||
                url.endsWith(".mov") ||
                url.endsWith(".flv") ||
                url.endsWith(".wmv") ||
                url.endsWith(".mkv");
    }
}