package cn.iocoder.yudao.module.knowledge.service;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.module.knowledge.constants.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.iocoder.yudao.module.knowledge.constants.CodeEnum;
import cn.iocoder.yudao.module.knowledge.controller.requestdto.TArchivesRequest;
import cn.iocoder.yudao.module.knowledge.mapper.TArchivesMapper;
import cn.iocoder.yudao.module.knowledge.entity.TArchives;
import cn.iocoder.yudao.module.knowledge.utils.FileTypeUtils;
import cn.iocoder.yudao.module.knowledge.utils.MimeTypeUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserNickname;

/**
 * 档案表(TArchives)表服务实现类
 *
 * @author makejava
 * @since 2024-04-11 10:25:58
 * 弃用 新实现在di-module-company
 */
@Deprecated
@Service
public class TArchivesService extends ServiceImpl<TArchivesMapper, TArchives> {

    @Autowired
    private TArchivesMapper tArchivesMapper;

    public Result add(TArchivesRequest tArchivesRequest) throws Exception {

        //去重
        if (ObjectUtils.isEmpty(tArchivesRequest.getArchiveType())){
            if (ObjectUtils.isEmpty(tArchivesRequest.getCurFilename())){
                tArchivesRequest.setCurFilename(tArchivesRequest.getOriginalFilename());
            }
            TArchives tArchives1 = new TArchives();
            if (ObjectUtils.isEmpty(tArchivesRequest.getParentId())){
                tArchives1 = tArchivesMapper.selectOnleByConditionDir(tArchivesRequest);
            }else {
                tArchives1 = tArchivesMapper.selectOnleByCondition(tArchivesRequest);
            }
            if (ObjectUtils.isNotEmpty(tArchives1)){
                return  Result.error(25000,"文件名重复");
            }
        }
        //不归档
        if (StringUtils.isNotEmpty(tArchivesRequest.getArchiveType()) && "0".equals(tArchivesRequest.getArchiveType())){
            TArchives tArchives = tArchivesMapper.selectOnleByCondition(tArchivesRequest);
            if (ObjectUtils.isNotEmpty(tArchives)){
                tArchives.setOriginalFilename(tArchivesRequest.getOriginalFilename());
                tArchives.setFileSize(tArchivesRequest.getFileSize());
                tArchives.setFileUrl(tArchivesRequest.getFileUrl());
                return Result.success(tArchivesMapper.updateById(tArchives));
            }
        }
        //归档
        if (StringUtils.isNotEmpty(tArchivesRequest.getArchiveType()) && "1".equals(tArchivesRequest.getArchiveType())){
            return Result.success(archivist(tArchivesRequest));
        }
        //用户信息
        tArchivesRequest.setCreator(getLoginUserNickname());
        tArchivesRequest.setCreatorId(getLoginUserId().toString());
        //保存数据
        TArchives tArchives = new TArchives();
        if (ObjectUtils.isNotEmpty(tArchivesRequest.getFileInfo())){
            tArchives.setFileSize(Long.parseLong(tArchivesRequest.getFileInfo().getFileSize()));
            tArchives.setFileUrl(tArchivesRequest.getFileInfo().getFileUrl());
        }
        BeanUtils.copyProperties(tArchivesRequest, tArchives);
        //文件类型
        if (StringUtils.isNotEmpty(tArchivesRequest.getFileUrl())) {
            tArchives.setIsDir(1);
            //图片
            if (ArrayUtils.contains(MimeTypeUtils.IMAGE_EXTENSION, FileTypeUtils.getFileType(tArchivesRequest.getOriginalFilename()))) {
                tArchives.setType("1");
            }
            //视频
            if (ArrayUtils.contains(MimeTypeUtils.VIDEO_EXTENSION, FileTypeUtils.getFileType(tArchivesRequest.getOriginalFilename()))) {
                tArchives.setType("2");
            }
            //文档
            if (ArrayUtils.contains(MimeTypeUtils.FLASH_FILE, FileTypeUtils.getFileType(tArchivesRequest.getOriginalFilename()))) {
                tArchives.setType("3");
            }
            //音频
            if (ArrayUtils.contains(MimeTypeUtils.FLASH_SANG, FileTypeUtils.getFileType(tArchivesRequest.getOriginalFilename()))) {
                tArchives.setType("4");
            }
            //加文件大小
            TArchives parById = getById(tArchives.getParentId());
            if (ObjectUtils.isNotEmpty(parById)){
                Long fileSize = parById.getFileSize();
                fileSize = fileSize + tArchives.getFileSize();
                resuceAd(parById,fileSize);
            }

        } else {
            tArchives.setIsDir(0);
        }
        boolean save = save(tArchives);
        //处理文件code
        if (ObjectUtils.isNotEmpty(tArchives.getParentId())) {
            TArchives parentObj = getById(tArchives.getParentId());
            tArchives.setCode(parentObj.getCode() + tArchives.getId() + "|");
        } else {
            tArchives.setCode(tArchives.getId() + "|");
        }
        updateById(tArchives);
        if (tArchives.getIsDir() == 1) {
            List<TArchives> list = baseMapper.getParByCode(tArchivesRequest.getCode());
            for (TArchives archives : list) {
                archives.setFileSize(archives.getFileSize() + tArchivesRequest.getFileSize());
            }
            updateBatchById(list);
        }
        return Result.success(save);
    }

