package com.fs.fastGpt.service.impl;


import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.company.domain.CompanyConfig;
import com.fs.company.service.ICompanyConfigService;
import com.fs.fastGpt.domain.AiCompanyConfig;
import com.fs.fastGpt.domain.FastGptCollentionData;
import com.fs.fastGpt.mapper.FastGptCollentionDataMapper;
import com.fs.fastGpt.service.IFastGptCollentionDataService;
import com.fs.fastgptApi.param.AddDataToCollectionBatchParam;
import com.fs.fastgptApi.param.FastGptCollentionDataParam;
import com.fs.fastgptApi.param.GetCollectionDataListParam;
import com.fs.fastgptApi.param.UpdateCollectionDataParam;
import com.fs.fastgptApi.result.AddDataToCollectionBatchResult;
import com.fs.fastgptApi.result.GetCollectionDataDetailResult;
import com.fs.fastgptApi.result.GetCollectionDataListResult;
import com.fs.fastgptApi.result.KnowledgeBaseResult;
import com.fs.fastgptApi.service.DataSetDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

/**
 * 集合里数据Service业务层处理
 * 
 * @author fs
 * @date 2024-09-30
 */
@Service
public class FastGptCollentionDataServiceImpl implements IFastGptCollentionDataService
{
    @Autowired
    private FastGptCollentionDataMapper fastGptCollentionDataMapper;

    @Autowired
    private DataSetDataService dataSetDataService;

    @Autowired
    private ICompanyConfigService companyConfigService;

    /**
     * 查询集合里数据
     * 
     * @param id 集合里数据主键
     * @return 集合里数据
     */
    @Override
    public FastGptCollentionData selectFastGptCollentionDataById(String id)
    {
        return fastGptCollentionDataMapper.selectFastGptCollentionDataById(id);
    }

    /**
     * 查询集合里数据列表
     * 
     * @param fastGptCollentionData 集合里数据
     * @return 集合里数据
     */
    @Override
    public List<FastGptCollentionData> selectFastGptCollentionDataList(FastGptCollentionData fastGptCollentionData)
    {
        return fastGptCollentionDataMapper.selectFastGptCollentionDataList(fastGptCollentionData);
    }

