package com.jeeplus.finance.projectRecords.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.annotation.TableField;
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.jeeplus.common.TokenProvider;
import com.jeeplus.finance.projectRecords.domain.CwFillingbatchFile;
import com.jeeplus.finance.projectRecords.domain.CwFillingbatchInfo;
import com.jeeplus.finance.projectRecords.domain.CwFillingbatchProject;
import com.jeeplus.finance.projectRecords.mapper.CwFillingBatchInfoMapper;
import com.jeeplus.finance.projectRecords.mapper.CwFillingbatchFileMapper;
import com.jeeplus.finance.projectRecords.mapper.CwFillingbatchProjectMapper;
import com.jeeplus.finance.projectRecords.mapper.CwProjectRecordsMapper;
import com.jeeplus.finance.projectRecords.service.dto.CwFillingbatchInfoDTO;
import com.jeeplus.finance.projectRecords.service.dto.CwFillingbatchProjectDTO;
import com.jeeplus.finance.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.finance.projectReport.domain.CwProjectReport;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportMapper;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Transactional
public class CwFillingbatchService {

    @Resource
    private CwFillingBatchInfoMapper cwFillingBatchInfoMapper;

    @Resource
    private CwFillingbatchProjectMapper cwFillingbatchProjectMapper;

    @Resource
    private CwFillingbatchFileMapper cwFillingbatchFileMapper;

    @Resource
    private CwProjectReportMapper cwProjectReportMapper;

    @Resource
    private CwProjectRecordsMapper cwProjectRecordsMapper;

    public IPage<CwFillingbatchInfoDTO> list(CwFillingbatchInfoDTO info, Page<CwFillingbatchInfoDTO> page) {
        QueryWrapper<CwFillingbatchInfoDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.del_flag", 0);
        if (ObjectUtil.isNotEmpty(info)) {
            //创建时间
            if (ArrayUtil.isNotEmpty(info.getCreateDates())) {
                queryWrapper.between("a.create_time", info.getCreateDates()[0], info.getCreateDates()[1]);
            }
            //创建人
            if (StringUtils.isNotBlank(info.getCreateById())) {
                queryWrapper.eq("a.create_by_id", info.getCreateById());
            }
            //状态
            if (StringUtils.isNotBlank(info.getStatus())) {
                queryWrapper.eq("a.status", info.getStatus());
            }
            //归档名称
            if (StringUtils.isNotBlank(info.getName())) {
                queryWrapper.eq("a.name", info.getName());
            }
        }
        //查询归档信息  将相关信息查询出来后设置好层级后,前端组件会自动组装成树状表
        IPage<CwFillingbatchInfoDTO> list = cwFillingBatchInfoMapper.findList(page, queryWrapper);
        List<CwFillingbatchInfoDTO> records = list.getRecords();
        if (CollectionUtil.isNotEmpty(records)){
            List<CwFillingbatchInfoDTO> projectList = cwFillingBatchInfoMapper.findProjectList();
            for (CwFillingbatchInfoDTO record : list.getRecords()) {
                //设置层级
                record.setLevel("1");
            }
            for (CwFillingbatchInfoDTO cwFillingbatchInfoDTO : projectList) {
                if (StringUtils.isBlank(cwFillingbatchInfoDTO.getStatus())){
                    cwFillingbatchInfoDTO.setStatus("2");
                }
            }
            records.addAll(projectList);
        }

        return list;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    public ResponseEntity deleteByIds(String ids) {
        //删除归档信息
        cwFillingBatchInfoMapper.deleteById(ids);
        //修改归档项目中的信息
        cwFillingBatchInfoMapper.updateInfo(ids);
        //删除归档项目文件中的信息
        List<CwFillingbatchProject> projectList = cwFillingbatchProjectMapper.selectList(new QueryWrapper<CwFillingbatchProject>().eq("fillingbatch_id", ids));
        if (CollectionUtil.isNotEmpty(projectList)) {
            for (CwFillingbatchProject project : projectList) {
                //根据id查询项目文件
                List<CwFillingbatchFile> fileList = cwFillingbatchFileMapper.selectList(new QueryWrapper<CwFillingbatchFile>().eq("report_id", project.getReportId()));
                //删除文件
                if (CollectionUtil.isNotEmpty(fileList)) {
                    for (CwFillingbatchFile file : fileList) {
                        cwFillingbatchFileMapper.delete(new QueryWrapper<CwFillingbatchFile>().eq("id", file.getId()));

                    }
                }
            }
        }
        return ResponseEntity.ok("删除成功");
    }

    /**
     * 查询批量归档详情
     *
     * @param id
     * @return
     */
    public CwFillingbatchInfoDTO queryById(String id) {
        //根据id查询归档信息
        CwFillingbatchInfoDTO cwFillingbatchInfo = cwFillingBatchInfoMapper.findById(id);
        //查询项目信息
        ArrayList<CwFillingbatchProject> projects = new ArrayList<>();
        List<CwFillingbatchProject> projectList = cwFillingBatchInfoMapper.findProjectByBatchId(id);
        if (CollectionUtil.isNotEmpty(projectList)) {
            ArrayList<CwFillingbatchProject> list = new ArrayList<>();
            //遍历项目并查询文件
            for (CwFillingbatchProject project : projectList) {
                project.setLevel("1");
                List<CwFillingbatchProject> fileList = cwFillingBatchInfoMapper.findFileByProId(project.getId());
                list.addAll(fileList);
            }
            projects.addAll(projectList);
            projects.addAll(list);
            cwFillingbatchInfo.setCwFillingbatchProjects(projects);
        }

        return cwFillingbatchInfo;
    }

    /**
     * 当前登录人未归档的B类项目,归档已完成但项目被驳回的B类项目
     *
     * @param info
     * @param page
     * @return
     */
    public IPage<CwFillingbatchProjectDTO> getProjectList(CwFillingbatchProjectDTO info, Page<CwFillingbatchProjectDTO> page) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        QueryWrapper<CwFillingbatchProjectDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.create_by_id", userDTO.getId());
        queryWrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotBlank(info.getName())) {
            queryWrapper.like("a.project_name", info.getName());
        }
        //获取当前登陆人所有未归档的B类项目
        IPage<CwFillingbatchProjectDTO> projectList = cwFillingBatchInfoMapper.getList(page, queryWrapper);
        //获取当前登录人所有归档被驳回的的项目
        List<CwFillingbatchProjectDTO> list = cwFillingBatchInfoMapper.findProList(userDTO.getId());
        Map<String, CwFillingbatchProjectDTO> uniqueProjectMap = new LinkedHashMap<>();
        //将未归档以及归档被驳回的项目存到list中最后重新进行赋值
        if (ObjectUtil.isNotEmpty(projectList)) {
            if (CollectionUtil.isNotEmpty(list)) {
                for (CwFillingbatchProjectDTO projectDTO : list) {
                    if ("4".equals(projectDTO.getStatus())) {
                        projectDTO.setLevel("1");
                        uniqueProjectMap.put(projectDTO.getId(), projectDTO);
                        continue;
                    }
                }
                List<CwFillingbatchProjectDTO> record = new ArrayList<>(uniqueProjectMap.values());
                List<CwFillingbatchProjectDTO> records = projectList.getRecords();
                for (CwFillingbatchProjectDTO dto : projectList.getRecords()) {
                    dto.setLevel("1");
                }
                records.addAll(record);
                projectList.setRecords(records);
            }


        }