    //归档
    public  boolean archivist(TArchivesRequest tArchivesRequest) {
        boolean flag = false;
        //获取当前年份
        Date date = new Date();  // 获取当前时间的Date实例
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");  // 定义日期格式
        String year = sdf.format(date);  // 格式化日期
        //查询归档文件夹
        TArchives tArchives = tArchivesMapper.selectByArchivParentId(tArchivesRequest.getParentId());
        //查询是否存在当年的文件夹
        List<TArchives> list = tArchivesMapper.selectByArchivId(tArchivesRequest.getParentId());
        //如果不存在，创建当年的文件夹进行归档
        if (CollectionUtils.isEmpty(list)){
            tArchivesRequest.setPigeonholeId(tArchives.getId());
            pigeonhole(tArchivesRequest,year);
        }else {
            for (TArchives archives : list) {
                //如果存在当年文件夹
                if (year.equals(archives.getCurFilename())){
                    //重名就替换
                    tArchivesRequest.setParentId(archives.getId());
                    TArchives one = tArchivesMapper.selectOneByCondition(tArchivesRequest);
                    if (ObjectUtils.isNotEmpty(one)){
                        Long id = one.getId();
                        tArchivesMapper.deleteById(id);
                    }
                    //添加归档文件
                    TArchives archives1 = new TArchives();
                    BeanUtils.copyProperties(tArchivesRequest, archives1);
                    archives1.setIsDir(1);
                    archives1.setParentId(archives.getId());
                    archives1.setType("3");
                    //加文件大小
                    TArchives parById = getById(archives1.getParentId());
                    Long fileSize = parById.getFileSize();
                    fileSize = fileSize + archives1.getFileSize();
                    resuceAd(parById,fileSize);
                    save(archives1);
                    //处理文件code
                    if (ObjectUtils.isNotEmpty(archives1.getParentId())) {
                        TArchives parentObj = getById(archives1.getParentId());
                        archives1.setCode(parentObj.getCode() + archives1.getId() + "|");
                    } else {
                        archives1.setCode(archives1.getId() + "|");
                    }
                    updateById(archives1);
                    if (archives1.getIsDir() == 1) {
                        List<TArchives> lists = baseMapper.getParByCode(tArchivesRequest.getCode());
                        for (TArchives archivess : lists) {
                            archivess.setFileSize(archivess.getFileSize() + tArchivesRequest.getFileSize());
                        }
                        updateBatchById(lists);
                    }
                    return true;
                }else {
                    tArchivesRequest.setPigeonholeId(tArchives.getId());
                    pigeonhole(tArchivesRequest,year);
                }
            }
        }
        return flag;
    }

