package com.jeeplus.test.cw.reportCancellApplyArchived.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.service.FlowTaskService;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.common.CommonUtils;
import com.jeeplus.test.cw.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.test.cw.projectReport.domain.CwProjectInfoData;
import com.jeeplus.test.cw.projectReport.domain.CwProjectReport;
import com.jeeplus.test.cw.projectReport.domain.CwProjectReportData;
import com.jeeplus.test.cw.projectReport.mapper.CwProjectInfoMapper;
import com.jeeplus.test.cw.projectReport.mapper.CwProjectReportMapper;
import com.jeeplus.test.cw.projectReportArchive.service.dto.WorkAttachmentArchiveDto;
import com.jeeplus.test.cw.reportCancellApply.domain.ReportCancellApply;
import com.jeeplus.test.cw.reportCancellApply.mapper.ReportCancellApplyMapper;
import com.jeeplus.test.cw.reportCancellApplyArchived.domain.CwProjectReportApplyArchive;
import com.jeeplus.test.cw.reportCancellApplyArchived.mapper.ReportCancellApplyArchivedMapper;
import com.jeeplus.test.cw.reportCancellApplyArchived.service.dto.ApplyArchiveReportDTO;
import com.jeeplus.test.cw.reportCancellApplyArchived.service.dto.ArchivedReportInfoDto;
import com.jeeplus.test.cw.reportCancellApplyArchived.service.dto.CwWorkAttachmentArchiveDto;
import com.jeeplus.test.mould.service.SerialnumTplService;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.mapper.OssServiceMapper;
import com.jeeplus.test.oss.service.OssService;
import com.jeeplus.test.workContract.service.dto.WorkAttachmentDto;
import liquibase.pro.packaged.A;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: 王强
 * @create: 2022-11-18 17:36
 **/
@Service
@Transactional
public class ReportCancellApplyArchivedService extends ServiceImpl<ReportCancellApplyArchivedMapper, CwProjectReportApplyArchive> {

    @Resource
    private ReportCancellApplyArchivedMapper applyMapper;

    @Resource
    private SerialnumTplService serialnumTplService;

    @Resource
    private OssServiceMapper ossServiceMapper;

    @Resource
    private ReportCancellApplyMapper cancellApplyMapper;

    @Resource
    private CwProjectInfoMapper infoMapper;

    @Resource
    private CwProjectReportMapper reportMapper;

    @Resource
    private OssService ossService;

    @Resource
    private FlowTaskService flowTaskService;

