package com.jeeplus.modules.sg.budgetSpectaculars.service;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.sg.budgetSpectaculars.entity.*;
import com.jeeplus.modules.sg.budgetSpectaculars.mapper.ProjectBasicsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.Collator;
import java.util.*;

/**
 * 基础底表展示处理
 * 预算执行管理-综合查询表导入数据处理service
 * @author: 徐滕
 * @create: 2021-09-15 16:52
 **/
@Service
@Transactional(readOnly = true)
public class ProjectBasicsService extends CrudService<ProjectBasicsMapper, ProjectBasicsInfo> {

    @Autowired
    private ProjectBasicsMapper mapper;

    public Page<ProjectBasicsInfo> findPage(Page<ProjectBasicsInfo> page, ProjectBasicsInfo entity) {
        Page<ProjectBasicsInfo> page1 = super.findPage(page, entity);
        return page1;
    }

    /**
     * 综合查询表数据处理
     * @param budgetExecuteList
     * @return
     */
    @Transactional(readOnly = false)
    public String disposeBudgetExecuteInfo(List<BudgetExecuteInfo> budgetExecuteList,String year){
        List<ProjectBasicsInfo> projectBasicsList = Lists.newArrayList();
        //遍历综合查询表数据信息
        for (BudgetExecuteInfo budgetExecuteInfo: budgetExecuteList) {
            //如果国网项目编码为空则不进行记录
            if(StringUtils.isBlank(budgetExecuteInfo.getProjectNumber())){
                continue;
            }
            //将综合查询中的部分数据添加到项目底表list中
            ProjectBasicsInfo projectBasicsInfo = new ProjectBasicsInfo();
            if(StringUtils.isNotBlank(budgetExecuteInfo.getProjectType()) && StringUtils.isNotBlank(budgetExecuteInfo.getThirdlySlassify())){
                if("配网建设改造项目".equals(budgetExecuteInfo.getProjectType()) && "10KV（20KV）中低压配电建设与改造工程项目".equals(budgetExecuteInfo.getThirdlySlassify())){
                    projectBasicsInfo.setProjectType("配网资本项目");
                }else if("配网建设改造项目".equals(budgetExecuteInfo.getProjectType()) && "业扩配套工程".equals(budgetExecuteInfo.getThirdlySlassify())){
                    projectBasicsInfo.setProjectType("业扩资本项目");
                }else if("配网建设改造项目".equals(budgetExecuteInfo.getProjectType()) && "变电站出线配套10KV（20KV）工程项目".equals(budgetExecuteInfo.getThirdlySlassify())){
                    projectBasicsInfo.setProjectType("出线配套项目");
                }else if("配网专项成本".equals(budgetExecuteInfo.getProjectType()) && "Z701配网专项成本".equals(budgetExecuteInfo.getThirdlySlassify())){
                    projectBasicsInfo.setProjectType("配网成本项目");
                }else if("配网专项成本".equals(budgetExecuteInfo.getProjectType()) && "Z703业扩专项成本".equals(budgetExecuteInfo.getThirdlySlassify())){
                    projectBasicsInfo.setProjectType("业扩成本项目");
                }else if("配网专项成本".equals(budgetExecuteInfo.getProjectType()) && "Z702农网专项成本（主业）".equals(budgetExecuteInfo.getThirdlySlassify())){
                    projectBasicsInfo.setProjectType("农网项目");
                }else{
                    projectBasicsInfo.setProjectType("");
                }
            }else{
                projectBasicsInfo.setProjectType("");
            }
            //添加项目名称
            if(StringUtils.isNotBlank(budgetExecuteInfo.getProjectName())){
                projectBasicsInfo.setProjectName(budgetExecuteInfo.getProjectName());
            }
            //添加国网项目编码
            if(StringUtils.isNotBlank(budgetExecuteInfo.getProjectNumber())){
                projectBasicsInfo.setProjectNumber(budgetExecuteInfo.getProjectNumber());
            }
            //添加一级单位
            if(StringUtils.isNotBlank(budgetExecuteInfo.getFirstLevelUnit())){
                projectBasicsInfo.setFirstLevelUnit(budgetExecuteInfo.getFirstLevelUnit());
            }
            //添加二级单位
            if(StringUtils.isNotBlank(budgetExecuteInfo.getSecondLevelUnit())){
                projectBasicsInfo.setSecondLevelUnit(budgetExecuteInfo.getSecondLevelUnit());
            }
            //添加归口部门
            if(StringUtils.isNotBlank(budgetExecuteInfo.getRelevantDepartment())){
                projectBasicsInfo.setRelevantDepartment(budgetExecuteInfo.getRelevantDepartment());
            }
            //添加项目性质
            if(StringUtils.isNotBlank(budgetExecuteInfo.getProjectProperty())){
                projectBasicsInfo.setProjectProperty(budgetExecuteInfo.getProjectProperty());
            }
            //添加结算送审日期
            if(StringUtils.isNotBlank(budgetExecuteInfo.getProjectProperty())){
                projectBasicsInfo.setProjectProperty(budgetExecuteInfo.getProjectProperty());
            }
            //添加结算审定日期
            if(StringUtils.isNotBlank(budgetExecuteInfo.getProjectProperty())){
                projectBasicsInfo.setProjectProperty(budgetExecuteInfo.getProjectProperty());
            }
            //添加项目是否关闭
            if(StringUtils.isNotBlank(budgetExecuteInfo.getProjectCloseTime())){
                projectBasicsInfo.setIfProjectClose("是");
            }else{
                projectBasicsInfo.setIfProjectClose("否");
            }
            //将数据添加到list中
            projectBasicsList.add(projectBasicsInfo);

        }
        for (ProjectBasicsInfo info: projectBasicsList) {
            info.preInsert();
            info.setYear(year);
        }
        insertAllProjectBasicsInfo(projectBasicsList);
        return "";
    }