        return projectList;
    }

    /**
     * 保存项目批量归档信息
     *
     * @param info
     * @return
     */
    public String saveForm(CwFillingbatchInfoDTO info) throws Exception {
        if (StringUtils.isNotBlank(info.getId())) {
            return edit(info);
        }
        return add(info);
    }

    private String edit(CwFillingbatchInfoDTO info) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());

        //修改归档信息
        CwFillingbatchInfo cwFillingbatchInfo = new CwFillingbatchInfo();
        BeanUtils.copyProperties(info, cwFillingbatchInfo);
        cwFillingbatchInfo.setUpdateById(userDTO.getId());
        cwFillingbatchInfo.setUpdateTime(new Date());
        cwFillingBatchInfoMapper.updateById(cwFillingbatchInfo);
        //根据id将归档项目表中的信息删除
        cwFillingbatchProjectMapper.delete(new QueryWrapper<CwFillingbatchProject>().eq("fillingbatch_id", info.getId()));
        //查找项目信息
        List<CwFillingbatchProject> projectList = cwFillingBatchInfoMapper.findProjectByBatchId(info.getId());
        if (CollectionUtil.isNotEmpty(projectList)) {
            for (CwFillingbatchProject cwFillingbatchProject : projectList) {
                //删除项目文件中的信息
                cwFillingbatchFileMapper.delete(new QueryWrapper<CwFillingbatchFile>().eq("report_id", cwFillingbatchProject.getReportId()));
            }
        }
        //新增项目信息
        if (CollectionUtil.isNotEmpty(info.getCwFillingbatchProjects())) {
            Integer count = 0;
            for (CwFillingbatchProject cwFillingbatchProject : info.getCwFillingbatchProjects()) {
                if ("1".equals(cwFillingbatchProject.getLevel())) {
                    //往归档项目表中添加信息
                    CwFillingbatchProject project = new CwFillingbatchProject();
                    project.setId(UUID.randomUUID().toString().replace("-", ""));
                    project.setFillingbatchId(info.getId());
                    project.setReportId(cwFillingbatchProject.getReportId());
                    count = count+1;
                    project.setSort(count);
                    cwFillingbatchProjectMapper.insert(project);
                    //遍历子级数据
                    if (CollectionUtil.isNotEmpty(cwFillingbatchProject.getChildren())) {
                        Integer count1 = 0;
                        for (CwFillingbatchFile child : cwFillingbatchProject.getChildren()) {
                            CwFillingbatchFile cwFillingbatchFile = new CwFillingbatchFile();
                            cwFillingbatchFile.setId(UUID.randomUUID().toString().replace("-", ""));
                            cwFillingbatchFile.setFileType(child.getProjectNumber());
                            cwFillingbatchFile.setFileRemarks(child.getName());
                            cwFillingbatchFile.setReportId(project.getId());
                            cwFillingbatchFile.setSort(count1++);
                            //往项目文件表中添加信息
                            cwFillingbatchFileMapper.insert(cwFillingbatchFile);
                        }

                    }
                }
            }
        }




        return info.getId();

    }

    private String add(CwFillingbatchInfoDTO info) throws Exception {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        //生成归档批次号
        String serialNum = SpringUtil.getBean(IWorkAttachmentApi.class).genSerialNum(userDTO.getCompanyDTO().getId(), CwFillingbatchInfoDTO.BIZ_CODE, TokenProvider.getCurrentToken());
        //往归档信息表中添加信息
        CwFillingbatchInfo cwFillingbatchInfo = new CwFillingbatchInfo();
        BeanUtils.copyProperties(info, cwFillingbatchInfo);
        cwFillingbatchInfo.setNo(serialNum);
        String id = UUID.randomUUID().toString().replace("-", "");
        cwFillingbatchInfo.setId(id);
        cwFillingbatchInfo.setCreateById(userDTO.getId());
        cwFillingbatchInfo.setCreateTime(new Date());
        cwFillingbatchInfo.setUpdateById(userDTO.getId());
        cwFillingbatchInfo.setUpdateTime(new Date());
        cwFillingBatchInfoMapper.insert(cwFillingbatchInfo);
        //遍历归档项目信息
        if (CollectionUtil.isNotEmpty(info.getCwFillingbatchProjects())) {
            Integer count = 0;
            for (CwFillingbatchProject cwFillingbatchProject : info.getCwFillingbatchProjects()) {
                if ("1".equals(cwFillingbatchProject.getLevel())) {
                    //往归档项目表中添加信息
                    CwFillingbatchProject project = new CwFillingbatchProject();
                    project.setId(UUID.randomUUID().toString().replace("-", ""));
                    project.setFillingbatchId(cwFillingbatchInfo.getId());
                    project.setReportId(cwFillingbatchProject.getReportId());
                    count = count+1;
                    project.setSort(count);
                    cwFillingbatchProjectMapper.insert(project);
                    //遍历子级数据
                    if (CollectionUtil.isNotEmpty(cwFillingbatchProject.getChildren())) {
                        Integer count1 = 0;
                        for (CwFillingbatchFile child : cwFillingbatchProject.getChildren()) {
                            CwFillingbatchFile cwFillingbatchFile = new CwFillingbatchFile();
                            cwFillingbatchFile.setId(UUID.randomUUID().toString().replace("-", ""));
                            cwFillingbatchFile.setFileType(child.getProjectNumber());
                            cwFillingbatchFile.setFileRemarks(child.getName());
                            cwFillingbatchFile.setReportId(project.getId());
                            cwFillingbatchFile.setSort(count1++);
                            //往项目文件表中添加信息
                            cwFillingbatchFileMapper.insert(cwFillingbatchFile);
                        }

                    }
                }
            }
        }
        return id;
    }


    /**
     * 根据id修改状态
     *
     * @param dto
     * @return
     */
    public String updateStatusById(CwFillingbatchInfoDTO dto) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());

        CwFillingbatchInfo cwFillingbatchInfo = new CwFillingbatchInfo();
        //如果状态为5
        if (dto.getStatus().equals("5")) {
            //修改归档项目表中的案卷号和项目状态
            if (CollectionUtil.isNotEmpty(dto.getCwFillingbatchProjects())) {
                for (CwFillingbatchProject cwFillingbatchProject : dto.getCwFillingbatchProjects()) {
                    if (StringUtils.isNotBlank(cwFillingbatchProject.getLevel()) && cwFillingbatchProject.getLevel().equals("1")){
                        CwFillingbatchProject project1 = new CwFillingbatchProject();
                        project1.setId(cwFillingbatchProject.getId());
                        project1.setAchiveNo(cwFillingbatchProject.getAchiveNo());
                        project1.setStatus(cwFillingbatchProject.getProjectStatus());
                        cwFillingbatchProjectMapper.updateById(project1);
                    }
                }
            }
            cwFillingbatchInfo.setAuditAgreeTime(new Date());
        }
        //修改归档信息表状态
        cwFillingbatchInfo.setId(dto.getId());
        cwFillingbatchInfo.setUpdateTime(new Date());
        cwFillingbatchInfo.setUpdateById(userDTO.getId());
        cwFillingbatchInfo.setStatus(dto.getStatus());
        cwFillingBatchInfoMapper.updateById(cwFillingbatchInfo);
        return "修改成功";
    }

    /*
    批量归档
     */
    public String importDecide(List<CwFillingbatchProjectDTO> listA, ArrayList<CwFillingbatchProjectDTO> arrayList, HashMap<String, String> hashMap) {
        //获取项目表中的所有数据
        QueryWrapper<CwFillingbatchProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",0);
        List<CwFillingbatchProject> projectList = cwFillingbatchProjectMapper.selectList(queryWrapper);
        //遍历导入的数据
        for (CwFillingbatchProjectDTO cwFillingbatchInfoDTO : listA) {
            HashSet<String> prefixReportNumberSet = new HashSet<>();
            if (StringUtils.isNotBlank(cwFillingbatchInfoDTO.getReportNo())){
                //对报告号进行分割，取“【”前的信息
                String prefixReportNumber = cwFillingbatchInfoDTO.getReportNo().substring(0,cwFillingbatchInfoDTO.getReportNo().lastIndexOf("["));
                prefixReportNumberSet.add(prefixReportNumber);
                if(prefixReportNumberSet.size()>1){
                    return "导入项目报告号类型不一样";
                }
            }
            ArrayList<CwFillingbatchFile> files = new ArrayList<>();
            if (ObjectUtil.isEmpty(cwFillingbatchInfoDTO)){
                continue;
            }
            //根据报告号查找报告id
            String id=cwProjectReportMapper.getIdByNo(cwFillingbatchInfoDTO.getReportNo());
            //根据报告号查询对应的报告信息
            if (StringUtils.isEmpty(id)){
                return "未查询到报告号-"+cwFillingbatchInfoDTO.getReportNo()+"对应的报告信息";
            }
            //查询项目是否是B类项目
            //根据报告id查询项目信息
            CwProjectRecordsDTO recordsDTO=cwProjectRecordsMapper.getInfoById(id);
            if (StringUtils.isBlank(recordsDTO.getProjectLevel()) && "1".equals(recordsDTO.getProjectLevel())){
                return "报告号:"+cwFillingbatchInfoDTO.getReportNo()+"的项目信息不是B类项目,无法进行批量归档";
            }
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            //判断当前登录人是否是项目登记人
            if (!userDTO.getId().equals(recordsDTO.getCreateId())){
                return "报告号"+cwFillingbatchInfoDTO.getReportNo()+"的项目登记人不是您,无法进行批量归档";
            }
            //判断该项目信息是否已经提交归档或者是否归档已完成
            for (CwFillingbatchProject project : projectList) {
                if (project.getReportId().equals(id)){
                    //判断当前的状态是否是2,3,5
                    switch (project.getStatus()){
                        case "2":
                            return "报告号-"+cwFillingbatchInfoDTO.getReportNo()+"正在归档中,无法重复归档";
                        case "3":
                            return "报告号-"+cwFillingbatchInfoDTO.getReportNo()+"正在归档中,无法重复归档";
                        case "5":
                            return "报告号-"+cwFillingbatchInfoDTO.getReportNo()+"已归档,无法重复归档";
                    }
                }
            }

            cwFillingbatchInfoDTO.setProjectNumber(recordsDTO.getProjectNumber());//项目编号
            cwFillingbatchInfoDTO.setName(recordsDTO.getProjectName());
            cwFillingbatchInfoDTO.setNo(recordsDTO.getReportNo());
            cwFillingbatchInfoDTO.setLevel("1");
            cwFillingbatchInfoDTO.setReportId(id);
            //将文件放入项目中
            CwFillingbatchFile cwFillingbatchFile = new CwFillingbatchFile();
            cwFillingbatchFile.setProjectNumber(cwFillingbatchInfoDTO.getProjectNumber());
            cwFillingbatchFile.setName(cwFillingbatchInfoDTO.getName());
            cwFillingbatchFile.setParentId(id);
            files.add(cwFillingbatchFile);
            cwFillingbatchInfoDTO.setCwFillingbatchFiles(files);
            arrayList.add(cwFillingbatchInfoDTO);

        }
        return null;
    }
}
