package cn.cslg.pas.service;

import cn.cslg.pas.common.model.PersonnelVO;
import cn.cslg.pas.common.model.QueryPatentVO;
import cn.cslg.pas.common.model.dto.ProductPatentDTO;
import cn.cslg.pas.common.model.vo.ProjectImportVO;
import cn.cslg.pas.common.model.vo.ProjectVO;
import cn.cslg.pas.common.utils.*;
import cn.cslg.pas.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.pas.domain.*;
import cn.cslg.pas.mapper.PatentMapper;
import cn.cslg.pas.mapper.ProjectImportMapper;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【os_thematic_import(专题库数据导入记录)】的数据库操作Service
 * @createDate 2022-05-19 10:55:10
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class ProjectImportService extends ServiceImpl<ProjectImportMapper, ProjectImport> {

    private final FileUtils fileUtils;
    private final ProjectImportStatusService projectImportStatusService;
    private final PatentMapper patentMapper;
    private final ProjectPatentLinkService projectPatentLinkService;
    private final RequestService requestService;
    private final CacheUtils cacheUtils;
    private final LoginUtils loginUtils;

    public IPage<ProjectImport> getPageList(ProjectImportVO params) throws IOException {
        //当查询使用发起人名称时
        if (params.getCreateName() != null && !params.getCreateName().equals("")) {
            String res = requestService.getPersonIdByNamePCS(params.getCreateName());
            List<Integer> createIds = JSONArray.parseArray(res, Integer.class);
            params.setCreateIds(createIds);
            //当未查询到时直接返回空页
            if (createIds == null || createIds.size() == 0) {
                //params.setCreateIds(Arrays.asList(-1));
                params.setCreateIds(Collections.singletonList(-1));
            }
        }
        PersonnelVO personnelVO =cacheUtils.getLoginUserPersonnel(loginUtils.getId());
        params.setTenantId(personnelVO.getTenantId());
        IPage<ProjectImport> pageList = baseMapper.getPageList(new Page<>(params.getCurrent(), params.getSize()), params);
        this.setDataList(pageList.getRecords());
        return pageList;
    }

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

    public Integer add(Integer userId, String url,Integer tenantId) {
        File file = new File(fileUtils.getSystemPath(url));
        ProjectImport projectImport = new ProjectImport();
        projectImport.setCreateBy(userId);
        projectImport.setCreateTime(new Date());
        projectImport.setUrl(url);
        projectImport.setFileSize(FileUtil.size(file));
        projectImport.setFileName(file.getName());
        projectImport.setTenantId(tenantId);
        projectImport.insert();
        return projectImport.getId();
    }

    /**
     * 给产品添加相关专利
     */
    @Transactional
    public List<String> importByNos(ProjectImportVO patentDTO) {
        List<String> orgPatentNos = new ArrayList<>();
        if (patentDTO.getPatentNo() != null) {
            patentDTO.setPatentNo(patentDTO.getPatentNo().replace(" ", ""));
            if (!patentDTO.getPatentNo().equals("")) {
                String[] strs = patentDTO.getPatentNo().split("\\|");
                orgPatentNos = new ArrayList<>(Arrays.asList(strs));
                QueryPatentVO params = new QueryPatentVO();
                params.setPatentNo(patentDTO.getPatentNo());
                params.setPatentNos(orgPatentNos);
                List<Patent> patents = patentMapper.getConPantents(params);
                List<String> patentNos = patents.stream().map(Patent::getPatentNo).collect(Collectors.toList());
                orgPatentNos.removeAll(patentNos);
                if (patents.size() > 0) {
                    List<ProjectPatentLink> projectPatentLinkList = new ArrayList<>();
                    patents.forEach(item -> {
                        ProjectPatentLink projectPatentLink = new ProjectPatentLink();
                        projectPatentLink.setProjectId(patentDTO.getProjectId());
                        projectPatentLink.setPatentId(item.getId());
                        projectPatentLinkList.add(projectPatentLink);
                    });
                    projectPatentLinkService.saveBatch(projectPatentLinkList);
                }
            }
        }
        return orgPatentNos;
    }

    private void setDataList(List<ProjectImport> importList) throws IOException {
        //获得创建人的id集合
        //List<Integer> createIds = importList.stream().map(ProjectImport::getCreateBy).collect(Collectors.toList());
        ArrayList<Integer> createPersonIds = new ArrayList<>();
        for (ProjectImport projectImport : importList) {
            createPersonIds.add(projectImport.getCreateBy());
        }

        //获取专题库负责人对应信息
        String jsonObject1 = requestService.getPersonnelFromPCS(createPersonIds);
        JSONArray jsonArray = JSON.parseArray(jsonObject1);
        List<ProjectVO.Personnel> personnelList = jsonArray.toJavaList(ProjectVO.Personnel.class);
        for (ProjectImport projectImport : importList) {
            for (ProjectVO.Personnel personnel : personnelList) {
                //装载创建人名
                if (projectImport.getCreateBy() != null) {
                    if (projectImport.getCreateBy().equals(personnel.getId())) {
                        projectImport.setCreateName(personnel.getPersonnelName());
                    }
                }

            }
        }
    }
}
