package cn.cslg.report.service.business;

import cn.cslg.report.common.model.vo.PersonnelVO;
import cn.cslg.report.common.utils.CacheUtils;
import cn.cslg.report.common.utils.Response;
import cn.cslg.report.common.utils.SecurityUtils.LoginUtils;

import cn.cslg.report.entity.ReportFiles;
import cn.cslg.report.entity.ReportReferences;


import cn.cslg.report.entity.asso.AssoReportReferences;

import cn.cslg.report.mapper.ReportReferencesMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
@SuppressWarnings({"all"})
public class ReportReferencesService extends ServiceImpl<ReportReferencesMapper, ReportReferences> {
    private final ReportFileService reportFileService;
    private final LoginUtils loginUtils;

    private final CacheUtils cacheUtils;
    private final ReportService reportService;
    private final AssoReportReferencesService assoReportReferencesService;
    public String add(ReportReferences reportReferences, List<MultipartFile> files)throws IOException{
        ReportReferences i = new ReportReferences();
        i.setReportID(reportReferences.getReportID());
        i.setCreationTime(new Date());
        i.setType(reportReferences.getType());
        i.setFileName(reportReferences.getFileName());
        i.setFileUrl(reportReferences.getFileUrl());
        i.setRemark(reportReferences.getRemark());
        i.setCreationManId(loginUtils.getId());
        i.setType(reportReferences.getType());
        i.setReferName(reportReferences.getReferName());
        i.insert();
        if (files != null && files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<Integer> fileIds = reportFileService.uploadFiles(files);
            assoReportReferencesService.add(i.getId(),fileIds);
            return Response.success();
        }

        return  Response.error();
    }

    /**
     *   查询分三种情况合在一起：
     *                     { 1：普通查询
     *                       2：分页查询
     *                       3：根据文件名模糊查询
     *                     }
     * @antor：chenyi
     * @param reportReferences
     * @return
     * @throws IOException
     */
    public String queryReportReferences(ReportReferences reportReferences)throws IOException{
        LambdaQueryWrapper<ReportReferences> wrapper = new LambdaQueryWrapper<>();
        PersonnelVO personnelVO =cacheUtils.getLoginUser(loginUtils.getId());
        String name = reportService.getName(reportReferences.getReportID());
        //根据报告id 查询报告文档上传表
        wrapper.eq(ReportReferences::getReportID,reportReferences.getReportID());

        wrapper.orderByDesc(ReportReferences::getId);

        List<ReportReferences> list=new ArrayList<>();
       //分页查询
        if(reportReferences.getSize()!=null&&reportReferences.getCurrent()!=null){
            IPage<ReportReferences> pages = this.page(new Page<>(reportReferences.getCurrent(), reportReferences.getSize()), wrapper);
            List<ReportReferences> records = pages.getRecords();

            for(ReportReferences references :records) {
                //根据id的精确查询和文件名的模糊查询
                List<ReportFiles> reportFiles = this.ReportReferences(references.getId(), reportReferences.getFileName());
                if (reportFiles.size() != 0) {

                    references.setPersonName(personnelVO.getName());

                    references.setReportName(name);

                    references.setReportFiles(reportFiles);
                    list.add(references);
                }
            }

           pages.setRecords(list);
            return Response.success(pages);
        }


        List<ReportReferences> list1 = this.list(wrapper);
        for(ReportReferences references:list1){
            List<ReportFiles> reportFiles = this.ReportReferences(references.getId(), reportReferences.getFileName());
            if (reportFiles.size() != 0) {

                references.setPersonName(personnelVO.getName());

                references.setReportName(name);
                references.setReportFiles(reportFiles);
                list.add(references);
            }

        }
        List<ReportReferences> l=new ArrayList<>(list);

        return Response.success(list);

    }

    /**
     * @antor:chenyi
     * @param id
     * @return
     * @throws IOException
     */
    public String delete(int id)throws IOException{
        this.removeById(id);
        //找到AssoReportReferences文件id
        LambdaQueryWrapper<AssoReportReferences> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AssoReportReferences::getReportReferencesID,id);
        List<AssoReportReferences> list = assoReportReferencesService.list(wrapper);
        //删除对应的文件
        reportFileService.removeByIds( list.stream().map(AssoReportReferences::getFileID).collect(Collectors.toList()));
        assoReportReferencesService.remove(wrapper);

       return Response.success();

    }

    public List<ReportFiles> ReportReferences(int id ,String str){
        //根据ReportReferences的id找到AssoReportReferences关联表的对象
        List<AssoReportReferences> select = assoReportReferencesService.select(id);
        //找到文件ReportFiles的id
        List<Integer> collect = select.stream().map(AssoReportReferences::getFileID).collect(Collectors.toList());
        if(collect.size()==0){
            return null;
        }
        LambdaQueryWrapper<ReportFiles> wrapper = new LambdaQueryWrapper<>();
        //根据ReportFiles的id和文件名
        wrapper.in(ReportFiles::getId, collect);
        if(str!=null&&str!=""){
            wrapper.like(ReportFiles::getName,str);
        }
        List<ReportFiles> reportFiles = reportFileService.list(wrapper);
        return reportFiles;

    }

    /**
     * 判断传过来的文件集合是否为空
     * 为空：只改reportReferences实体所对应的表
     * 不为空： 先改reportReferences实体所对应的表
     * 在删除关联AssoReportReferences 关联表的内容
     * 在删除  reportFile内容
     * 重新插入 reportFile
     * 在插入 关联AssoReportReferences 关联表的内容
     *
     * @param reportReferences
     * @param files
     * @return
     * @throws IOException
     */

    public Boolean updateReportReferences(ReportReferences reportReferences,List<MultipartFile> files)throws IOException{
        if(files!=null && files.size() != 0 ){
            LambdaQueryWrapper<AssoReportReferences> wrapper =new LambdaQueryWrapper<>();
            wrapper.eq(AssoReportReferences::getReportReferencesID,reportReferences.getId());
            List<AssoReportReferences> list = assoReportReferencesService.list(wrapper);
            List<Integer> collect = list.stream().map(AssoReportReferences::getFileID).collect(Collectors.toList());
                assoReportReferencesService.remove(wrapper);
                reportFileService.removeByIds(collect);
                List<Integer> fileIdList = reportFileService.uploadFiles(files);
                assoReportReferencesService.add(reportReferences.getId(),fileIdList);
        }
        return reportReferences.updateById();
    }

/**
 * function :删除报告的时候删除
 */
  @Transactional(rollbackFor = Exception.class)
  public String deleteByReportId(Integer id){
      LambdaQueryWrapper<ReportReferences> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(ReportReferences::getReportID,id);
      remove(wrapper);
      return Response.success();
  }






}
