package cn.cslg.pas.service;

import cn.cslg.pas.common.core.base.Constants;
import cn.cslg.pas.common.model.BaseEntity;
import cn.cslg.pas.common.model.vo.ProjectFileVO;
import cn.cslg.pas.common.utils.*;
import cn.cslg.pas.common.model.dto.UploadFileDTO;
import cn.cslg.pas.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.pas.domain.Personnel;
import cn.cslg.pas.domain.ProjectFile;
import cn.cslg.pas.mapper.ProjectFileMapper;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 专题库附件表 服务实现类
 * </p>
 *
 * @author 王岩
 * @since 2022-01-24
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class ProjectFileService extends ServiceImpl<ProjectFileMapper, ProjectFile> {
    private final FileUtils fileUtils;
    private final LoginUtils loginUtils;
    private final OutInterfaceService outInterfaceService;

    public IPage<ProjectFile> getPageList(ProjectFileVO params) throws IOException {
        //分页查询列表
        IPage<ProjectFile> pageList = baseMapper.getPageList(new Page<>(params.getCurrent(), params.getSize()), params);
        //从分页结果中获取列表
        List<ProjectFile> projectFiles = pageList.getRecords();
        ArrayList<Integer> personnelIds = new ArrayList<>();
        for (ProjectFile projectFile : projectFiles) {
            personnelIds.add(projectFile.getCreateBy());
        }
        //调用权限系统接口根据人员ids查询人员列表
        String res = outInterfaceService.getPersonnelByIdsFromPCS(personnelIds);
        JSONObject jsonObject = JSONObject.parseObject(res);
        List<Personnel> personnels = JSON.parseArray(jsonObject.getString("data"), Personnel.class);
        //遍历列表和人员列表，给列表装载人员名称
        for (ProjectFile projectFile : projectFiles) {
            for (Personnel personnel : personnels) {
                if (personnel.getId().equals(projectFile.getCreateBy())) {
                    projectFile.setCreateName(personnel.getPersonnelName());
                }
            }
        }
        pageList.setRecords(projectFiles);

        return pageList;
    }

    public ProjectFile getProjectFileByName(String name, Integer projectId, String type, String suffix) {
        LambdaQueryWrapper<ProjectFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectFile::getName, name);
        queryWrapper.eq(ProjectFile::getProjectId, projectId);
        queryWrapper.eq(ProjectFile::getType, type);
        queryWrapper.eq(ProjectFile::getSuffix, suffix);
        return this.getOne(queryWrapper);
    }

    public List<ProjectFile> getProjectFileByProjectId(Integer projectId) {
        LambdaQueryWrapper<ProjectFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectFile::getProjectId, projectId);
        return this.list(queryWrapper);
    }

    public List<ProjectFile> getProjectFileByIds(List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<ProjectFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProjectFile::getId, ids);
        return this.list(queryWrapper);
    }

    public List<ProjectFile> getProjectFileByProjectIds(List<Integer> projectIds) {
        if (projectIds == null || projectIds.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<ProjectFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProjectFile::getProjectId, projectIds);
        return this.list(queryWrapper);
    }

    public List<ProjectFile> getProjectFileByProjectIdAndType(Integer type, Integer projectId) {
        LambdaQueryWrapper<ProjectFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectFile::getType, type);
        queryWrapper.eq(ProjectFile::getProjectId, projectId);
        return this.list(queryWrapper);
    }

    public void importProjectFile(Integer projectId, Integer userId, String tempPath, String projectFileJson, String projectReportJson) {
        List<ProjectFile> projectFileList = new ArrayList<>();
        if (StringUtils.isNotEmpty(projectFileJson)) {
            projectFileList.addAll(JsonUtils.jsonToList(projectFileJson, ProjectFile.class));
        }
        if (StringUtils.isNotEmpty(projectReportJson)) {
            projectFileList.addAll(JsonUtils.jsonToList(projectReportJson, ProjectFile.class));
        }
        for (ProjectFile projectFile : projectFileList) {
            String copyPath = tempPath + FileUtils.FILE_SEPARATOR + (projectFile.getType().equals("1") ? Constants.PROJECT_REPORT_DIRECTORY_NAME : Constants.PROJECT_FILE_DIRECTORY_NAME) + FileUtils.FILE_SEPARATOR + projectFile.getFileName();
            if (!FileUtil.exist(copyPath)) {
                continue;
            }
            String extName = FileUtil.extName(projectFile.getFileName());
            String fileName = IdUtil.simpleUUID() + "." + extName;
            String saveUrl = fileUtils.getDirectory(fileName);
            String savePath = fileUtils.getSystemPath(saveUrl);
            ProjectFile temp = this.getProjectFileByName(projectFile.getName(), projectId, projectFile.getType(), extName);
            if (temp == null) {
                temp = new ProjectFile();
                temp.setCreateBy(userId);
                temp.setCreateTime(DateUtils.getDateTime());
                temp.setProjectId(projectId);
                temp.setName(projectFile.getName());
                temp.setType(projectFile.getType());
                temp.setRemark(projectFile.getRemark());
            } else {
                FileUtil.del(fileUtils.getSystemPath(temp.getUrl()));
            }
            File file = FileUtil.copy(copyPath, savePath, true);
            temp.setUrl(saveUrl);
            temp.setFileName(fileName);
            temp.setSize((int) FileUtil.size(file));
            temp.insertOrUpdate();
        }
    }

    public String add(ProjectFile projectFile, MultipartFile file) {
        ProjectFile temp = this.getProjectFileByName(projectFile.getName(), projectFile.getProjectId(), projectFile.getType(), FileUtil.extName(file.getOriginalFilename()));
        if (temp != null) {
            return Response.error("文件名称已存在");
        }
        UploadFileDTO fileDTO = fileUtils.uploadFile(file);
        projectFile.setSize((int) file.getSize());
        projectFile.setUrl(fileDTO.getPath());
        projectFile.setFileName(fileDTO.getFileName());
        projectFile.setCreateTime(DateUtils.getDateTime());
        projectFile.setCreateBy(loginUtils.getId());
        projectFile.setSuffix(fileDTO.getExtName());
        projectFile.insert();
        return Response.success(projectFile.getId());
    }

    public String edit(ProjectFile projectFile, MultipartFile file) {
        if (StringUtils.isNotNull(file)) {
            ProjectFile temp = this.getProjectFileByName(projectFile.getName(), projectFile.getProjectId(), projectFile.getType(), FileUtil.extName(file.getOriginalFilename()));
            if (temp != null && !temp.getId().equals(projectFile.getId())) {
                return Response.error("文件名称已存在");
            }
            if (StringUtils.isNotEmpty(projectFile.getUrl())) {
                FileUtil.del(fileUtils.getSystemPath(projectFile.getUrl()));
            }
            UploadFileDTO fileDTO = fileUtils.uploadFile(file);
            projectFile.setSize((int) file.getSize());
            projectFile.setUrl(fileDTO.getPath());
            projectFile.setFileName(fileDTO.getFileName());
            projectFile.setSuffix(fileDTO.getExtName());
        } else {
            File localFile = FileUtil.file(fileUtils.getSystemPath(projectFile.getUrl()));
            ProjectFile temp = this.getProjectFileByName(projectFile.getName(), projectFile.getProjectId(), projectFile.getType(), FileUtil.extName(localFile.getName()));
            if (temp != null && !temp.getId().equals(projectFile.getId())) {
                return Response.error("文件名称已存在");
            }
        }
        projectFile.updateById();
        return Response.success();
    }

    public String delete(Integer id) {
        ProjectFile temp = this.getById(id);
        this.removeById(id);
        if (StringUtils.isNotEmpty(temp.getUrl())) {
            FileUtil.del(fileUtils.getSystemPath(temp.getUrl()));
        }
        return Response.success(true);
    }

    public void deleteByProjectId(Integer projectId) {
        List<ProjectFile> projectFileList = this.getProjectFileByProjectId(projectId);
        for (ProjectFile projectFile : projectFileList) {
            FileUtil.del(fileUtils.getSystemPath(projectFile.getUrl()));
        }
        this.remove(Wrappers.<ProjectFile>lambdaQuery().eq(ProjectFile::getProjectId, projectId));
    }

}
