package tech.easyflow.admin.controller.ai;

import org.springframework.web.bind.annotation.PostMapping;
import tech.easyflow.ai.entity.Plugin;
import tech.easyflow.ai.entity.BotPlugin;
import tech.easyflow.ai.entity.PluginItem;
import tech.easyflow.ai.enums.PluginType;
import tech.easyflow.common.annotation.UsePermission;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.tree.Tree;
import tech.easyflow.common.web.controller.BaseCurdController;
import tech.easyflow.ai.service.BotPluginService;
import tech.easyflow.ai.service.PluginService;
import tech.easyflow.ai.service.PluginItemService;
import tech.easyflow.ai.service.PluginVisibilityService;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.common.web.jsonbody.JsonBody;
import tech.easyflow.system.service.CategoryPermissionService;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 *  控制层。
 *
 * @author michael
 * @since 2025-04-07
 */
@RestController
@RequestMapping("/api/v1/botPlugins")
@UsePermission(moduleName = "/api/v1/bot")
public class BotPluginController extends BaseCurdController<BotPluginService, BotPlugin> {

    public BotPluginController(BotPluginService service) {
        super(service);
    }

    @Resource
    private BotPluginService botPluginService;
    @Resource
    private PluginItemService pluginItemService;
    @Resource
    private PluginService pluginService;
    @Resource
    private PluginVisibilityService pluginVisibilityService;

    @GetMapping("list")
    public Result<List<BotPlugin>> list(BotPlugin entity, Boolean asTree, String sortKey, String sortType){

        QueryWrapper queryWrapper = QueryWrapper.create(entity, buildOperators(entity));
        queryWrapper.orderBy(buildOrderBy(sortKey, sortType, getDefaultOrderBy()));

        List<BotPlugin> botPlugins = service.getMapper().selectListWithRelationsByQuery(queryWrapper);
        List<BotPlugin> visibleList = new ArrayList<>();
        for (BotPlugin relation : botPlugins) {
            Plugin plugin = relation.getAiPlugin();
            if (plugin == null) {
                visibleList.add(relation);
                continue;
            }
            if (PluginType.isWorkflow(plugin.getType())) {
                continue;
            }
            if (pluginVisibilityService.canAccessPlugin(plugin.getCreatedBy(), plugin.getId())) {
                visibleList.add(relation);
            }
        }

        List<BotPlugin> list = Tree.tryToTree(visibleList, asTree);

         return Result.ok(list);
    }

    @PostMapping("/getList")
    public Result<List<Plugin>> getList(@JsonBody(value = "botId", required = true) String botId){
        List<Plugin> plugins = botPluginService.getList(botId);
        List<Plugin> visibleList = new ArrayList<>();
        for (Plugin plugin : plugins) {
            if (plugin == null) {
                continue;
            }
            if (PluginType.isWorkflow(plugin.getType())) {
                continue;
            }
            if (pluginVisibilityService.canAccessPlugin(plugin.getCreatedBy(), plugin.getId())) {
                visibleList.add(plugin);
            }
        }
        return Result.ok(visibleList);
    }

    @PostMapping("/getBotPluginToolIds")
    public Result<List<BigInteger>> getBotPluginToolIds(@JsonBody(value = "botId", required = true) String botId){
        return Result.ok(botPluginService.getBotPluginToolIds(botId));
    }

    @PostMapping("/doRemove")
    public Result<Boolean> doRemove(@JsonBody(value = "botId", required = true) String botId,
                           @JsonBody(value = "pluginToolId", required = true) String pluginToolId){
        return Result.ok(botPluginService.doRemove(botId, pluginToolId));
    }

    @PostMapping("updateBotPluginToolIds")
    public Result<?> save(@JsonBody("botId") BigInteger botId, @JsonBody("pluginToolIds") BigInteger [] pluginToolIds) {
        if (pluginToolIds != null) {
            for (BigInteger pluginToolId : pluginToolIds) {
                if (pluginToolId == null) {
                    continue;
                }
                PluginItem pluginItem = pluginItemService.getById(pluginToolId);
                if (pluginItem == null) {
                    continue;
                }
                if (pluginItem.getPluginId() != null) {
                    Plugin plugin = pluginService.getById(pluginItem.getPluginId());
                    if (plugin != null) {
                        if (PluginType.isWorkflow(plugin.getType())) {
                            throw new tech.easyflow.common.web.exceptions.BusinessException("当前版本暂不支持聊天助手绑定工作流插件");
                        }
                        pluginVisibilityService.assertPluginVisible(plugin.getCreatedBy(), plugin.getId(), "无权限绑定插件");
                    }
                }
            }
        }
        service.saveBotAndPluginTool(botId, pluginToolIds);
        return Result.ok();
    }

}