    /**
     * 批量插入数据信息
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String insertAllProjectBasicsInfo(List<ProjectBasicsInfo> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 100;//限制条数
            Integer size = projectBasicsList.size();
            //判断是否有必要分批
            if(pointsDataLimit<size){
                int part = size/pointsDataLimit;//分批数
                //
                for (int i = 0; i < part; i++) {
                    //100条
                    List<ProjectBasicsInfo> listPage = projectBasicsList.subList(0, pointsDataLimit);
                    mapper.insertList(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    mapper.insertList(projectBasicsList);
                }
            }else{
                mapper.insertList(projectBasicsList);
            }
        }
        return null;
    }

    /**
     * 项目明细帐导入文件处理
     * @param projectDetailList
     * @return
     */
    @Transactional(readOnly = false)
    public String disposeProjectDetailInfo(List<ProjectDetailInfo> projectDetailList){
        Set set = new HashSet();
        //遍历列表将项目定义编码去重取出
        for (ProjectDetailInfo info: projectDetailList) {
            //判定如果不为空则将项目定义编码添加到set中进行去重
            if(StringUtils.isNotBlank(info.getProjectDefinitionNumber())){
                set.add(info.getProjectDefinitionNumber());
            }
        }
        //将set转换为List;
        List<String> projectDefinitionNumberList = new ArrayList<>(set);
        //创建项目基础底表List，用于之后的批量修改数据信息
        List<ProjectBasicsInfo> projectBasicsList = Lists.newArrayList();
        //遍历并从列表中取出相对应的数据存储到List中
        for (String projectDefinitionNumber: projectDefinitionNumberList) {
            //创建list
            List<ProjectDetailInfo> infoByProjectDefinitionNumberList = Lists.newArrayList();
            Iterator<ProjectDetailInfo> it = projectDetailList.iterator();
            while(it.hasNext()){
                ProjectDetailInfo info = it.next();
                if(StringUtils.isBlank(info.getProjectDefinitionNumber())){//判定是否相同
                    it.remove();
                    continue;
                }
                if(projectDefinitionNumber.equals(info.getProjectDefinitionNumber())
                    && ("生产成本-外包材料费".equals(info.getCourseName())
                    || "生产成本-外包检修费".equals(info.getCourseName())
                    || "生产成本-自营材料费".equals(info.getCourseName())
                    || "项目建设成本-成本".equals(info.getCourseName())
                    ) && StringUtils.isNotBlank(info.getPostingDate())){//判定是否相同
                    infoByProjectDefinitionNumberList.add(info);
                    it.remove();
                }
            }
            //对时间进行排序
            projectDetailDateSort(infoByProjectDefinitionNumberList);
            if(infoByProjectDefinitionNumberList.size()>0){
                ProjectBasicsInfo projectBasics = new ProjectBasicsInfo();
                projectBasics.setProjectNumber(projectDefinitionNumber);
                //添加首次领料日期
                for (ProjectDetailInfo detailsInfo: infoByProjectDefinitionNumberList) {
                    if(StringUtils.isNotBlank(detailsInfo.getPostingDate())){
                        projectBasics.setFirstAcquisitionTime(detailsInfo.getPostingDate());
                        //实际开工日期 == 首次领料日期
                        projectBasics.setPracticalStartUpDate(detailsInfo.getPostingDate());
                        break;
                    }
                }
                //判定项目定义编码类型添加首笔施工费入账日期信息
                for (ProjectDetailInfo detailsInfo: infoByProjectDefinitionNumberList) {
                    if(detailsInfo.getProjectDefinitionNumber().startsWith("1810")){    //①资本类（项目定义编码（K列）为1810）
                        //筛选科目名称（N）列为“生产成本-外包材料费”或“生产成本-外包检修费”或“生产成本-自营材料费”或“项目建设成本-成本”，物料描述（X列）为空,且wbs描述（j列）为“安装工程支出”或“建筑工程支出”的最早过账日期（C列）
                        if(("生产成本-外包材料费".equals(detailsInfo.getCourseName())
                            || "生产成本-外包检修费".equals(detailsInfo.getCourseName())
                            || "生产成本-自营材料费".equals(detailsInfo.getCourseName())
                            || "项目建设成本-成本".equals(detailsInfo.getCourseName())
                        ) && StringUtils.isBlank(detailsInfo.getMaterialDescription())
                        && ("安装工程支出".equals(detailsInfo.getWbsDescription()) || "建筑工程支出".equals(detailsInfo.getWbsDescription()))){//判定是否相同
                            projectBasics.setFirstConstructionFeeRecordedTime(detailsInfo.getPostingDate());
                            break;
                        }
                    }else if(detailsInfo.getProjectDefinitionNumber().startsWith("B11")){   //②成本类（项目定义编码（K列）为B11）
                        //供应商名称为“镇江大照电力建设有限公司”或“镇江市金龙电业发展有限公司” 的最早过账日期（C列）
                        if("镇江大照电力建设有限公司".equals(detailsInfo.getSupplierName()) || "镇江市金龙电业发展有限公司".equals(detailsInfo.getSupplierName())){
                            projectBasics.setFirstConstructionFeeRecordedTime(detailsInfo.getPostingDate());
                            break;
                        }
                    }
                }
                projectBasicsList.add(projectBasics);
            }
        }
        //批量修改
        modifyAllProjectBasicsInfo(projectBasicsList);
        return null;
    }

