package cn.qinys.platform.admin.service.impl;

import cn.qinys.platform.admin.mapper.WishingTreeMapper;
import cn.qinys.platform.admin.req.GeoAddressReq;
import cn.qinys.platform.admin.req.WishingTreeCreateReq;
import cn.qinys.platform.admin.req.WishingTreePageReq;
import cn.qinys.platform.admin.resp.WishingTreePageResp;
import cn.qinys.platform.admin.service.WishTreeService;
import cn.qinys.platform.base.response.Result;
import cn.qinys.platform.base.utils.BeanExUtils;
import cn.qinys.platform.entity.wishing.WishingTree;
import cn.qinys.platform.openfeign.UpmsFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author lie tan
 * @description
 * @date 2026-05-23 12:05
 **/
@Service
public class WishTreeServiceImpl implements WishTreeService {

    @Resource
    private WishingTreeMapper wishingTreeMapper;

    @Resource
    UpmsFeignClient upmsFeignClient;
    @Resource
    ChatClient chatClient;


    @Override
    public Integer createWishTree(WishingTreeCreateReq req) {
        WishingTree tree = BeanExUtils.convert(req, WishingTree.class);
        // insert returns number of rows; id is populated into entity if DB supports generated keys
        if (!StringUtils.hasText(tree.getAddress())) {
            Result<String> address = upmsFeignClient.getAddressByAltitudeAndLongitude(new GeoAddressReq(req.getLongitude(), req.getLatitude()));
            tree.setAddress(address.getData());
        }
        String summary = this.getDescription(tree.getAddress());
        tree.setSummary(summary);
        if (!StringUtils.hasText(tree.getDescription())) {
            tree.setDescription(summary);
        }
        wishingTreeMapper.insert(tree);
        return tree.getId();
    }

    @Override
    public Page<WishingTreePageResp> getWishTreePage(WishingTreePageReq req) {
        Page<WishingTree> page = new Page<>(req.getCurrent(), req.getSize());
        QueryWrapper<WishingTree> wrapper = new QueryWrapper<>();
        wrapper.eq("is_deleted", 0)
                .like(StringUtils.hasText(req.getName()), "name", req.getName())
                .orderByDesc("id");
        return wishingTreeMapper.selectTreePage(page, wrapper);
    }

    private String getDescription(String address) {
        if (!StringUtils.hasText(address)) {
            return null;
        }
        return chatClient.prompt().user(address).call().content();
    }


}
