package com.gxwebsoft.oa.service.impl;

import com.aliyun.bailian20231229.Client;
import com.aliyun.bailian20231229.models.DeleteCategoryResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.oa.mapper.OaCompanyMapper;
import com.gxwebsoft.oa.service.OaCompanyService;

import cn.hutool.core.util.StrUtil;

import com.gxwebsoft.oa.entity.OaCompany;
import com.gxwebsoft.oa.param.OaCompanyParam;
import com.gxwebsoft.ai.config.KnowledgeBaseConfig;
import com.gxwebsoft.ai.entity.AiCloudDoc;
import com.gxwebsoft.ai.entity.AiCloudFile;
import com.gxwebsoft.ai.factory.KnowledgeBaseClientFactory;
import com.gxwebsoft.ai.service.AiCloudDocService;
import com.gxwebsoft.ai.service.AiCloudFileService;
import com.gxwebsoft.ai.util.AiCloudDataCenterUtil;
import com.gxwebsoft.ai.util.AiCloudKnowledgeBaseUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;

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.stream.Collectors;

/**
 * 企业信息Service实现
 *
 * @author 科技小王子
 * @since 2024-09-20 12:33:12
 */
@Service
public class OaCompanyServiceImpl extends ServiceImpl<OaCompanyMapper, OaCompany> implements OaCompanyService {

    @Autowired
    private AiCloudDocService aiCloudDocService;

    @Autowired
    private AiCloudFileService aiCloudFileService;
    
    @Autowired
    private KnowledgeBaseConfig config;

    @Autowired
    private KnowledgeBaseClientFactory clientFactory;
	
    @Override
    public PageResult<OaCompany> pageRel(OaCompanyParam param) {
        PageParam<OaCompany, OaCompanyParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        List<OaCompany> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

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

    @Override
    public OaCompany getByIdRel(Integer companyId) {
        OaCompanyParam param = new OaCompanyParam();
        param.setCompanyId(companyId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public void initCompanyDocDirectories(OaCompany oaCompany, Integer userId) {
        String workspaceId = config.getWorkspaceId();
        String topCategoryId = config.getTopCategoryId();
        String categoryId = "";
        try {
            Client client = clientFactory.createClient();
            categoryId = AiCloudDataCenterUtil.addCategory(client, workspaceId, topCategoryId, oaCompany.getCompanyName()).getBody().getData().getCategoryId();
        } catch (Exception e) {
            e.printStackTrace();
            return; // 创建分类失败时直接返回
        }

        // 1. 先创建顶级目录（公司名称）
        AiCloudDoc topDirectory = new AiCloudDoc();
        topDirectory.setCategoryId(categoryId);
        topDirectory.setCompanyId(oaCompany.getCompanyId());
        topDirectory.setParentId(0); // 顶级目录的父ID为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());
        
        // 保存顶级目录并获取其ID
        aiCloudDocService.save(topDirectory);
        Integer topDirId = topDirectory.getId(); // 假设实体类有getDocId()方法

        // 2. 创建子目录列表
        List<String> directoryNames = Arrays.asList(
            "1.基本情况", "2.企业领导人员任职情况", "3.任期内年度总结报告", "4.公司章程及议事规则", 
            "5.领导班子分工", "6.任期内会议纪要与会议记录", "7.内部控制制度", "8.企业发展规划及战略", 
            "9.目标责任", "10-11.重大经济事项决策及执行（项目）", "12.固定资产、资产处置资料", 
            "13.财务数据", "14.以前年度审计"
        );
        
        List<AiCloudDoc> directories = new ArrayList<>();
        for (int i = 0; i < directoryNames.size(); i++) {
            AiCloudDoc doc = new AiCloudDoc();
            doc.setCategoryId(categoryId);
            doc.setCompanyId(oaCompany.getCompanyId());
            doc.setParentId(topDirId); // 关键修改：父目录ID设为顶级目录的ID
            doc.setName(directoryNames.get(i));
            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());
            directories.add(doc);
        }
        
        // 批量保存子目录
        aiCloudDocService.saveBatch(directories);
    }
    
    @Override
    public boolean removeCompanyDocDirectories(Integer companyId) {
    	boolean ret = true;
    	String workspaceId = config.getWorkspaceId();
    	if(companyId==null) {
    		return ret;
    	}
    	//目录
    	List<AiCloudDoc> docList = aiCloudDocService.list(new LambdaQueryWrapper<AiCloudDoc>().eq(AiCloudDoc::getCompanyId, companyId));
    	List<Integer> docIds = docList.stream().map(AiCloudDoc::getId).collect(Collectors.toList());
    	//先删目阿里云录下所有文件
    	List<AiCloudFile> fileList = aiCloudFileService.list(new LambdaQueryWrapper<AiCloudFile>().in(AiCloudFile::getDocId, docIds));
    	List<Integer> fileIds = fileList.stream().map(AiCloudFile::getId).collect(Collectors.toList());
    	for(AiCloudFile file : fileList) {
    		try {
    			Client client = clientFactory.createClient();
    			AiCloudDataCenterUtil.deleteFile(client, workspaceId, file.getFileId());
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	//再删阿里云目录
    	List<String> categoryIds = docList.stream().map(AiCloudDoc::getCategoryId).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
    	for(String categoryId : categoryIds) {
            try {
                Client client = clientFactory.createClient();
                ret = AiCloudDataCenterUtil.deleteCategory(client, workspaceId, categoryId).getBody().getSuccess();
            } catch (Exception e) {
                e.printStackTrace();
            }
    	}
    	aiCloudDocService.removeByIds(docIds);
    	aiCloudFileService.removeByIds(fileIds);
    	return ret;
    }
    
    @Override
    public boolean removeCompanyKnowledgeBase(Integer companyId) {
    	boolean ret = true;
    	String workspaceId = config.getWorkspaceId();
    	if(companyId==null) {
    		return ret;
    	}
    	//删阿里云知识库
    	OaCompany oaCompany = baseMapper.selectById(companyId);
        try {
            Client client = clientFactory.createClient();
            ret = AiCloudKnowledgeBaseUtil.deleteIndex(client, workspaceId, oaCompany.getKbId()).getBody().getSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
}