    /**
     * 差选项目列表信息
     *
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<ArchivedReportInfoDto> getList(Page<ArchivedReportInfoDto> page, ArchivedReportInfoDto projectReportData) throws Exception {
        QueryWrapper<ArchivedReportInfoDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(projectReportData, ArchivedReportInfoDto.class);
        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.eq("a.status", "5");
        //条件
        if (StringUtils.isNotEmpty(projectReportData.getProjectNumber())) {
            queryWrapper.like("d.project_number", projectReportData.getProjectNumber());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectName())) {
            queryWrapper.like("d.project_name", projectReportData.getProjectName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterId())) {
            queryWrapper.eq("d.project_master_id", projectReportData.getProjectMasterId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Id())) {
            queryWrapper.eq("d.real_header", projectReportData.getProjectMaster2Id());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterName())) { // 项目经理1筛选
            queryWrapper.like("g.name", projectReportData.getProjectMasterName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Name())) { // 项目经理2筛选
            queryWrapper.like("k.name", projectReportData.getProjectMaster2Name());
        }
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.like("a.create_by", projectReportData.getCreateBy().getId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getApplyFileType())) { // 状态筛选
            queryWrapper.eq("a.apply_file_type", projectReportData.getApplyFileType());
        }
        //创建时间
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_date", contractDates[0], contractDates[1]);
        }
        // 如果当前用户是部门主任，则可以查看部门所有的项目、自己创建的项目以及所属项目组的项目
        // 如果当前用户是员工，则可以查看自己创建的项目以及所属项目组的项目
        StringBuilder officeIds = new StringBuilder();
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> manageOfficeIdList= Lists.newArrayList();
        IPage<ArchivedReportInfoDto> list = applyMapper.getList(page, queryWrapper,officeIds.toString());
        list.getRecords().stream().forEach(i -> {
            // 报告作废归档
            if (StringUtils.isNotBlank(i.getArchivedTaskId()) && StringUtils.isNotBlank(i.getApplyFileType())) {
                if ("2".equals(i.getApplyFileType())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsArchived(flowTaskService.getTaskAuditUsers(i.getArchivedTaskId()));  // 获取数据审核人
                }
            }
        });
        return list;
    }

    /**
     * 根据id查询项目详情
     *
     * @param id
     * @return
     */
    public ApplyArchiveReportDTO queryById(String id) {
        //传过来的是报告作废流程表的id
        ReportCancellApply apply = cancellApplyMapper.selectById(id);
        ApplyArchiveReportDTO reportDTO = new ApplyArchiveReportDTO();
        if (null != apply) {
            //根据报告表id查出报废归档信息
            CwProjectReportApplyArchive applyArchive = applyMapper.getInfoByBFID(apply.getId());
            if (null != applyArchive) {
                reportDTO.setReportNum(applyArchive.getReportNum());
                reportDTO.setPapersNum(applyArchive.getPapersNum());
                reportDTO.setYear(applyArchive.getYear());
                reportDTO.setNumber(applyArchive.getNumber());
                reportDTO.setIsNumber(applyArchive.getIsNumber());
                reportDTO.setAuditDate(applyArchive.getAuditDate());
                reportDTO.setFileNumber(applyArchive.getFileNumber());
                reportDTO.setApplyFileType(applyArchive.getApplyFileType());
                reportDTO.setReportRemarks(applyArchive.getReportRemarks());
                reportDTO.setCarchivedType(applyArchive.getCarchivedType());
                //设置附件
                List<CwWorkAttachmentArchiveDto> files = applyMapper.selectFileInfoByAttid(applyArchive.getId());
                if (null != files) {
                    files.forEach(fi -> {
                        UserDTO userDTO = applyMapper.getUserInfo(fi.getUserId());
                        fi.setCreateBy(userDTO);
                    });
                    //附件信息
                    reportDTO.setWorkAttachmentDtoList(files);
                }
            }
            //设置项目信息
            //根据新建行id找到项目id
            CwProjectRecordsDTO recordsDTO = applyMapper.getProjectByNewLineId(apply.getReportNewLineId());
            reportDTO.setCwProjectRecordsDTO(recordsDTO);
            //设置报告文号相关信息
            //根据新建行找到签字注师信息与报告文号信息
            CwProjectInfoData byId = infoMapper.getById(apply.getReportNewLineId());
            CwProjectReport report = reportMapper.getByNewLineId(byId.getReportId());
            reportDTO.setReportNo(byId.getReportNo());
            reportDTO.setReportDate(byId.getReportDate());
            reportDTO.setReportCreateName(byId.getCreateBy());
            reportDTO.setSignatureAnnotator1Name(report.getSignatureAnnotator1Name());
            reportDTO.setSignatureAnnotator2Name(report.getSignatureAnnotator2Name());
        } else {
            //传来的是归档的id
            apply = cancellApplyMapper.selectByArchivedId(id);
            if (null != apply) {
                //根据报告表id查出报废归档信息
                CwProjectReportApplyArchive applyArchive = applyMapper.getInfoByBFID(apply.getId());
                if (null != applyArchive) {
                    reportDTO.setReportNum(applyArchive.getReportNum());
                    reportDTO.setPapersNum(applyArchive.getPapersNum());
                    reportDTO.setYear(applyArchive.getYear());
                    reportDTO.setNumber(applyArchive.getNumber());
                    reportDTO.setIsNumber(applyArchive.getIsNumber());
                    reportDTO.setAuditDate(applyArchive.getAuditDate());
                    reportDTO.setFileNumber(applyArchive.getFileNumber());
                    reportDTO.setApplyFileType(applyArchive.getApplyFileType());
                    reportDTO.setReportRemarks(applyArchive.getReportRemarks());
                    reportDTO.setCarchivedType(applyArchive.getCarchivedType());
                    //设置附件
                    List<CwWorkAttachmentArchiveDto> files = applyMapper.selectFileInfoByAttid(applyArchive.getId());
                    if (null != files) {
                        files.forEach(fi -> {
                            UserDTO userDTO = applyMapper.getUserInfo(fi.getUserId());
                            fi.setCreateBy(userDTO);
                        });
                        //附件信息
                        reportDTO.setWorkAttachmentDtoList(files);
                    }
                }
                //设置项目信息
                //根据新建行id找到项目id
                CwProjectRecordsDTO recordsDTO = applyMapper.getProjectByNewLineId(apply.getReportNewLineId());
                reportDTO.setCwProjectRecordsDTO(recordsDTO);
                //设置报告文号相关信息
                //根据新建行找到签字注师信息与报告文号信息
                CwProjectInfoData byId = infoMapper.getById(apply.getReportNewLineId());
                CwProjectReport report = reportMapper.getByNewLineId(byId.getReportId());
                reportDTO.setReportNo(byId.getReportNo());
                reportDTO.setReportDate(byId.getReportDate());
                reportDTO.setReportCreateName(byId.getCreateBy());
                reportDTO.setSignatureAnnotator1Name(report.getSignatureAnnotator1Name());
                reportDTO.setSignatureAnnotator2Name(report.getSignatureAnnotator2Name());
            }
        }
        return reportDTO;
    }

