package cn.cslg.pas.service;

import cn.cslg.pas.common.core.base.Constants;
import cn.cslg.pas.common.model.vo.UploadParamsVO;
import cn.cslg.pas.common.utils.*;
import cn.cslg.pas.common.model.dto.UploadFileDTO;
import cn.cslg.pas.domain.Patent;
import cn.cslg.pas.domain.PatentImage;
import cn.cslg.pas.mapper.PatentImageMapper;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.PictureData;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 专利信息附图表 服务类
 * </p>
 *
 * @author 王岩
 * @since 2022-02-24
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class PatentImageService extends ServiceImpl<PatentImageMapper, PatentImage> {

    private final FileUtils fileUtils;
    private final PatentService patentService;

    public List<PatentImage> getPatentImageByPatentId(Integer patentId) {
        LambdaQueryWrapper<PatentImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PatentImage::getPatentId, patentId);
        return this.list(queryWrapper);
    }

    public List<PatentImage> getPatentImageByPatentIds(List<Integer> patentIds) {
        if (patentIds == null || patentIds.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<PatentImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PatentImage::getPatentId, patentIds);
        return this.list(queryWrapper);
    }

    public PatentImage getPatentImageByPatentIdAndStatus(Integer patentId, Integer status) {
        LambdaQueryWrapper<PatentImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PatentImage::getPatentId, patentId);
        queryWrapper.eq(PatentImage::getStatus, status);
        return this.getOne(queryWrapper);
    }

    /**
     * 摘要附图表"os_patent_img"新增专利摘要附图方法（Excel方式）
     *
     * @param patentId    专利id
     * @param pictureData 摘要附图
     * @return 返回摘要附图路径
     */
    public String updatePatentImage(Integer patentId, PictureData pictureData) throws IOException {
        //专利附图表"os_patent_img"根据专利id删除该专利的摘要图片数据，以免上传重复
        this.deleteByPatentIdAndStatus(patentId, 1);
        //调用方法将图片上传至本地图片文件夹下，并返回图片的文件名称和文件路径
        Map<String, String> result = ExcelUtils.savePicture(pictureData);
        //专利附图表实体类装载数据
        PatentImage patentImage = new PatentImage();
        patentImage.setStatus(1);
        patentImage.setPatentId(patentId);
        patentImage.setUrl(result.get("path"));
        patentImage.setFileName(result.get("name"));
        //数据入库
        patentImage.insert();
        return patentImage.getUrl();
    }

    /**
     * 摘要附图表"os_patent_img"新增专利摘要附图方法（网站导入方式）
     *
     * @param uploadParamsVO 专利实体类对象
     * @return 返回摘要附图路径
     */
    public String updatePatentImage2(UploadParamsVO uploadParamsVO) throws IOException {
        //专利附图表"os_patent_img"根据专利id删除该专利的摘要图片数据，以免上传重复
        this.deleteByPatentIdAndStatus(uploadParamsVO.getPatent().getId(), 1);

        //专利附图表实体类装载数据
        PatentImage patentImage = new PatentImage();
        patentImage.setStatus(1);
        patentImage.setPatentId(uploadParamsVO.getPatent().getId());
        patentImage.setUrl(uploadParamsVO.getFileDTO().getPath());
        patentImage.setFileName(uploadParamsVO.getFileDTO().getFileName());
        //数据入库
        patentImage.insert();
        return patentImage.getUrl();
    }

    public void delete(Integer id) {
        PatentImage temp = this.getById(id);
        this.removeById(id);
        if (StringUtils.isNotEmpty(temp.getUrl())) {
            FileUtil.del(fileUtils.getSystemPath(temp.getUrl()));
        }
    }

    public void deleteByPatentIdAndStatus(Integer patentId, Integer status) {
        this.remove(Wrappers.<PatentImage>lambdaQuery().eq(PatentImage::getPatentId, patentId).eq(PatentImage::getStatus, status));
    }

    @Transactional
    public String add(MultipartFile file, PatentImage patentImage) {
        if (file == null || file.isEmpty()) {
            return Response.error("请选择文件");
        }
        UploadFileDTO fileDTO = fileUtils.uploadFile(file);
        patentImage.setUrl(fileDTO.getPath());
        patentImage.setFileName(fileDTO.getFileName());
        patentImage.insert();
        this.updatePatenAbstractPath(patentImage);
        return Response.success(patentImage.getId());
    }

    @Transactional
    public String edit(MultipartFile file, PatentImage patentImage) {
        if (file != null && !file.isEmpty()) {
            if (StringUtils.isNotEmpty(patentImage.getUrl())) {
                FileUtil.del(fileUtils.getSystemPath(patentImage.getUrl()));
            }
            UploadFileDTO fileDTO = fileUtils.uploadFile(file);
            patentImage.setUrl(fileDTO.getPath());
            patentImage.setFileName(fileDTO.getFileName());
        }
        patentImage.updateById();
        this.updatePatenAbstractPath(patentImage);
        return Response.success(true);
    }

    private void updatePatenAbstractPath(PatentImage patentImage) {
        if (patentImage.getStatus() == 1) {
            Patent patent = patentService.getById(patentImage.getPatentId());
            patent.setAbstractPath(patentImage.getUrl());
            patent.updateById();
        }
    }

    public void importPatentImage(String tempPath, String patentIdPatentNoJson, String patentImageJson) {
        List<Patent> importPatentList = JsonUtils.jsonToList(patentIdPatentNoJson, Patent.class);
        List<Patent> localPatentList = patentService.getPatentListByPatentNo(importPatentList.stream().map(Patent::getPatentNo).collect(Collectors.toList()));
        List<PatentImage> localPatentImageList = this.getPatentImageByPatentIds(localPatentList.stream().map(Patent::getId).collect(Collectors.toList()));
        List<PatentImage> importPatentImageList = JsonUtils.jsonToList(patentImageJson, PatentImage.class);
        for (PatentImage patentImage : importPatentImageList) {
            String fileName = IdUtil.simpleUUID() + "." + FileUtil.extName(patentImage.getFileName());
            String saveUrl = fileUtils.getDirectory(fileName);
            String savePath = fileUtils.getSystemPath(saveUrl);
            String tempImage = tempPath + FileUtils.FILE_SEPARATOR + Constants.PATENT_IMAGE_DIRECTORY_NAME + FileUtils.FILE_SEPARATOR + patentImage.getFileName();
            String patentNo = importPatentList.stream().filter(item -> item.getId().equals(patentImage.getPatentId())).findFirst().orElse(new Patent()).getPatentNo();
            Patent localPatent = localPatentList.stream().filter(item -> item.getPatentNo().equals(patentNo)).findFirst().orElse(null);
            if (localPatent == null) {
                continue;
            }
            patentImage.setPatentId(localPatent.getId());
            patentImage.setUrl(saveUrl);
            patentImage.setFileName(fileName);
            patentImage.setId(null);
            if (FileUtil.exist(tempImage)) {
                if (patentImage.getStatus().equals(1)) {
                    Patent patent = patentService.getById(localPatent.getId());
                    patent.setAbstractPath(saveUrl);
                    patent.updateById();
                }
                patentImage.insert();
                FileUtil.copy(tempImage, savePath, true);
            }
        }
        localPatentImageList.forEach(item -> {
            item.deleteById();
            FileUtil.del(fileUtils.getSystemPath(item.getUrl()));
        });
    }
}