    public boolean pigeonhole(TArchivesRequest tArchivesRequest,String year){

        //重名就替换
        TArchives one = tArchivesMapper.selectOneByCondition(tArchivesRequest);
        if (ObjectUtils.isNotEmpty(one)){
            Long id = one.getId();
            tArchivesMapper.deleteById(id);
        }
        TArchives archives = new TArchives();
        archives.setParentId(tArchivesRequest.getPigeonholeId());
        archives.setCurFilename(year);
        archives.setIsDir(0);
        archives.setType("0");
        save(archives);
        //处理文件code
        if (ObjectUtils.isNotEmpty(archives.getParentId())) {
            TArchives parentObj = getById(archives.getParentId());
            archives.setCode(parentObj.getCode() + archives.getId() + "|");
        } else {
            archives.setCode(archives.getId() + "|");
        }
        updateById(archives);
        //添加归档文件
        TArchives archives1 = new TArchives();
        BeanUtils.copyProperties(tArchivesRequest, archives1);
        archives1.setIsDir(1);
        archives1.setParentId(archives.getId());
        archives1.setType("3");
        //加文件大小
        TArchives parById = getById(archives1.getParentId());
        if (ObjectUtils.isNotEmpty(parById)){
            Long fileSize = parById.getFileSize();
            fileSize = fileSize + archives1.getFileSize();
            resuceAd(parById,fileSize);
            save(archives1);
        }
        //处理文件code
        if (ObjectUtils.isNotEmpty(archives1.getParentId())) {
            TArchives parentObj = getById(archives1.getParentId());
            archives1.setCode(parentObj.getCode() + archives1.getId() + "|");
        } else {
            archives1.setCode(archives1.getId() + "|");
        }
        updateById(archives1);
        if (archives1.getIsDir() == 1) {
            List<TArchives> lists = baseMapper.getParByCode(tArchivesRequest.getCode());
            for (TArchives archivess : lists) {
                archivess.setFileSize(archivess.getFileSize() + tArchivesRequest.getFileSize());
            }
            updateBatchById(lists);
        }
        return true;
    }

    public IPage findAll(Page<TArchives> page, TArchivesRequest tArchives) {
        IPage<TArchives> page1;
        if (StringUtils.isEmpty(tArchives.getOriginalFilename())){
            page1 = baseMapper.selectTArchivesList(page, tArchives);
        }else{
            String code="";
            //根据parid获取code
            if (ObjectUtil.isNotEmpty(tArchives.getParentId())){
                TArchives tArchives1 = this.getById(tArchives.getParentId());
                code= tArchives1.getCode();
            }
            tArchives.setCode(code);
            page1 = baseMapper.selectTArchivesListOfName(page, tArchives);
        }
        return page1;
    }

    public IPage appFindAll(Page<TArchives> page, TArchivesRequest tArchives) {
        IPage<TArchives> page1;
        if (StringUtils.isEmpty(tArchives.getOriginalFilename())){
            page1 = baseMapper.selectTArchivesList(page, tArchives);
        }else{
            String code="";
            //根据parid获取code
            if (ObjectUtil.isNotEmpty(tArchives.getParentId())){
                TArchives tArchives1 = this.getById(tArchives.getParentId());
                code= tArchives1.getCode();
            }
            tArchives.setCode(code);
            page1 = baseMapper.selectTArchivesListOfName(page, tArchives);
        }
        return page1;
    }

    public Result updateByTaId(TArchives tArchives) {
        boolean flag = false;
        //当前目录下去重
        List<TArchives> list = tArchivesMapper.selectByCondition(tArchives);
        if (CollectionUtils.isEmpty(list) || list.size() < 1) {
            //判断是否修改了文件名称
            String originalFilename = getById(tArchives.getId()).getOriginalFilename();
            if (StringUtils.isNotEmpty(originalFilename) && !originalFilename.equals(tArchives.getCurFilename())) {
                tArchives.setOriginalFilename(tArchives.getCurFilename());
            }
            return Result.success(updateById(tArchives));
        } else {
            return Result.error(CodeEnum.DB_FAILD.getCode(), CodeEnum.DB_FAILD.getMsg());
        }
    }


