package com.gxwebsoft.ai.service.impl;

import com.aliyun.bailian20231229.Client;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.ai.mapper.AiCloudDocMapper;
import com.gxwebsoft.ai.service.AiCloudDocService;
import com.gxwebsoft.ai.util.AiCloudDataCenterUtil;
import com.gxwebsoft.ai.config.KnowledgeBaseConfig;
import com.gxwebsoft.ai.entity.AiCloudDoc;
import com.gxwebsoft.ai.factory.KnowledgeBaseClientFactory;
import com.gxwebsoft.ai.param.AiCloudDocParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.Dict;
import com.gxwebsoft.common.system.entity.DictData;
import com.gxwebsoft.common.system.param.DictDataParam;
import com.gxwebsoft.common.system.service.DictDataService;
import com.gxwebsoft.common.system.service.DictService;
import com.gxwebsoft.oa.entity.OaCompany;
import com.gxwebsoft.oa.service.OaCompanyService;
import com.gxwebsoft.pwl.entity.PwlProject;
import com.gxwebsoft.pwl.service.PwlProjectService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * AI云文档目录表Service实现
 *
 * @author yc
 */
@Service
public class AiCloudDocServiceImpl extends ServiceImpl<AiCloudDocMapper, AiCloudDoc> implements AiCloudDocService {

    @Autowired
    private KnowledgeBaseConfig config;
    
    @Autowired
    private KnowledgeBaseClientFactory clientFactory;
    
    @Autowired
    private DictService dictService;

    @Autowired
    private DictDataService dictDataService;

    @Autowired
    private PwlProjectService pwlProjectService;

    @Autowired
    private OaCompanyService oaCompanyService;
	