    /**
     * 新增集合里数据
     * 
     * @param collentionDataParam 集合里数据
     * @return 结果
     */
    @Override
    public R insertFastGptCollentionData(FastGptCollentionDataParam collentionDataParam)
    {
        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(collentionDataParam.getCompanyId(), "sys:AiKf:config");
        AiCompanyConfig aiCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), AiCompanyConfig.class);

        AddDataToCollectionBatchParam param=new AddDataToCollectionBatchParam();

        param.setTrainingType(collentionDataParam.getTrainingType());
        param.setCollectionId(collentionDataParam.getCollectionId());
        param.setData(collentionDataParam.getData());

        AddDataToCollectionBatchResult addDataToCollectionBatchResult = dataSetDataService.addDataToCollectionBatch(param,aiCompanyConfig.getUrl(), aiCompanyConfig.getKey());
        if (addDataToCollectionBatchResult.getCode() == 200) {
            return R.ok().put("suc",addDataToCollectionBatchResult.getData().getInsertLen());
        } else {
            return R.error("添加失败");
        }
    }

    /**
     * 修改集合里数据
     * 
     * @param fastGptCollentionData 集合里数据
     * @return 结果
     */
    @Override
    public R updateFastGptCollentionData(FastGptCollentionData fastGptCollentionData)
    {
        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(fastGptCollentionData.getCompanyId(), "sys:AiKf:config");
        AiCompanyConfig aiCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), AiCompanyConfig.class);


        UpdateCollectionDataParam param=new UpdateCollectionDataParam();
        param.setDataId(fastGptCollentionData.getId());
        param.setQ(fastGptCollentionData.getQuestion());
        param.setA(fastGptCollentionData.getAnswer());
        KnowledgeBaseResult knowledgeBaseResult = dataSetDataService.updateCollectionData(param,aiCompanyConfig.getUrl(), aiCompanyConfig.getKey());
        if(knowledgeBaseResult.getCode()==200){
            fastGptCollentionDataMapper.updateFastGptCollentionData(fastGptCollentionData);
        }else {
            return R.error();
        }
        return R.ok();
    }

    /**
     * 批量删除集合里数据
     * 
     * @param ids 需要删除的集合里数据主键
     * @return 结果
     */
    @Override
    public R deleteFastGptCollentionDataByIds(String[] ids,Long companyId)
    {

        ArrayList<String> list=new ArrayList<>();

        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(companyId, "sys:AiKf:config");
        AiCompanyConfig aiCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), AiCompanyConfig.class);

        for (String id : ids) {
            KnowledgeBaseResult knowledgeBaseResult = dataSetDataService.deleteCollectionData(id,aiCompanyConfig.getUrl(), aiCompanyConfig.getKey());
            if (knowledgeBaseResult.getCode()==200){
                fastGptCollentionDataMapper.deleteFastGptCollentionDataById(id);
            }else {
                list.add(id);
            }

        }
        return R.ok().put("data",list);

    }

    /**
     * 删除集合里数据信息
     * 
     * @param id 集合里数据主键
     * @return 结果
     */
    @Override
    public int deleteFastGptCollentionDataById(String id)
    {
        return fastGptCollentionDataMapper.deleteFastGptCollentionDataById(id);
    }

    @Override
    public R syncCollentionData(String collectionId, Long companyId) throws ParseException {

        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(companyId, "sys:AiKf:config");
        AiCompanyConfig aiCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), AiCompanyConfig.class);

        int pageNum=1;
        int pageSize=30;

        GetCollectionDataListParam param=new GetCollectionDataListParam();
        param.setCollectionId(collectionId);
        param.setPageNum(pageNum);
        param.setPageSize(pageSize);

        int total = syncCollectionData(param,aiCompanyConfig.getUrl(), aiCompanyConfig.getKey(), companyId);

        // 计算总页数
        int totalPages = (int) Math.ceil((double) total / pageSize);

        // 如果总页数大于1，则遍历剩余页
        if (totalPages > 1) {
            for (int i = 2; i <= totalPages; i++) {
                param.setPageNum(i);
                try {
                    syncCollectionData(param,aiCompanyConfig.getUrl(), aiCompanyConfig.getKey(),companyId);
                } catch (Exception e) {
                    // 处理可能的异常
                    System.err.println("同步出错 " + i + ": " + e.getMessage());
                }
            }
        }
        return R.ok();
    }

    public  int syncCollectionData(GetCollectionDataListParam param,String url, String key, Long companyId) throws ParseException {


        // 定义输出格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 设置时区为 UTC

        int total=0;

        FastGptCollentionData fastGptCollentionData=new FastGptCollentionData();

        GetCollectionDataListResult collectionDataList = dataSetDataService.getCollectionDataList(param,url, key);
        if (collectionDataList!=null && collectionDataList.getCode()==200){
            List<GetCollectionDataListResult.DataItem> data = collectionDataList.getData().getData();
            if (data!=null && data.size()>0){
                for (GetCollectionDataListResult.DataItem item : data) {
                    fastGptCollentionData.setId(item.get_id());
                    fastGptCollentionData.setDatasetId(item.getDatasetId());
                    fastGptCollentionData.setCollectionId(item.getCollectionId());
                    fastGptCollentionData.setQuestion(item.getQ());
                    fastGptCollentionData.setAnswer(item.getA());
                    fastGptCollentionData.setChunkIndex(item.getChunkIndex());
                    GetCollectionDataDetailResult collectionDataDetail = dataSetDataService.getCollectionDataDetail(item.get_id(),url, key);

                    fastGptCollentionData.setIndexes(JSON.toJSONString(collectionDataDetail.getData().getIndexes()));

                    fastGptCollentionData.setCompanyId(companyId);
                    fastGptCollentionDataMapper.insertOrUpdateFastGptCollentionData(fastGptCollentionData);
                }
            }
            total=collectionDataList.getData().getTotal();
        }
        return total;
    }
}