    public Result delete(List<Long> ids) throws Exception {
        if (ObjectUtils.isEmpty(ids)){
            return Result.error(25323,"请先选择要删除的文件");
        }
        int flag = 0;
        for (Long id : ids) {
            TArchives tArchives = getById(id);
            if (tArchives.getId()==105 || tArchives.getId() ==106 || tArchives.getId()==193 ||
                    tArchives.getId()==10653 || tArchives.getId()==10963 || tArchives.getId()==10655 ||
                    tArchives.getId()==10966 || tArchives.getId()==10969 || tArchives.getId()==10967 ||
                    tArchives.getId()==154L ||tArchives.getId()==11004L || tArchives.getId()==11033L || tArchives.getId()==11034L){
                return Result.error(25000,"该类文件不能删除");
            }
            LambdaUpdateWrapper<TArchives> wrapper =new LambdaUpdateWrapper<>();
            wrapper.likeRight(TArchives::getCode,tArchives.getCode()).set(TArchives::getIsRecycled,0);
            flag = tArchivesMapper.update(wrapper);
            //减文件大小
            TArchives parById = getById(tArchives.getParentId());
            if(ObjectUtils.isNotEmpty(parById)){
                Long fileSize = parById.getFileSize();
                fileSize = fileSize - tArchives.getFileSize();
                resuceRe(parById,fileSize);
            }
        }
        return Result.success(flag);
    }

    public List<TArchives> selectOneById(Long id) {
        ArrayList<TArchives> finalList = new ArrayList<>();
        String fileCode ="";
        if(ObjectUtil.isNotEmpty(id)){
            TArchives byId = this.getById(id);
            fileCode = byId.getCode();
        }

        List<TArchives> tArchives = tArchivesMapper.selectOneByCode(fileCode);
        finalList.addAll(tArchives);
        return finalList;
    }

    public List<TArchives> selectOneByIds(List<Long> ids) {

        if (ObjectUtils.isEmpty(ids)){
            return new ArrayList<TArchives>();
        }
        String fileCode ="";
        List<TArchives> finalList = new ArrayList<>();

        for (Long id : ids) {
            if(ObjectUtil.isNotEmpty(id)){
                TArchives byId = this.getById(id);
                if (byId.getIsDir()==0){
                    List<TArchives> tempListDir = new ArrayList<>();
                    fileCode = byId.getCode();
                    tempListDir = tArchivesMapper.selectOneByCode(fileCode);
                    finalList.addAll(tempListDir);
                }else {
                    List<TArchives> tempListDoc = new ArrayList<>();
                    TArchives tArchives = this.getById(id);
                    tempListDoc.add(tArchives);
                    finalList.addAll(tempListDoc);
                }
            }
        }

        return finalList;
    }

    public Result ackDelete(List<Long> ids) {

        if (ObjectUtils.isEmpty(ids)){
            return  Result.success();
        }
        //计算文件大小
        for (Long id : ids) {
            TArchives byId = getById(id);
            if (ObjectUtils.isNotEmpty(byId.getParentId())) {
                TArchives parById = getById(byId.getParentId());
                Long fileSize = parById.getFileSize();
                fileSize = fileSize - byId.getFileSize();
                parById.setFileSize(fileSize);
                updateById(parById);
            }
        }
        //更新文件编码
        int flag = 0;
        for (Long id : ids) {
            TArchives tArchives = getById(id);
            LambdaUpdateWrapper<TArchives> query = new LambdaUpdateWrapper<>();
            query.likeRight(TArchives::getCode, tArchives.getCode()).set(TArchives::getDeleted, 1);
            flag = tArchivesMapper.update(query);
        }

        return Result.success(flag);
    }

    public TArchives selectByCode(String code) {
        return tArchivesMapper.selectByCode(code);
    }

    public Result restore(List<Long> ids) {
        int flag = 0;
        for (Long id : ids) {
            TArchives tArchives = getById(id);
            LambdaUpdateWrapper<TArchives> wrapper =new LambdaUpdateWrapper<>();
            wrapper.likeRight(TArchives::getCode,tArchives.getCode()).set(TArchives::getIsRecycled,1);
            flag = tArchivesMapper.update(wrapper);
            //加文件大小
            TArchives parById = getById(tArchives.getParentId());
            if (ObjectUtils.isNotEmpty(parById)){
                Long fileSize = parById.getFileSize();
                fileSize = fileSize + tArchives.getFileSize();
                resuceAd(parById,fileSize);
            }

        }
        return Result.success(flag);
    }