    /**
     * 保存项目归档信息以及其他相关信息
     *
     * @param cwProjectReportArchiveDTO
     * @return
     * @throws Exception
     */
    public String saveForm(ApplyArchiveReportDTO cwProjectReportArchiveDTO) throws Exception {
        //根据报废id来查是否有改数据
        CwProjectReportApplyArchive report = applyMapper.getInfoByBFID(cwProjectReportArchiveDTO.getId());
        if (null != report) {
            report.setCreateBy(cwProjectReportArchiveDTO.getCreateBy().getId());
            return update(cwProjectReportArchiveDTO, report.getId(),report.getArchiveId(),report.getProcInsId(),report.getProcessDefinitionId());
        } else {
            report = applyMapper.selectById(cwProjectReportArchiveDTO.getId());
            if (null != report) {
                return update(cwProjectReportArchiveDTO, report.getId(),report.getArchiveId(),report.getProcInsId(),report.getProcessDefinitionId());
            } else {
                return add(cwProjectReportArchiveDTO);
            }
        }
    }

    /**
     * 合同登记新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(ApplyArchiveReportDTO reportDTO) throws Exception {
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        String id = UUID.randomUUID().toString().replace("-", "");
        CwProjectReportApplyArchive applyArchive = new CwProjectReportApplyArchive();
        BeanUtils.copyProperties(reportDTO, applyArchive);
        applyArchive.setId(id);
        applyArchive.setCreateBy(userDTO.getId());
        applyArchive.setCreateDate(new Date());
        applyArchive.setUpdateBy(userDTO.getId());
        applyArchive.setUpdateDate(new Date());
        //传过来的是report表的id
        //根据改id查报废信息
//        String newLineId = applyMapper.getNewLineId(reportDTO.getId());
        //根据newLineID查出报废表id
//        String bfId = applyMapper.getBfId(newLineId);
        applyArchive.setArchiveId(reportDTO.getId());
        applyMapper.insert(applyArchive);
        //修改报告作废表的归档状态
        applyMapper.updateArchiveStyle(reportDTO.getId(), applyArchive.getApplyFileType());
        List<CwWorkAttachmentArchiveDto> list = reportDTO.getWorkAttachmentDtoList();
        if (CollectionUtils.isNotEmpty(list)) {
            saveFiles(list, userDTO, id);
        }
        return id;
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(ApplyArchiveReportDTO reportData, String id,String archiveId,String procInsId,String defId) throws Exception {
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();

        CwProjectReportApplyArchive cwProjectReportArchive = new CwProjectReportApplyArchive();
        BeanUtils.copyProperties(reportData, cwProjectReportArchive);
        cwProjectReportArchive.setUpdateBy(userDTO.getId());
        cwProjectReportArchive.setUpdateDate(new Date());
        cwProjectReportArchive.setId(id);
        cwProjectReportArchive.setArchiveId(archiveId);
        cwProjectReportArchive.setProcInsId(procInsId);
        cwProjectReportArchive.setProcessDefinitionId(defId);
        applyMapper.updateById(cwProjectReportArchive);
        //修改报告作废表的归档状态
        applyMapper.updateArchiveStyle(cwProjectReportArchive.getArchiveId(), cwProjectReportArchive.getApplyFileType());
        //对上传的文件数据进行持久化操作
        List<CwWorkAttachmentArchiveDto> list = reportData.getWorkAttachmentDtoList();
        if (CollectionUtils.isNotEmpty(list)) {
            updateFiles(list, userDTO, cwProjectReportArchive.getId());
        } else {
            applyMapper.deleteFileInfo(cwProjectReportArchive.getId());
        }

        return cwProjectReportArchive.getId();
    }

    /**
     * 修改附件信息
     *
     * @param list    待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id      关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<CwWorkAttachmentArchiveDto> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (CwWorkAttachmentArchiveDto dto : list) {
            names = names + "," + dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachment> infoList = applyMapper.findList(id);
        if (CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachment i : infoList) {
                if (!names.contains(i.getUrl())) {
                    ossServiceMapper.deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (CwWorkAttachmentArchiveDto dto : list) {
            //判断是否存在
            Integer isExit = applyMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachment i = new WorkAttachment();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateDate(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateDate(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (CollectionUtils.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("cwWorkContract");
                i.setFileSize(dto.getSize());
                i.setSort(j);
                ossServiceMapper.insertWorkAttachment(i, userDTO);
                j++;
            }
        }
    }

    /**
     * 保存附件信息
     *
     * @param list    待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id      关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<CwWorkAttachmentArchiveDto> list, UserDTO userDTO, String id) {
        int j = 1;
        for (CwWorkAttachmentArchiveDto dto : list) {
            WorkAttachment i = new WorkAttachment();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateDate(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateDate(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (CollectionUtils.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("cwWorkContract");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            ossServiceMapper.insertWorkAttachment(i, userDTO);
            j++;
        }
    }

    /**
     * 修改状态
     *
     * @param cwProjectReportArchiveDTO
     * @return
     */
    public String updateStatusById(ApplyArchiveReportDTO cwProjectReportArchiveDTO) {
        CwProjectReportApplyArchive cwProjectReportArchive = new CwProjectReportApplyArchive();
        CwProjectReportApplyArchive applyArchive = applyMapper.selectById(cwProjectReportArchiveDTO.getId());
        if (null != applyArchive){
            applyMapper.updateCancellArchiveType(cwProjectReportArchiveDTO.getApplyFileType(), cwProjectReportArchiveDTO.getId());

            applyMapper.updateStatusByArchiveId(cwProjectReportArchiveDTO.getApplyFileType(), applyArchive.getArchiveId());
        } else {
            applyArchive = applyMapper.getInfoByBFID(cwProjectReportArchiveDTO.getId());
            applyMapper.updateCancellArchiveType(cwProjectReportArchiveDTO.getApplyFileType(), applyArchive.getId());

            applyMapper.updateStatusByArchiveId(cwProjectReportArchiveDTO.getApplyFileType(), applyArchive.getArchiveId());
        }

        return "操作成功";
    }

    public ApplyArchiveReportDTO findByContractInfoId(String id) {
        return applyMapper.selectFilePaperByContractInfoId(id);
    }
}