    /**
     * 项目明细帐时间数据排序
     * @param list
     * @return
     */
    public static List<ProjectDetailInfo> projectDetailDateSort(List<ProjectDetailInfo> list){
        //根据指定比较器产生的顺序对指定列表进行排序。
        Collections.sort(list, new Comparator<ProjectDetailInfo>() {
            @Override
            public int compare(ProjectDetailInfo o1, ProjectDetailInfo o2) {
                //获取所需语言环境的 Collator，根据所需切换其他语言环境
                Collator collator = Collator.getInstance(Locale.CANADA);
                return collator.compare(o1.getPostingDate(), o2.getPostingDate());
            }
        });
        return list;
    }

    /**
     * 批量修改数据信息
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String modifyAllProjectBasicsInfo(List<ProjectBasicsInfo> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 100;//限制条数
            Integer size = projectBasicsList.size();
            //判断是否有必要分批
            if(pointsDataLimit<size){
                int part = size/pointsDataLimit;//分批数
                //
                for (int i = 0; i < part; i++) {
                    //100条
                    List<ProjectBasicsInfo> listPage = projectBasicsList.subList(0, pointsDataLimit);
                    mapper.modifyList(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    mapper.modifyList(projectBasicsList);
                }
            }else{
                mapper.modifyList(projectBasicsList);
            }
        }
        return null;
    }



    /**
     * 导入工程结算明细Excel数据
     * @param projectSettlementList
     * @return
     */
    @Transactional(readOnly = false)
    public String disposeProjectSettlementInfo(List<ProjectSettlementInfo> projectSettlementList){
        Set set = new HashSet();
        //遍历列表将项目定义号去重取出
        for (ProjectSettlementInfo info: projectSettlementList) {
            //判定如果不为空则将项目定义编码添加到set中进行去重
            if(StringUtils.isNotBlank(info.getProjectDefinitionNo())){
                set.add(info.getProjectDefinitionNo());
            }
        }
        //将set转换为List;
        List<String> projectDefinitionList = new ArrayList<>(set);
        //创建项目基础底表List，用于之后的批量修改数据信息
        List<ProjectBasicsInfo> projectBasicsList = Lists.newArrayList();
        for (String projectDefinition: projectDefinitionList) {
            //创建list
            List<ProjectSettlementInfo> infoByProjectDefinitionList = Lists.newArrayList();
            Iterator<ProjectSettlementInfo> it = projectSettlementList.iterator();
            while(it.hasNext()){
                ProjectSettlementInfo info = it.next();
                if(StringUtils.isBlank(info.getProjectDefinitionNo())){//判定项目定义号是否为空，为空则将其删除
                    it.remove();
                    continue;
                }
                if(projectDefinition.equals(info.getProjectDefinitionNo())){//判定是否相同
                    infoByProjectDefinitionList.add(info);
                    it.remove();
                }
            }
            if(infoByProjectDefinitionList.size()>0){
                //正序排列结算送审日期
                sortSubmittedForReviewDate(infoByProjectDefinitionList);
                ProjectBasicsInfo projectBasics = new ProjectBasicsInfo();
                projectBasics.setProjectNumber(projectDefinition);
                //添加结算送审日期和结算审定日期
                for (ProjectSettlementInfo materialInfo: infoByProjectDefinitionList) {
                    if(StringUtils.isNotBlank(materialInfo.getSubmittedForReviewDate())){
                        projectBasics.setCalculationForReviewTime(materialInfo.getSubmittedForReviewDate());
                        break;
                    }
                }
                //倒叙排列结算送审日期
                invertedSubmittedForReviewDate(infoByProjectDefinitionList);
                for (ProjectSettlementInfo materialInfo: infoByProjectDefinitionList) {
                    if(StringUtils.isNotBlank(materialInfo.getApprovalDate())){
                        projectBasics.setCalculationExamineTime(materialInfo.getApprovalDate());
                        break;
                    }
                }
                projectBasicsList.add(projectBasics);
            }
        }
        //批量修改(工程结算)
        modifyProjectSettlementList(projectBasicsList);
        return null;
    }