    public Result move(TArchivesRequest tArchivesRequest) {
        int flag = 0;
        for (Long id : tArchivesRequest.getIds()) {
            TArchives tArchives = tArchivesMapper.selectById(id);
            tArchives.setParentId(tArchivesRequest.getParentId());
            flag = tArchivesMapper.updateById(tArchives);
        }
        return Result.success(flag);
    }

    /**
     * 递归减文件大小
     * @param tArchives
     * @param fileSize
     */
    public void resuceRe(TArchives tArchives,Long fileSize){
        tArchives.setFileSize(fileSize);
        updateById(tArchives);
        if (ObjectUtils.isNotEmpty(tArchives.getParentId())){
            TArchives one = getById(tArchives.getParentId());
            resuceRe(one,fileSize);
        }
    }

    /**
     * 递归加文件大小
     * @param tArchives
     * @param fileSize
     */
    public void resuceAd(TArchives tArchives,Long fileSize){
        tArchives.setFileSize(fileSize);
        updateById(tArchives);
        if (ObjectUtils.isNotEmpty(tArchives.getParentId())){
            TArchives one = getById(tArchives.getParentId());
            resuceAd(one,fileSize);
        }
    }

    public Result getParentId(Long id) {
        TArchives tArchives = new TArchives();
        if (ObjectUtils.isNotEmpty(id)){
            tArchives = tArchivesMapper.getParentId(id);
        }
        /*if (ObjectUtils.isNotEmpty(tArchives.getParentId())){
            tArchives = tArchivesMapper.getParentId(tArchives.getParentId());
        }else {
            tArchives.setId(null);
        }*/
        if (ObjectUtils.isEmpty(tArchives.getParentId())){
            tArchives.setParentId(null);
        }
        return Result.success(tArchives);
    }

    public Result findAllDocList(Page<TArchives> page, TArchivesRequest tArchives) {
        List<TArchives> allDocList = tArchivesMapper.findAllDocList(page, tArchives);
        return Result.success(allDocList);
    }

    public List<TArchives> findAllDoc(TArchivesRequest tArchives) {
//        String tokenStr = "&Authorization=Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZGVudGl0eUlkIjoxLCJkZXB0SWQiOjEsIm5pY2tuYW1lIjoiR2xvYmFsIFVzZXIiLCJ0ZW5hbnQtaWQiOjEsInVzZXJuYW1lIjoiR2xvYmFsIFVzZXIiLCJleHAiOjE5NzU2NTcyNzZ9.VuFK-ubqp54VwSL3O8yprt7lMWkc77jfSboxUXtRqQ4";

        List<TArchives> result = baseMapper.findAllDoc(tArchives);
//        result = result.stream()
//                .peek(obj -> obj.setFileUrl(obj.getFileUrl() + tokenStr))
//                .collect(Collectors.toList());
        return result;
    }

    public void delByFileIdAndYear(TArchivesRequest tArchives) {
        LambdaQueryWrapper<TArchives> queryWrapper1 =new LambdaQueryWrapper();
        queryWrapper1.eq(TArchives::getParentId,tArchives.getParentId())
                .eq(TArchives::getCurFilename,"归档");
        TArchives guid = this.getOne(queryWrapper1);
        LambdaQueryWrapper<TArchives> queryWrapper2 =new LambdaQueryWrapper();
        queryWrapper2.eq(TArchives::getParentId,guid.getId())
                .eq(TArchives::getCurFilename,tArchives.getYear());
        TArchives one = this.getOne(queryWrapper2);
        if (ObjectUtils.isNotEmpty(one)){
            //删除此文件夹下的相关归档文件
            LambdaQueryWrapper<TArchives> queryWrapper3=new LambdaQueryWrapper();
            queryWrapper3.eq(TArchives::getParentId,one.getId())
                    .eq(TArchives::getCurFilename,tArchives.getCurFilename());
            this.remove(queryWrapper3);
        }

    }

    public IPage<TArchives> appFindByParentId(Page<TArchives> page, TArchivesRequest tArchives) {
        IPage<TArchives> tArchivesIPage = tArchivesMapper.appFindByParentId(page, tArchives);
        return tArchivesIPage;
    }
}

