package com.qmth.paper.library.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.paper.library.business.bean.result.DocManageDetailResult;
import com.qmth.paper.library.business.bean.result.DocManageOtherDetailResult;
import com.qmth.paper.library.business.bean.result.DocManageResult;
import com.qmth.paper.library.business.bean.result.DocManageStatResult;
import com.qmth.paper.library.business.bean.vo.FilePathVo;
import com.qmth.paper.library.business.entity.PaperLibraryOther;
import com.qmth.paper.library.business.mapper.DocManageMapper;
import com.qmth.paper.library.business.service.DocManageService;
import com.qmth.paper.library.business.service.FileUploadService;
import com.qmth.paper.library.business.service.PaperLibraryOtherService;
import com.qmth.paper.library.business.service.PaperLibraryService;
import com.qmth.paper.library.common.bean.params.DownLoadPaperParams;
import com.qmth.paper.library.common.entity.SysUser;
import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import com.qmth.paper.library.common.service.LibraryCommonService;
import com.qmth.paper.library.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 文档管理 服务实现类
 * </p>
 */
@Service
public class DocManageServiceImpl implements DocManageService {
    @Resource
    private DocManageMapper docManageMapper;
    @Resource
    private PaperLibraryService paperLibraryService;
    @Resource
    private LibraryCommonService libraryCommonService;
    @Resource
    private PaperLibraryOtherService paperLibraryOtherService;
    @Resource
    private FileUploadService fileUploadService;

    @Override
    public IPage<DocManageResult> pageData(Long semesterId, Long examId, String courseCode, Integer pageNumber, Integer pageSize) {
//        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
//        Set<Long> orgIds = libraryCommonService.listSubOrgIds(sysUser.getOrgId());
        return docManageMapper.pageData(new Page<>(pageNumber, pageSize), semesterId, examId, courseCode, null);
    }

    @Override
    public DocManageStatResult statData(Long semesterId, Long examId, String courseCode) {
//        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
//        Set<Long> orgIds = libraryCommonService.listSubOrgIds(sysUser.getOrgId());
        return docManageMapper.statData(semesterId, examId, courseCode, null);
    }

    @Override
    public IPage<DocManageDetailResult> pageDetail(Long paperScanTaskId, String collegeName, String majorName, String className, String examRoom, String teacher, String teachClass, Boolean isBind, String param, Double minScore, Double maxScore, Integer minBindCount, Integer maxBindCount, String pictureSymbol, Integer pictureCount, Integer pageNumber, Integer pageSize) {
        IPage<DocManageDetailResult> detailResultIPage = docManageMapper.pageDetail(new Page<>(pageNumber, pageSize), paperScanTaskId, collegeName, majorName, className, examRoom, teacher, teachClass, isBind, param, minScore, maxScore, minBindCount, maxBindCount, pictureSymbol, pictureCount);
        for (DocManageDetailResult record : detailResultIPage.getRecords()) {
            List<String> batchNoList = paperLibraryService.listBatchNo(record.getStudentId());
            if(!batchNoList.isEmpty()) {
                record.setBatchNo(String.join(",", batchNoList));
            }
        }
        return detailResultIPage;
    }

    @Override
    public List<DocManageDetailResult> listDetail(DownLoadPaperParams downLoadPaperParams) {
        String ids = downLoadPaperParams.getIds();
        List<DocManageDetailResult> docManageDetailResults;
        if (StringUtils.isNotBlank(ids) && ids.split(",").length > 0) {
            String[] idsArray = ids.split(",");
            docManageDetailResults = docManageMapper.listDetail(downLoadPaperParams.getPaperScanTaskId(), Arrays.asList(idsArray));
        } else {
            Long paperScanTaskId = downLoadPaperParams.getPaperScanTaskId();
            if (paperScanTaskId == null) {
                throw ExceptionResultEnum.ERROR.exception("扫描任务ID必传");
            }
            String collegeName = downLoadPaperParams.getCollegeName();
            String majorName = downLoadPaperParams.getMajorName();
            String className = downLoadPaperParams.getClassName();
            String courseName = downLoadPaperParams.getCourseName();
            String teacher = downLoadPaperParams.getTeacher();
            String teachClass = downLoadPaperParams.getTeachClass();
            Boolean isBind = downLoadPaperParams.getIsBind() == null ? null : downLoadPaperParams.getIsBind() == 1;
            String param = downLoadPaperParams.getParam();
            Double minScore = downLoadPaperParams.getMinScore();
            Double maxScore = downLoadPaperParams.getMaxScore();
            Integer minBindCount = downLoadPaperParams.getMinBindCount();
            Integer maxBindCount = downLoadPaperParams.getMaxBindCount();
            String pictureSymbol = downLoadPaperParams.getPictureSymbol();
            Integer pictureCount = downLoadPaperParams.getPictureCount();
            docManageDetailResults = docManageMapper.pageDetail(paperScanTaskId, collegeName, majorName, className, courseName, teacher, teachClass, isBind, param, minScore, maxScore, minBindCount, maxBindCount, pictureSymbol, pictureCount);
        }
        return docManageDetailResults;
    }

    @Override
    public IPage<DocManageOtherDetailResult> pageOtherDetail(Long paperScanTaskId, Integer pageNumber, Integer pageSize) {
        QueryWrapper<PaperLibraryOther> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PaperLibraryOther::getPaperScanTaskId, paperScanTaskId)
                .orderByAsc(PaperLibraryOther::getCreateTime);
        Page<PaperLibraryOther> paperLibraryOtherPage = paperLibraryOtherService.page(new Page<>(pageNumber, pageSize), queryWrapper);
        List<DocManageOtherDetailResult> list = new ArrayList<>();
        for (PaperLibraryOther record : paperLibraryOtherPage.getRecords()) {
            DocManageOtherDetailResult docManageOtherDetailResult = new DocManageOtherDetailResult();
            List<FilePathVo> filePathVos = JSON.parseArray(record.getPath(), FilePathVo.class);
            List<String> fileNames = new ArrayList<>();
            List<String> fileUrls = new ArrayList<>();
            for (FilePathVo filePathVo : filePathVos) {
                // 截取文件名
                String fileName = filePathVo.getPath();
                fileNames.add(fileName.substring(fileName.replaceAll("\\\\", "/").lastIndexOf("/") + 1));
                // 拼接可访问地址
                fileUrls.add(fileUploadService.filePreview(filePathVo));
            }
            docManageOtherDetailResult.setFileName(String.join("，", fileNames));
            docManageOtherDetailResult.setFileUrls(fileUrls);
            list.add(docManageOtherDetailResult);
        }

        Page<DocManageOtherDetailResult> page = new Page(pageNumber, pageSize);
        page.setRecords(list);
        page.setTotal(paperLibraryOtherPage.getTotal());
        page.setPages(paperLibraryOtherPage.getPages());
        return page;
    }


}
