package com.artfess.cqxy.documentLibrary.manager.impl;

import com.artfess.base.context.BaseContext;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.query.QueryOP;
import com.artfess.base.util.BeanUtils;
import com.artfess.cqxy.documentLibrary.manager.FileLibraryTypeManager;
import com.artfess.cqxy.documentLibrary.model.FileLibraryType;
import com.artfess.cqxy.projectManagement.enums.ProjectStatusEnum;
import com.artfess.cqxy.search.enums.FunctionEnum;
import com.artfess.cqxy.search.manager.GlobalRetrievalManager;
import com.artfess.cqxy.search.model.GlobalRetrieval;
import com.artfess.cqxy.universal.manager.AccessoryManager;
import com.artfess.cqxy.universal.model.Accessory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.artfess.cqxy.documentLibrary.dao.FileLibraryDao;
import com.artfess.cqxy.documentLibrary.model.FileLibrary;
import com.artfess.cqxy.documentLibrary.manager.FileLibraryManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 文件库表(FileLibrary)表服务实现类
 *
 * @author 黎沐华
 * @since 2022-04-02 09:22:25
 */
@Service
public class FileLibraryManagerImpl extends BaseManagerImpl<FileLibraryDao, FileLibrary> implements FileLibraryManager {

    @Autowired
    private AccessoryManager accessoryManager;
    @Autowired
    private FileLibraryTypeManager typeManager;
    @Autowired
    private BaseContext baseContext;
    @Autowired
    private GlobalRetrievalManager grm;

    @Override
    public PageList<FileLibrary> queryAllByPage(QueryFilter<FileLibrary> queryFilter) {
        queryFilter.addFilter("bflt.IS_DELE_", "0", QueryOP.EQUAL);
        queryFilter.addFilter("bfl.IS_DELE_", "0", QueryOP.EQUAL);
        IPage<FileLibrary> result =
                baseMapper.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        // 附件信息处理
        List<FileLibrary> records = result.getRecords();
        for (FileLibrary ele : records) {
            ele.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(ele.getId()));
        }
        return new PageList<>(result);
    }

    @Override
    public boolean saveOrUpdate(FileLibrary entity) {
        boolean save = StringUtils.isEmpty(entity.getId());
        // 先保存其中的 节点信息
        FileLibraryType type = entity.getTypeInfo();
        // 这里前端需要封装一个完整的类型信息，否则将会丢失原有数据
        Assert.notNull(type,"节点信息不能为空！");
        Assert.notNull(type.getHasChildren(),"是否有子节点的状态不能为空！");
        Assert.notNull(type.getCode(),"节点编码不能为空！");
        Assert.notNull(type.getName(),"节点名称不能为空！");
        Assert.notNull(type.getPcode(),"父节点编码不能为空！");
        typeManager.saveOrUpdate(type);
        entity.setTypeId(type.getId());
        boolean op = super.saveOrUpdate(entity);
        if (!typeManager.checkHasChild(type.getId())) {
            typeManager.changeHasChildNode(type.getId(), true);
        }
        // 处理附件信息
        List<Accessory> flag = entity.getAccessoryInfo();//处理空指针
        List<Accessory> accessoryList = null == flag ? new ArrayList<>():flag;
        for (Accessory ele : accessoryList) {
            ele.setSourceId(entity.getId());
            ele.setDirectory(ProjectStatusEnum.eight.getCode());
            ele.setGroup("FileLibrary");
            ele.setNode(ProjectStatusEnum.eight.getCode());
            ele.setCreateBy(baseContext.getCurrentUserId());
            ele.setCreateName(baseContext.getCurrentUserName());
            ele.setCreateTime(LocalDateTime.now());
        }
        // 先清空该ID下的所有附件信息再添加
        accessoryManager.removeBySourceId(entity.getId());
        // 如果没有附件则返回true，不进入添加
        boolean saveAcc = accessoryList.size() == 0 || accessoryManager.saveAccess(accessoryList);
        // 同步到检索表
        GlobalRetrieval globalRetrieval= grm.getByBizId(entity.getId());
        handleRetrieval(save || BeanUtils.isEmpty(globalRetrieval) ?new GlobalRetrieval():globalRetrieval,entity);

        return op;
    }

    private void handleRetrieval(GlobalRetrieval globalRetrieval,FileLibrary entity){
        globalRetrieval.setProjectId("");
        globalRetrieval.setArchivesType(1);
        globalRetrieval.setBizDataId(entity.getId());
        globalRetrieval.setFunctionCode(FunctionEnum.thirtyTwo.getCode());
        globalRetrieval.setFunctionName(FunctionEnum.thirtyTwo.getName());
        globalRetrieval.setBizTableName(FunctionEnum.thirtyTwo.getTableName());
        globalRetrieval.setDetailsRoteUrl(FunctionEnum.thirtyTwo.getTableRoteUrl());
        globalRetrieval.setTableRoteUrl(FunctionEnum.thirtyTwo.getTableRoteUrl());
        globalRetrieval.setTableApiUrl(FunctionEnum.thirtyTwo.getTableApiUrl());
        globalRetrieval.setDetailsApiUrl(FunctionEnum.thirtyTwo.getDetailsApiUrl());
        globalRetrieval.setFunctionPath(FunctionEnum.thirtyTwo.getFunctionPath());
        globalRetrieval.setDocumentNumber(entity.getDocumentNumber());
        globalRetrieval.setName(entity.getEstablishmentName());
        globalRetrieval.setSearchTitle(entity.getEstablishmentName()+"_"+entity.getDocumentNumber()+"_"+entity.getDescribe()+"_"+entity.getRemarks());
        grm.saveOrUpdate(globalRetrieval);
    }

    @Override
    public boolean deleteByIds(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        // 在删除前获取typeId
        String typeId = "";
        if (idList.size() > 0) {
            typeId = baseMapper.selectById(idList.get(0)).getTypeId();
        }
        // 删除数据
        boolean op = super.removeByIds(idList);
        // 删除后检查节点下是否还有数据，没有则置是否有子节点为无
        boolean hasChildren = baseMapper.selectList(new QueryWrapper<FileLibrary>().eq("TYPE_ID_", typeId)).size() > 0;
        if (!hasChildren) {
            typeManager.changeHasChildNode(typeId, false);
        }
        // 同步删除检索表中的信息
        for(String ele:idList){
            grm.remove(1,ele);
        }
        return op;
    }

    @Override
    public FileLibrary get(Serializable id) {
        FileLibrary result = super.get(id);
        result.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(String.valueOf(id)));
        return result;
    }
}

