package com.easyproject.system.service.coze.impl;

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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.coze.openapi.client.bots.ListBotReq;
import com.coze.openapi.client.bots.RetrieveBotReq;
import com.coze.openapi.client.bots.RetrieveBotResp;
import com.coze.openapi.client.bots.model.Bot;
import com.coze.openapi.client.bots.model.SimpleBot;
import com.coze.openapi.client.common.pagination.PageResp;
import com.coze.openapi.client.workspace.ListWorkspaceReq;
import com.coze.openapi.client.workspace.model.Workspace;
import com.coze.openapi.service.service.CozeAPI;
import com.easyproject.common.core.domain.AjaxResult;
import com.easyproject.common.utils.coze.ChatAiForCozeUtils;
import com.easyproject.service.domain.coze.CozeBotSet;
import com.easyproject.service.domain.coze.CozeTokenSet;
import com.easyproject.service.domain.coze.CozeWorkspacesSet;
import com.easyproject.service.mapper.coze.CozeBotSetMapper;
import com.easyproject.service.mapper.coze.CozeWorkspacesSetMapper;
import com.easyproject.service.service.ICozeJwtService;
import com.easyproject.system.service.coze.ICozeWorkspacesSetService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 空间设置Service业务层处理
 *
 * @author easyproject
 * @date 2025-03-22
 */
@Slf4j
@Service
public class CozeWorkspacesSetServiceImpl implements ICozeWorkspacesSetService {
    @Resource
    private CozeWorkspacesSetMapper cozeWorkspacesSetMapper;
    @Resource
    private CozeBotSetMapper cozeBotSetMapper;
    @Resource
    private ICozeJwtService cozeJwtService;

    /**
     * 查询智能体列表-某个空间中的
     *
     * @param spaceId 空间ID
     * @return 空间设置
     */
    @Override
    public AjaxResult selectCozeWorkspacesSetById(String spaceId) {
        List<CozeBotSet> botEndList = null;
        CozeBotSet bot = null;

        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if (ObjectUtil.isNotEmpty(tokenSet)) {
            //初始化客户端
            CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

            //查询空间列表-组装参数
            ListBotReq listBotReq = ListBotReq.builder().spaceID(spaceId).pageNum(1).pageSize(20).build();
            try {
                PageResp<SimpleBot> botList = coze.bots().list(listBotReq);
                botEndList = new ArrayList<>();
                for (SimpleBot item : botList.getItems()) {
                    bot = new CozeBotSet();
                    bot.setSimpleBot(item);
                    bot.setSpaceId(spaceId);
                    bot.setStatus(2);
                    //查询是否启用了智能体
                    long count = cozeBotSetMapper.selectCount(Wrappers.<CozeBotSet>lambdaQuery().eq(CozeBotSet::getSpaceId, spaceId).eq(CozeBotSet::getBotId, item.getBotID()).eq(CozeBotSet::getStatus, 1));
                    if (count > 0) {
                        bot.setStatus(1);
                        bot.setBotId(item.getBotID());
                    }
                    botEndList.add(bot);
                }
            } catch (Exception e) {
                log.error("空间【{}】，没有智能体", spaceId);
            }
        }

        return AjaxResult.success(botEndList);
    }