    /**
     * 数据排序(正序)
     * @param list
     * @return
     */
    public static List<ProjectSettlementInfo> sortSubmittedForReviewDate(List<ProjectSettlementInfo> list){
        //根据指定比较器产生的顺序对指定列表进行排序。
        Collections.sort(list, new Comparator<ProjectSettlementInfo>() {
            @Override
            public int compare(ProjectSettlementInfo o1, ProjectSettlementInfo o2) {
                //获取所需语言环境的 Collator，根据所需切换其他语言环境
                Collator collator = Collator.getInstance(Locale.CANADA);
                return collator.compare(o1.getSubmittedForReviewDate(), o2.getSubmittedForReviewDate());
            }
        });
        return list;
    }

    /**
     * 数据排序(倒序)
     * @param list
     * @return
     */
    public static List<ProjectSettlementInfo> invertedSubmittedForReviewDate(List<ProjectSettlementInfo> list){
        //根据指定比较器产生的顺序对指定列表进行排序。
        Collections.sort(list, new Comparator<ProjectSettlementInfo>() {
            @Override
            public int compare(ProjectSettlementInfo o1, ProjectSettlementInfo o2) {
                //获取所需语言环境的 Collator，根据所需切换其他语言环境
                Collator collator = Collator.getInstance(Locale.CANADA);
                return collator.compare(o2.getApprovalDate(), o1.getApprovalDate());
            }
        });
        return list;
    }


