package cn.com.poc.appbuilder.aggregation.impl;

import cn.com.poc.appbuilder.aggregation.AppBuilderService;
import cn.com.poc.appbuilder.model.BizAppbuilderConversationModel;
import cn.com.poc.appbuilder.service.BizAppbuilderConversationService;
import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.utils.BlContext;
import cn.com.poc.support.security.oauth.entity.UserBaseEntity;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import cn.hutool.core.io.FileUtil;
import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

@Service
public class AppBuilderServiceImpl implements AppBuilderService {

    @Resource
    private FmxParamConfigService fmxParamConfigService;

    @Resource
    private RedisService redisService;

    @Resource
    private BizAppbuilderConversationService bizAppbuilderConversationService;


    private final String APPBUILDER_CONVERSATION_PREFIX = "APPBUILDER_CONVERSATION_";

    @Override
    public String conversation(String appId) {
        AppBuilderClient builder = getClient(appId);
        String conversationId = null;
        UserBaseEntity currentMember = null;
        try {
            // 获取用户信息
            currentMember = BlContext.getCurrentUserNotException();
            conversationId = builder.createConversation();
            // 新建对话
        } catch (Exception e) {
            throw new BusinessException(e.getLocalizedMessage());
        }
        return conversationId;
    }

    @Override
    public String upload(String appId, String conversationId, MultipartFile file) {
//        UserBaseEntity currentMember = null;
        try {
//            currentMember = BlContext.getCurrentUserNotException();
//            Integer memberId = Math.toIntExact(currentMember.getUserId());
            String key = APPBUILDER_CONVERSATION_PREFIX + ":" + conversationId;

            //判断会话有没有过期
            Map<Object, Object> hmget = redisService.hmget(key);
            if (hmget == null) {
                throw new BusinessException("会话已过期");
            }

            //获取fileId
            AppBuilderClient builder = getClient(appId);

            // 上传临时文件
            // 获取文件名
            UUID uuid = UUID.randomUUID();
            File tempFile = null;

            String suffix = "." + FileUtil.getSuffix(file.getOriginalFilename()).toString();

            //创建临时文件
            tempFile = File.createTempFile(uuid.toString(), suffix);
            FileOutputStream fos = new FileOutputStream(tempFile);

            try {
                // 写入数据到临时文件
                byte[] bytes = file.getBytes();
                fos.write(bytes);
            } catch (Exception e) {
                throw new BusinessException("写入临时文件失败");
            } finally {
                //关闭临时文件
                fos.flush();
                fos.close();
            }
            String fileId = null;
                fileId = builder.uploadLocalFile(conversationId, tempFile.getAbsolutePath());

            //删除临时文件
            tempFile.delete();

            //更新redis，把fileId存入redis中
            Map<String, Object> map = new HashMap<>();
            map.put("app_id", appId);
            map.put("file_id", fileId);
            redisService.hmset(key, map, redisService.getExpire(key));

            return fileId;
        } catch (Exception e) {
            throw new BusinessException("抛出异常");
        }
    }

    @Override
    public List<String> getCurrentUserConversationIds() {
        UserBaseEntity currentMember = null;
        try {
            currentMember = BlContext.getCurrentUserNotException();
        } catch (Exception e) {
            throw new BusinessException("获取用户信息失败");
        }
        Integer memberId = Math.toIntExact(currentMember.getUserId());
        String key = APPBUILDER_CONVERSATION_PREFIX + memberId;

        //模糊查询获取键的集合
        Map<String, Map<String, Object>> hmDimMultiGet = redisService.hmDimMultiGet(key);
        List<String> conversationIds = new ArrayList<>();

        for (String outerKey : hmDimMultiGet.keySet()) {
            // Split the outerKey using ":" as delimiter
            String[] parts = outerKey.split(":");
            if (parts.length == 2) {
                // parts[0] will be "APPBUILDER_CONVERSATION_memberId"
                // parts[1] will be the actual conversation_id
                String conversationId = parts[1];
                conversationIds.add(conversationId);
            }
        }

        return conversationIds;
    }


    @Override
    public AppBuilderClientIterator communication(String conversationId, String query, List<String> fileIds, Boolean stream) throws Exception {
        BizAppbuilderConversationModel model = new BizAppbuilderConversationModel();
        model.setConversationId(conversationId);
        model.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAppbuilderConversationModel> models = bizAppbuilderConversationService.findByExample(model, null);
        if(CollectionUtils.isEmpty(fileIds)){
            fileIds = new ArrayList<String>();
        }
        return getClient(models.get(0).getAppId()).run(query, conversationId, fileIds.toArray(new String[fileIds.size()]), stream);
    }

    private AppBuilderClient getClient(String appId) {
        String token = fmxParamConfigService.getParam("baidu.appbuilder.token");
        return new AppBuilderClient(appId, token);
    }
}