    /**
     * 查询空间设置列表
     *
     * @param cozeWorkspacesSet 空间设置
     * @return 空间设置
     */
    @Override
    public AjaxResult selectCozeWorkspacesSetList(CozeWorkspacesSet cozeWorkspacesSet) {

        List<CozeWorkspacesSet> list = null;
        CozeWorkspacesSet workspacesSet = null;

        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if (ObjectUtil.isNotEmpty(tokenSet)) {
            //初始化客户端
            CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

            //查询空间列表-组装参数
            ListWorkspaceReq req = new ListWorkspaceReq();
            req.setPageNum(1);
            req.setPageSize(20);

            //查询空间列表-发起请求
            PageResp<Workspace> workspaces = coze.workspaces().list(req);

            if (!workspaces.getItems().isEmpty()) {
                list = new ArrayList<>();
                for (Workspace item : workspaces.getItems()) {
                    workspacesSet = new CozeWorkspacesSet();
                    workspacesSet.setWorkspace(item);
                    workspacesSet.setStatus(2);
                    //查询是否启用的空间
                    long count = cozeWorkspacesSetMapper.selectCount(Wrappers.<CozeWorkspacesSet>lambdaQuery().eq(CozeWorkspacesSet::getSpacesId, item.getId()));
                    if (count > 0) {
                        workspacesSet.setSpacesId(item.getId());
                        workspacesSet.setStatus(1);
                    }
                    list.add(workspacesSet);
                }
            }
        }

        if (ObjectUtil.isNotEmpty(list)) {
            //初始化客户端
            CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());
            for (CozeWorkspacesSet item : list) {
                CozeBotSet botSet = cozeBotSetMapper.selectOne(Wrappers.<CozeBotSet>lambdaQuery().eq(CozeBotSet::getSpaceId, item.getSpacesId()));
                if (ObjectUtil.isNotEmpty(botSet)) {
                    //查询三方平台智能体信息
                    RetrieveBotResp botInfo = coze.bots().retrieve(RetrieveBotReq.of(botSet.getBotId()));
                    Bot bot = botInfo.getBot();
                    SimpleBot botEnd = new SimpleBot();
                    botEnd.setBotName(bot.getName());
                    botSet.setSimpleBot(botEnd);
                    item.setBotSet(botSet);
                }
            }
        }


        return AjaxResult.success(list);
    }

    /**
     * 修改空间设置
     *
     * @param cozeWorkspacesSet 空间设置
     * @return 结果
     */
    @Override
    public AjaxResult updateCozeWorkspacesSet(CozeWorkspacesSet cozeWorkspacesSet) {

        if (ObjectUtil.isNotEmpty(cozeWorkspacesSet.getSpacesId())) {
            if (cozeWorkspacesSet.getStatus() == 1) {
                //删除所有数据
                cozeWorkspacesSetMapper.deleteAll(1);

                //添加新的
                CozeWorkspacesSet spacesSet = new CozeWorkspacesSet();
                spacesSet.setSpacesId(cozeWorkspacesSet.getSpacesId());
                spacesSet.setStatus(1);
                spacesSet.setCreateTime(DateUtil.date());
                cozeWorkspacesSetMapper.insert(spacesSet);
                return AjaxResult.success();
            } else {
                return AjaxResult.error("至少需要一个状态是【使用中】");
            }

        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 方法说明: 空间智能体设置
     *
     * @param
     * @return
     * @author java-101
     * @date 2025-03-23 14:01:31
     */
    @Override
    public AjaxResult updateStatus(CozeBotSet botSet) {
        //查询某个空间下是否有智能体
        CozeBotSet cozeBotSet = cozeBotSetMapper.selectOne(Wrappers.<CozeBotSet>lambdaQuery().eq(CozeBotSet::getSpaceId, botSet.getSpaceId()));
        if (ObjectUtil.isEmpty(cozeBotSet)) {
            cozeBotSet = new CozeBotSet();
            cozeBotSet.setSpaceId(botSet.getSpaceId());
            cozeBotSet.setBotId(botSet.getBotId());
            cozeBotSet.setStatus(1);
            cozeBotSet.setCreateTime(DateUtil.date());
            cozeBotSetMapper.insert(cozeBotSet);
            return AjaxResult.success();
        } else {
            LambdaUpdateWrapper<CozeBotSet> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.set(CozeBotSet::getBotId, botSet.getBotId());
            updateWrapper.set(CozeBotSet::getStatus, 1);
            updateWrapper.set(CozeBotSet::getUpdateTime, DateUtil.date());
            updateWrapper.eq(CozeBotSet::getId, cozeBotSet.getId());
            cozeBotSetMapper.update(null, updateWrapper);
            return AjaxResult.success();
        }
    }

}
