package org.springblade.plugin.workflow.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springblade.plugin.workflow.chat.core.cache.WfChatCache;
import org.springblade.plugin.workflow.chat.excel.WfChatAppExcel;
import org.springblade.plugin.workflow.chat.mapper.WfChatAppMapper;
import org.springblade.plugin.workflow.chat.pojo.entity.WfChatAppEntity;
import org.springblade.plugin.workflow.chat.pojo.entity.WfChatAssistantEntity;
import org.springblade.plugin.workflow.chat.pojo.vo.WfChatAppVO;
import org.springblade.plugin.workflow.chat.service.IWfChatAppService;
import org.springblade.plugin.workflow.chat.service.IWfChatAssistantService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * dify - 应用 服务实现类
 *
 * @author ssc
 */
@Service
@RequiredArgsConstructor
public class WfChatAppServiceImpl extends BaseServiceImpl<WfChatAppMapper, WfChatAppEntity> implements IWfChatAppService {

	private final IWfChatAssistantService assistantService;

	@Override
	public IPage<WfChatAppVO> selectAppPage(IPage<WfChatAppVO> page, WfChatAppVO appVO) {
		return page.setRecords(baseMapper.selectAppPage(page, appVO));
	}


	@Override
	public List<WfChatAppExcel> exportApp(Wrapper<WfChatAppEntity> queryWrapper) {
		List<WfChatAppExcel> appList = baseMapper.exportApp(queryWrapper);
		//appList.forEach(app -> {
		//	app.setTypeName(DictCache.getValue(DictEnum.YES_NO, App.getType()));
		//});
		return appList;
	}

	@Override
	public void submit(WfChatAppEntity appEntity) {
		Long id = appEntity.getId();
		if (ObjectUtil.isEmpty(id)) {
			this.save(appEntity);
		} else {
			// 清理缓存
			WfChatCache.clearCache();
			// 更新
			this.updateById(appEntity);
			// 更新助手中的应用类型
			WfChatAssistantEntity assistant = new WfChatAssistantEntity();
			assistant.setAppType(appEntity.getType());
			assistantService.update(assistant, new LambdaQueryWrapper<WfChatAssistantEntity>()
				.eq(WfChatAssistantEntity::getAppId, id));
		}
	}
}