    @Override
    public PageResult<AiCloudDoc> pageRel(AiCloudDocParam param) {
        PageParam<AiCloudDoc, AiCloudDocParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<AiCloudDoc> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<AiCloudDoc> listRel(AiCloudDocParam param) {
        List<AiCloudDoc> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<AiCloudDoc, AiCloudDocParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public AiCloudDoc getByIdRel(Integer id) {
        AiCloudDocParam param = new AiCloudDocParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public List<AiCloudDoc> getSelfAndChildren(Integer docId) {
        // 查询所有未删除的目录
        AiCloudDocParam param = new AiCloudDocParam();
        param.setDeleted(0);
        List<AiCloudDoc> allDocs = this.listRel(param);
        
        // 查找指定目录
        AiCloudDoc targetDoc = allDocs.stream()
                .filter(doc -> doc.getId().equals(docId))
                .findFirst()
                .orElse(null);
        
        if (targetDoc == null) {
            return new ArrayList<>();
        }
        
        // 递归获取所有子孙目录
        List<AiCloudDoc> result = new ArrayList<>();
        result.add(targetDoc);
        getChildrenRecursive(allDocs, targetDoc.getId(), result);
        
        return result;
    }

    /**
     * 递归获取所有子目录
     *
     * @param allDocs 所有目录列表
     * @param parentId 父目录ID
     * @param result 结果列表
     */
    private void getChildrenRecursive(List<AiCloudDoc> allDocs, Integer parentId, List<AiCloudDoc> result) {
        List<AiCloudDoc> children = allDocs.stream()
                .filter(doc -> parentId.equals(doc.getParentId()))
                .collect(Collectors.toList());
        
        for (AiCloudDoc child : children) {
            result.add(child);
            getChildrenRecursive(allDocs, child.getId(), result);
        }
    }
    
    @Override
    public Boolean createDocDirectories(Integer companyId, Integer userId, Integer projectId) {
    	if (companyId == null && projectId != null && projectId > 0) {
    	    PwlProject project = pwlProjectService.getById(projectId);
    	    if (project != null) {
    	        companyId = project.getCompanyId();
    	    }
    	}
    	
        OaCompany oaCompany = oaCompanyService.getById(companyId);
        if (oaCompany == null) {
            return false;
        }
        String categoryId = getDocCategoryId(companyId, oaCompany.getCompanyName(), projectId);
        if (StrUtil.isBlank(categoryId)) {
            return false;
        }

        // 1. 查询或创建顶级目录（避免重复）
        AiCloudDoc topDirectory = this.getOne(new LambdaQueryWrapper<AiCloudDoc>()
                .eq(AiCloudDoc::getCompanyId, companyId)
                .eq(AiCloudDoc::getProjectId, projectId)
                .eq(AiCloudDoc::getParentId, 0));
        if (topDirectory == null) {
            topDirectory = new AiCloudDoc();
            topDirectory.setCategoryId(categoryId);
            topDirectory.setProjectId(projectId);
            topDirectory.setCompanyId(oaCompany.getCompanyId());
            topDirectory.setParentId(0);
            topDirectory.setName(oaCompany.getCompanyName());
            topDirectory.setSortNumber(0);
            topDirectory.setStatus(0);
            topDirectory.setDeleted(0);
            topDirectory.setUserId(userId);
            topDirectory.setTenantId(oaCompany.getTenantId());
            topDirectory.setCreateTime(LocalDateTime.now());
            topDirectory.setUpdateTime(LocalDateTime.now());
            // 设置 docType
            if (projectId != null && projectId != 0) {
                topDirectory.setDocType(1);
            } else if (projectId != null && projectId == 0 && oaCompany.getCompanyId() != null && oaCompany.getCompanyId() != 0) {
                topDirectory.setDocType(2);
            } else if (projectId != null && projectId == 0 && oaCompany.getCompanyId() != null && oaCompany.getCompanyId() == 0) {
                topDirectory.setDocType(3);
            } else {
                topDirectory.setDocType(0);
            }
            this.save(topDirectory);
        }
        Integer topDirId = topDirectory.getId();

        // 2. 获取目录名称列表（优先字典）
        List<String> directoryNames = getDirectoryNames();

        // 3. 查询已存在的子目录，只添加不存在的名称
        Set<String> existingNames = this.list(new LambdaQueryWrapper<AiCloudDoc>()
                .eq(AiCloudDoc::getParentId, topDirId)
                .eq(AiCloudDoc::getCompanyId, companyId)
                .eq(AiCloudDoc::getProjectId, projectId))
                .stream()
                .map(AiCloudDoc::getName)
                .collect(Collectors.toSet());

        List<AiCloudDoc> newDirectories = new ArrayList<>();
        for (int i = 0; i < directoryNames.size(); i++) {
            String name = directoryNames.get(i);
            if (!existingNames.contains(name)) {
                AiCloudDoc doc = new AiCloudDoc();
                doc.setCategoryId(categoryId);
                doc.setProjectId(projectId);
                doc.setCompanyId(oaCompany.getCompanyId());
                doc.setParentId(topDirId);
                doc.setName(name);
                doc.setSortNumber(i + 1);
                doc.setStatus(0);
                doc.setDeleted(0);
                doc.setUserId(userId);
                doc.setTenantId(oaCompany.getTenantId());
                doc.setCreateTime(LocalDateTime.now());
                doc.setUpdateTime(LocalDateTime.now());
                // 设置 docType
                if (projectId != null && projectId != 0) {
                    doc.setDocType(1);
                } else if (projectId != null && projectId == 0 && oaCompany.getCompanyId() != null && oaCompany.getCompanyId() != 0) {
                    doc.setDocType(2);
                } else if (projectId != null && projectId == 0 && oaCompany.getCompanyId() != null && oaCompany.getCompanyId() == 0) {
                    doc.setDocType(3);
                } else {
                    doc.setDocType(0);
                }
                newDirectories.add(doc);
            }
        }

        if (!newDirectories.isEmpty()) {
            return this.saveBatch(newDirectories);
        }
        return true;
    }

    // 提取字典读取逻辑
    private List<String> getDirectoryNames() {
        List<String> defaultNames = Arrays.asList(
                "1.基本情况", "2.企业领导人员任职情况", "3.任期内年度总结报告", "4.公司章程及议事规则",
                "5.领导班子分工", "6.任期内会议纪要与会议记录", "7.内部控制制度", "8.企业发展规划及战略",
                "9.目标责任", "10-11.重大经济事项决策及执行（项目）", "12.固定资产、资产处置资料",
                "13.财务数据", "14.以前年度审计"
        );
        try {
            Dict dict = dictService.getOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, "documentCategory"));
            if (dict != null) {
                DictDataParam param = new DictDataParam();
                param.setDictId(dict.getDictId());
                List<DictData> dictDataList = dictDataService.listRel(param);
                if (CollectionUtil.isNotEmpty(dictDataList)) {
                    return dictDataList.stream()
                            .map(DictData::getDictDataCode)
                            .collect(Collectors.toList());
                }
            }
        } catch (Exception e) {
            // 忽略异常，使用默认列表
        	e.printStackTrace();
        }
        return defaultNames;
    }

    // 修正获取 categoryId 的逻辑，避免空指针
    private String getDocCategoryId(Integer companyId, String companyName, Integer projectId) {
        // 查询公司顶级目录（projectId=0, parentId=0）
        AiCloudDoc docTop = this.getOne(new LambdaQueryWrapper<AiCloudDoc>()
                .eq(AiCloudDoc::getCompanyId, companyId)
                .eq(AiCloudDoc::getProjectId, 0)
                .eq(AiCloudDoc::getParentId, 0));
        if (docTop != null) {
            return docTop.getCategoryId();
        }
        // 如果是项目目录，公司顶级目录必须已存在，否则返回空
        if (projectId != null && projectId > 0) {
            return "";
        }
        // 否则为公司创建新的远程分类
        String workspaceId = config.getWorkspaceId();
        String topCategoryId = config.getTopCategoryId();
        try {
            Client client = clientFactory.createClient();
            return AiCloudDataCenterUtil.addCategory(client, workspaceId, topCategoryId, companyName)
                    .getBody().getData().getCategoryId();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
