package cn.qinys.platform.mobile.service;

import cn.qinys.platform.entity.wishing.Wish;
import cn.qinys.platform.entity.wishing.WishingTree;
import cn.qinys.platform.mobile.mapper.WishMapper;
import cn.qinys.platform.mobile.mapper.WishingTreeMapper;
import cn.qinys.platform.mobile.req.WishCreateReq;
import cn.qinys.platform.mobile.resp.WishDetailResp;
import cn.qinys.platform.mobile.resp.WishListResp;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class WishServiceImpl implements WishService {

    @Resource
    private WishMapper wishMapper;

    @Resource
    private WishingTreeMapper wishingTreeMapper;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public WishListResp listByTree(Long treeId, Integer page, Integer pageSize) {
        Page<Wish> mpPage = wishMapper.selectPage(
                new Page<>(page, pageSize),
                new LambdaQueryWrapper<Wish>()
                        .eq(Wish::getTreeId, treeId)
                        .eq(Wish::getIsPublic, 1)
                        .eq(Wish::getStatus, 0)
                        .orderByDesc(Wish::getCreatedAt)
        );

        WishListResp resp = new WishListResp();
        resp.setList(mpPage.getRecords().stream().map(this::toDetailResp).toList());
        resp.setTotal(mpPage.getTotal());
        return resp;
    }

    @Override
    public WishListResp listMyWishes(String userId, Integer page, Integer pageSize) {
        Page<Wish> mpPage = wishMapper.selectPage(
                new Page<>(page, pageSize),
                new LambdaQueryWrapper<Wish>()
                        .eq(Wish::getUserId, userId)
                        .orderByDesc(Wish::getCreatedAt)
        );

        WishListResp resp = new WishListResp();
        resp.setList(mpPage.getRecords().stream().map(this::toDetailResp).toList());
        resp.setTotal(mpPage.getTotal());
        return resp;
    }

    @Override
    public WishDetailResp getDetail(Long id) {
        Wish wish = wishMapper.selectById(id);
        return wish != null ? toDetailResp(wish) : null;
    }

    @Override
    public WishDetailResp create(WishCreateReq req, String userId) {
        WishingTree tree = wishingTreeMapper.selectById(req.getTreeId());

        Wish wish = new Wish();
        wish.setTreeId(req.getTreeId());
        wish.setTreeName(tree != null ? tree.getName() : "");
        wish.setUserId(userId);
        wish.setContent(req.getContent());
        wish.setImages(toJson(req.getImages()));
        wish.setLongitude(req.getLng());
        wish.setLatitude(req.getLat());
        wish.setAddress(req.getAddress());
        wish.setIsPublic(req.getIsPublic() != null && req.getIsPublic() ? 1 : 0);
        wish.setTags(toJson(req.getTags()));

        wishMapper.insert(wish);
        return toDetailResp(wish);
    }

    @Override
    public boolean delete(Long id, String userId) {
        Wish wish = wishMapper.selectById(id);
        if (wish == null || !wish.getUserId().equals(userId)) {
            return false;
        }
        wishMapper.deleteById(id);
        return true;
    }

    @Override
    public int like(Long id) {
        Wish wish = wishMapper.selectById(id);
        if (wish == null) {
            return 0;
        }
        wish.setLikes(wish.getLikes() + 1);
        wishMapper.updateById(wish);
        return wish.getLikes();
    }

    private WishDetailResp toDetailResp(Wish wish) {
        WishDetailResp resp = new WishDetailResp();
        resp.setId(wish.getId());
        resp.setTreeId(wish.getTreeId());
        resp.setTreeName(wish.getTreeName());
        resp.setUserId(wish.getUserId());
        resp.setContent(wish.getContent());
        resp.setImages(parseJsonList(wish.getImages()));
        resp.setLng(wish.getLongitude());
        resp.setLat(wish.getLatitude());
        resp.setAddress(wish.getAddress());
        resp.setIsPublic(wish.getIsPublic() != null && wish.getIsPublic() == 1);
        resp.setTags(parseJsonList(wish.getTags()));
        resp.setLikes(wish.getLikes());
        resp.setStatus(wish.getStatus());
        resp.setCreatedAt(wish.getCreatedAt());
        return resp;
    }

    private String toJson(List<String> list) {
        if (list == null || list.isEmpty()) return "[]";
        try {
            return OBJECT_MAPPER.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            log.error("toJson error", e);
            return "[]";
        }
    }

    private List<String> parseJsonList(String json) {
        if (json == null || json.isBlank()) return new ArrayList<>();
        try {
            return OBJECT_MAPPER.readValue(json, new TypeReference<List<String>>() {});
        } catch (Exception e) {
            log.error("parseJsonList error", e);
            return new ArrayList<>();
        }
    }
}