    /**
     * 批量修改数据信息(工程结算)
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String modifyProjectSettlementList(List<ProjectBasicsInfo> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 100;//限制条数
            Integer size = projectBasicsList.size();
            //判断是否有必要分批
            if(pointsDataLimit<size){
                int part = size/pointsDataLimit;//分批数
                //
                for (int i = 0; i < part; i++) {
                    //100条
                    List<ProjectBasicsInfo> listPage = projectBasicsList.subList(0, pointsDataLimit);
                    mapper.modifyProjectSettlementList(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    mapper.modifyProjectSettlementList(projectBasicsList);
                }
            }else{
                mapper.modifyProjectSettlementList(projectBasicsList);
            }
        }
        return null;
    }

    /**
     * 导入甲供材超欠供物资明细Excel数据
     * @param whichMaterialList
     * @return
     */
    @Transactional(readOnly = false)
    public String disposeWhichMaterialInfo(List<WhichMaterialInfo> whichMaterialList){
        Set set = new HashSet();
        //遍历列表将项目定义号去重取出
        for (WhichMaterialInfo info: whichMaterialList) {
            //判定如果不为空则将项目定义编码添加到set中进行去重
            if(StringUtils.isNotBlank(info.getProjectDefinition())){
                set.add(info.getProjectDefinition());
            }
        }
        //将set转换为List;
        List<String> projectDefinitionList = new ArrayList<>(set);
        //创建项目基础底表List，用于之后的批量修改数据信息
        List<ProjectBasicsInfo> projectBasicsList = Lists.newArrayList();
        for (String projectDefinition: projectDefinitionList) {
            //创建list
            List<WhichMaterialInfo> infoByProjectDefinitionList = Lists.newArrayList();
            Iterator<WhichMaterialInfo> it = whichMaterialList.iterator();
            while(it.hasNext()){
                WhichMaterialInfo info = it.next();
                if(StringUtils.isBlank(info.getProjectDefinition())){//判定项目定义号是否为空，为空则删除该条记录
                    it.remove();
                    continue;
                }
                if(projectDefinition.equals(info.getProjectDefinition())){//判定是否相同
                    infoByProjectDefinitionList.add(info);
                    it.remove();
                }
            }
            if(infoByProjectDefinitionList.size()>0){
                ProjectBasicsInfo projectBasics = new ProjectBasicsInfo();
                projectBasics.setProjectNumber(projectDefinition);
                //添加首次领料日期
                for (WhichMaterialInfo materialInfo: infoByProjectDefinitionList) {
                    if(StringUtils.isNotBlank(materialInfo.getDifferenceFeeK()) && "0".equals(materialInfo.getDifferenceFeeK())){
                        projectBasics.setIfGetRejectedMaterialFinish("是");
                    }else{
                        projectBasics.setIfGetRejectedMaterialFinish("否");
                    }
                }
                projectBasicsList.add(projectBasics);
            }
        }
        //批量修改(甲供材)
        modifyWhichMaterialList(projectBasicsList);
        return null;
    }


    /**
     * 批量修改数据信息
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String modifyWhichMaterialList(List<ProjectBasicsInfo> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 100;//限制条数
            Integer size = projectBasicsList.size();
            //判断是否有必要分批
            if(pointsDataLimit<size){
                int part = size/pointsDataLimit;//分批数
                //
                for (int i = 0; i < part; i++) {
                    //100条
                    List<ProjectBasicsInfo> listPage = projectBasicsList.subList(0, pointsDataLimit);
                    mapper.modifyWhichMaterialList(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    mapper.modifyWhichMaterialList(projectBasicsList);
                }
            }else{
                mapper.modifyWhichMaterialList(projectBasicsList);
            }
        }
        return null;
    }

    /**
     * 导入人工维护Excel数据
     * @param handmadeVindicateList
     * @return
     */
    @Transactional(readOnly = false)
    public String disposeHandmadeVindicateInfo(List<HandmadeVindicateInfo> handmadeVindicateList){
        Iterator<HandmadeVindicateInfo> it = handmadeVindicateList.iterator();
        //删除项目编号为空的数据信息
        while(it.hasNext()){
            HandmadeVindicateInfo info = it.next();
            if(StringUtils.isBlank(info.getProjectNumber())){//判定项目定义号是否为空，为空则删除该条记录
                it.remove();
            }else{
                info.preUpdate();//添加修改人和时间记录信息
            }
        }
        //批量修改(人工维护)
        modifyHandmadeVindicateList(handmadeVindicateList);
        return null;
    }


    /**
     * 批量修改手工上传数据信息
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String modifyHandmadeVindicateList(List<HandmadeVindicateInfo> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 100;//限制条数
            Integer size = projectBasicsList.size();
            //判断是否有必要分批
            if(pointsDataLimit<size){
                int part = size/pointsDataLimit;//分批数
                //
                for (int i = 0; i < part; i++) {
                    //100条
                    List<HandmadeVindicateInfo> listPage = projectBasicsList.subList(0, pointsDataLimit);
                    mapper.modifyHandmadeVindicateList(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    mapper.modifyHandmadeVindicateList(projectBasicsList);
                }
            }else{
                mapper.modifyHandmadeVindicateList(projectBasicsList);
            }
        }
        return null;
    }

}
