package com.njcn.process.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.process.mapper.SupvFileMapper;
import com.njcn.process.pojo.param.SupvFileParam;
import com.njcn.process.pojo.po.SupvFile;
import com.njcn.process.pojo.po.SupvPlan;
import com.njcn.process.pojo.po.SupvProblem;
import com.njcn.process.service.ISupvFileService;
import com.njcn.process.service.ISupvPlanService;
import com.njcn.process.service.ISupvProblemService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.pojo.po.DictData;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2023-06-21
 */
@Service
@RequiredArgsConstructor
public class SupvFileServiceImpl extends ServiceImpl<SupvFileMapper, SupvFile> implements ISupvFileService {


    private final FileStorageUtil fileStorageUtil;
    private final ISupvProblemService supvProblemService;
    private final ISupvPlanService supvPlanService;
    private final DicDataFeignClient dicDataFeignClient;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean planUpload(MultipartFile file,
                              String planId,
                              Integer type,
                              String uploaderId,
                              String uploaderName,
                              String attachmentType,
                              String uploadTime) {
        Boolean fly;
        SupvFile supvFile = this.getOne(new LambdaQueryWrapper<SupvFile>().eq(SupvFile::getBusiId,planId).eq(SupvFile::getType,type).eq(SupvFile::getAttachmentType,attachmentType));
        String url = fileStorageUtil.uploadMultipart(file, OssPath.SURVEY_RESULT);
        SupvFile supvFilePO = new SupvFile();
        supvFilePO.setAttachmentName(file.getOriginalFilename());
        supvFilePO.setFileUrl(url);
        supvFilePO.setAttachmentType(attachmentType);
        supvFilePO.setBusiId(planId);
        supvFilePO.setType(type);
        supvFilePO.setUploaderId(uploaderId);
        supvFilePO.setUploadTime(DateUtil.parseLocalDateTime(uploadTime));
        supvFilePO.setUploaderName(uploaderName);
        if(Objects.nonNull(supvFile)){
            fileStorageUtil.deleteFile(supvFile.getFileUrl());
            supvFilePO.setUuid(supvFile.getUuid());
            supvFilePO.setIsUploadHead(supvFile.getIsUploadHead());
            fly= this.updateById(supvFilePO);
//            updateTime(type,planId,uploadTime,attachmentType,supvFile.getUuid());
        }else{
            supvFilePO.setCreateTime(LocalDateTime.now());
            supvFilePO.setIsUploadHead(0);
            fly= this.save(supvFilePO);
//            updateTime(type,planId,uploadTime,attachmentType,null);
        }
        return fly;
    }

    @Override
    public List<SupvFile> listFile(SupvFileParam param) {
        if (param.getType()==0){
            return this.baseMapper.selectPlanFile(param);
        }else if(param.getType()==1){
            return this.baseMapper.selecProblemtFile(param);
        }else {
            return this.baseMapper.selectSimpleFile(param);
        }

    }

    @Override
    public String detail(HttpServletResponse response,String busId, Integer type,String attachmentType) {
        SupvFile supvFile = this.getOne(new LambdaQueryWrapper<SupvFile>().eq(SupvFile::getBusiId,busId).eq(SupvFile::getType,type).eq(SupvFile::getAttachmentType,attachmentType));
        if(Objects.nonNull(supvFile)){
            fileStorageUtil.downloadStream(response,supvFile.getFileUrl());
            return null;
        }else {
            throw new BusinessException("不存在附件");
        }
    }

    @Override
    public Boolean delFile(List<String> ids) {
        List<SupvFile> supvFiles = this.listByIds(ids);
        for(SupvFile supvFile : supvFiles){
            fileStorageUtil.deleteFile(supvFile.getFileUrl());
        }
        this.removeByIds(ids);
        return true;
    }

    /**
     * @Description:
     * @param type 区分问题计划
     * @param planId 业务id（问题id）
     * @param uploadTime 上传时间
     * @param attachmentType 下拉选择类型
     * @param id 附件id
     * @Author: wr
     * @Date: 2023/9/12 8:59
     */
   private void updateTime(Integer type,String planId,String uploadTime,String attachmentType,String id){
       DictData stamped_report = dicDataFeignClient.getDicDataByCode("Stamped_Report").getData();
        if(type==1&&attachmentType.equals(stamped_report.getId())){
            //获取问题信息,查询所有问题
            SupvProblem byId = supvProblemService.getById(planId);
            List<SupvProblem> list = supvProblemService.list(new LambdaQueryWrapper<SupvProblem>()
                    .eq(SupvProblem::getPlanId, byId.getPlanId()));
            if(list.size()<2){
                supvPlanService.update(new LambdaUpdateWrapper<SupvPlan>()
                        .eq(SupvPlan::getPlanId,list.get(0).getPlanId())
                        .set(SupvPlan::getReportIssueTime,uploadTime)
                );
            }else{
                //根据问题查询上传附件信息，在排序取第一条
                List<String> ids = list.stream().map(SupvProblem::getProblemId).collect(Collectors.toList());
                List<SupvFile> files = this.list(new LambdaQueryWrapper<SupvFile>()
                        .in(SupvFile::getBusiId, ids)
                        .eq(SupvFile::getType, type)
                        .eq(SupvFile::getAttachmentType, stamped_report.getId())
                        .orderByAsc(SupvFile::getCreateTime)
                );
                if(CollUtil.isNotEmpty(files)){
                    if(files.get(0).getUuid().equals(id)){
                        supvPlanService.update(new LambdaUpdateWrapper<SupvPlan>()
                                .eq(SupvPlan::getPlanId,list.get(0).getPlanId())
                                .set(SupvPlan::getReportIssueTime,uploadTime));
                    }
                }

            }
        }

    }
}
