package com.artfess.cqxy.statistics.manager.Impl;

import com.artfess.base.feign.UCFeignService;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryField;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.query.QueryOP;
import com.artfess.base.util.BeanUtils;
import com.artfess.cqxy.projectManagement.dao.ProjectManagementDao;
import com.artfess.cqxy.projectManagement.manager.ProjectManagementManager;
import com.artfess.cqxy.projectManagement.manager.ProjectPersonnelManager;
import com.artfess.cqxy.projectManagement.model.ProjectManagement;
import com.artfess.cqxy.statistics.dao.NewStatisticsDao;
import com.artfess.cqxy.statistics.manager.NewStatisticsManager;
import com.artfess.cqxy.statistics.vo.*;
import com.artfess.uc.api.impl.util.ContextUtil;
import com.artfess.uc.api.model.IUser;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: Rong Tao
 * @Date: 2022/7/27 13:37
 */
@Service
public class NewStatisticsManagerImpl extends BaseManagerImpl<NewStatisticsDao, ProjectManagement> implements NewStatisticsManager {

    @Autowired
    private NewStatisticsDao newStatisticsDao;
    @Resource
    private UCFeignService ucFeignService;
    @Autowired
    private ProjectPersonnelManager projectPersonnelManager;
    @Autowired
    private ProjectManagementManager projectManagementManager;
    @Autowired
    private ProjectManagementDao projectManagementDao;

    QueryFilter<ProjectManagement> isUser(QueryFilter<ProjectManagement> queryFilter) {
        List<QueryField> queryFields = queryFilter.getQuerys();
        boolean isParentId = true;
        boolean isDele = true;
        for (QueryField ele : queryFields) {
            if ("parent_id_".equalsIgnoreCase(ele.getProperty()) || "parentId".equalsIgnoreCase(ele.getProperty())) {
                isParentId = false;
            }
            if ("IS_DELE_".equalsIgnoreCase(ele.getProperty()) || "ISDELE".equalsIgnoreCase(ele.getProperty())) {
                isDele = false;
            }
        }
        if (isParentId) {
            queryFilter.addFilter("parent_id_", "root", QueryOP.EQUAL);
        }
        if (isDele) {
            queryFilter.addFilter("IS_DELE_", "0", QueryOP.EQUAL);
        }
        //查询项目时通过项目人员增加查询条件，只有管理员或者可以管理此项目的人员才能查询到此项目
        IUser user = ContextUtil.getCurrentUser();
        // 如果是管理员或者没有项目权限
        if (null != user) {
//            String currentUserId = baseContext.getCurrentUserId();
            boolean disableAll = false;
            Integer userType = user.getUserType();
            String userId = user.getUserId();
            CommonResult<JsonNode> userNode = ucFeignService.getUserById(userId);
            if (userNode.getState()) {
                JsonNode userJsonNode = userNode.getValue();
                if (null != userJsonNode) {
                    userType = userJsonNode.get("userType").asInt();
                }
            }
            // 1.先通过用户类型判断，过滤掉超级管理员之类的用户
            if (userType != null && userType != 0 && userType != 1) {
                // 2.再通过角色判断，过滤掉没有对应角色权限的人员
                // 获取当前用户拥有的所有角色
                Set<String> set = new HashSet<String>();
                List<ObjectNode> list = ucFeignService.getRoleListByAccount(user.getAccount());
                if (BeanUtils.isNotEmpty(list)) {
                    for (ObjectNode objectNode : list) {
                        set.add(objectNode.get("code").asText());
                    }
                }
                if (!set.contains("sysRole") && !set.contains("bld") && !set.contains("xmgl")) {
                    disableAll = true;
                }
            }
            if (disableAll) {
                List<String> projectIds = projectPersonnelManager.getProjectByPersonnelId(userId);
                List<String> projectIdsByuserIdList = projectManagementDao.queryProjectIdsByUserId(userId);
                if (null == projectIds) {
                    projectIds = new ArrayList<>();
                }
                projectIds.addAll(projectIdsByuserIdList);
                // 去重
                List projectIdList = (List) projectIds.stream().distinct().collect(Collectors.toList());
                queryFilter.addFilter("ID_", projectIdList, QueryOP.IN);
            }
        }
        return queryFilter;
    }

    @Override
    public BasicInformationVo getBasicInformation(QueryFilter<ProjectManagement> queryFilter) {
        QueryFilter<ProjectManagement> totalQueryFilter = isUser(queryFilter);
        QueryFilter<ProjectManagement> startQueryFilter = totalQueryFilter;
        QueryFilter<ProjectManagement> completedQueryFilter = totalQueryFilter;
        BasicInformationVo vo = new BasicInformationVo();
        // 项目总数
        vo.setTotal(newStatisticsDao.getBasicInformation(convert2Wrapper(totalQueryFilter, currentModelClass())));
        // 已开工
        startQueryFilter.addFilter("PROJECT_STATUS_", "9", QueryOP.GREAT);
        vo.setStart(newStatisticsDao.getBasicInformation(convert2Wrapper(startQueryFilter, currentModelClass())));
        // 已竣工
        completedQueryFilter.addFilter("PROJECT_STATUS_", "11", QueryOP.GREAT);
        vo.setCompleted(newStatisticsDao.getBasicInformation(convert2Wrapper(completedQueryFilter, currentModelClass())));
        // 未开工
        vo.setNotStart(new BigDecimal(vo.getTotal()).subtract(new BigDecimal(vo.getStart())).stripTrailingZeros().toPlainString());
        return vo;
    }

    @Override
    public ProjectProgressVo getProjectProgress(QueryFilter<ProjectManagement> queryFilter) {
        ProjectProgressVo vo = new ProjectProgressVo();
        QueryFilter<ProjectManagement> newFilter = isUser(queryFilter);
        newFilter.getPageBean().setPageSize(-1);

        //前期手续
        newFilter.addFilter("PROJECT_STATUS_", "8", QueryOP.LESS);
        vo.setEarlyStage(newStatisticsDao.getBasicInformation(convert2Wrapper(newFilter, currentModelClass())));

        for (QueryField ele : newFilter.getQuerys()) {
            if ("PROJECT_STATUS_".equalsIgnoreCase(ele.getProperty()) || "PROJECTSTATUS".equalsIgnoreCase(ele.getProperty())) {
                ele.setProperty("1");
                ele.setValue("1");
                ele.setOperation(QueryOP.EQUAL);
            }
        }

        //招投标与合同
        newFilter.addFilter("PROJECT_STATUS_", "8", QueryOP.GREAT_EQUAL);
        newFilter.addFilter("PROJECT_STATUS_", "9", QueryOP.LESS_EQUAL);
        vo.setBiddingAndContract(newStatisticsDao.getBasicInformation(convert2Wrapper(newFilter, currentModelClass())));

        for (QueryField ele : queryFilter.getQuerys()) {
            if ("PROJECT_STATUS_".equalsIgnoreCase(ele.getProperty()) || "PROJECTSTATUS".equalsIgnoreCase(ele.getProperty())) {
                ele.setProperty("1");
                ele.setValue("1");
                ele.setOperation(QueryOP.EQUAL);
            }
        }

        //工程施工
        newFilter.addFilter("PROJECT_STATUS_", "10", QueryOP.GREAT_EQUAL);
        newFilter.addFilter("PROJECT_STATUS_", "11", QueryOP.LESS_EQUAL);
        vo.setConstruction(newStatisticsDao.getBasicInformation(convert2Wrapper(newFilter, currentModelClass())));

        for (QueryField ele : queryFilter.getQuerys()) {
            if ("PROJECT_STATUS_".equalsIgnoreCase(ele.getProperty()) || "PROJECTSTATUS".equalsIgnoreCase(ele.getProperty())) {
                ele.setProperty("1");
                ele.setOperation(QueryOP.EQUAL);
                ele.setValue("1");
            }
        }

        //竣工验收
        newFilter.addFilter("PROJECT_STATUS_", "12", QueryOP.GREAT_EQUAL);
        vo.setCompleted(newStatisticsDao.getBasicInformation(convert2Wrapper(newFilter, currentModelClass())));

        return vo;
    }

    @Override
    public StartCountVo getStartCount(QueryFilter<ProjectManagement> queryFilter) {
        queryFilter.getPageBean().setPageSize(-1);
        StartCountVo vo = new StartCountVo();
        QueryFilter<ProjectManagement> newFilter = isUser(queryFilter);
        QueryFilter<ProjectManagement> queryFilter1 = newFilter;
        //开工总数
        queryFilter1.addFilter("PROJECT_STATUS_", "9", QueryOP.GREAT);
        vo.setTotal(newStatisticsDao.getBasicInformation(convert2Wrapper(queryFilter1, currentModelClass())));

        //本月开工
        PageList<ProjectManagement> projectManagementPageList = projectManagementManager.queryAllByPage(newFilter);
        int num = 0;
        for (ProjectManagement projectManagement : projectManagementPageList.getRows()) {
            QueryFilter<ProjectManagement> tempQueryFilter = queryFilter;
            boolean isDel = false;
            for (QueryField ele : tempQueryFilter.getQuerys()) {
                if ("IS_DELE_".equalsIgnoreCase(ele.getProperty()) || "ISDELE".equalsIgnoreCase(ele.getProperty())) {
                    isDel = true;
                }
                if ("PROJECT_STATUS_".equalsIgnoreCase(ele.getProperty()) || "PROJECTSTATUS".equalsIgnoreCase(ele.getProperty())) {
                    ele.setProperty("1");
                    ele.setValue("1");
                }
                if ("ESTABLISHMENT_DATE_".equalsIgnoreCase(ele.getProperty()) || "ESTABLISHMENTDATE".equalsIgnoreCase(ele.getProperty())) {
                    ele.setProperty("1");
                    ele.setValue("1");
                }
                if ("START_DATE_".equalsIgnoreCase(ele.getProperty()) || "STARTDATE".equalsIgnoreCase(ele.getProperty())) {
                    ele.setProperty("1");
                    ele.setValue("1");
                }
                if ("parent_id_".equalsIgnoreCase(ele.getProperty()) || "parentId".equalsIgnoreCase(ele.getProperty())) {
                    ele.setProperty("1");
                    ele.setValue("1");
                }
            }
            if (!isDel) {
                tempQueryFilter.addFilter("IS_DELE_", "0", QueryOP.EQUAL);
            }


            tempQueryFilter.addFilter("PROJECT_ID_", projectManagement.getId(), QueryOP.EQUAL);
            QueryFilter<ProjectManagement> tempQueryFilter2 = tempQueryFilter;
            LocalDate curentDate = LocalDate.now();
            LocalDate firstDay = curentDate.with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天
            LocalDate lastDay = curentDate.with(TemporalAdjusters.lastDayOfMonth()); // 获取当前月的最后一天
            tempQueryFilter.addFilter("ESTABLISHMENT_DATE_", firstDay, QueryOP.GREAT_EQUAL);
            tempQueryFilter.addFilter("ESTABLISHMENT_DATE_", lastDay, QueryOP.LESS_EQUAL);
            // 查询施工许可表，如果查询数量为0再去查询开工准备表
            int sgCount = Integer.valueOf(newStatisticsDao.getStartCount(convert2Wrapper(tempQueryFilter, currentModelClass())));
            if (sgCount > 0) {
                num += 1;
            } else {
                for (QueryField ele : tempQueryFilter.getQuerys()) {
                    if ("ESTABLISHMENT_DATE_".equalsIgnoreCase(ele.getProperty()) || "ESTABLISHMENTDATE".equalsIgnoreCase(ele.getProperty())) {
                        ele.setProperty("1");
                        ele.setValue("1");
                    }
                    if ("START_DATE_".equalsIgnoreCase(ele.getProperty()) || "STARTDATE".equalsIgnoreCase(ele.getProperty())) {
                        ele.setProperty("1");
                        ele.setValue("1");
                    }
                }
                // 查询开工准备表
                tempQueryFilter2.addFilter("START_DATE_", firstDay, QueryOP.GREAT_EQUAL);
                tempQueryFilter2.addFilter("START_DATE_", lastDay, QueryOP.LESS_EQUAL);
                sgCount = Integer.valueOf(newStatisticsDao.getStartCount2(convert2Wrapper(tempQueryFilter, currentModelClass())));
                if (sgCount > 0) {
                    num += 1;
                }
            }
        }
        vo.setNowTotal(String.valueOf(num));
        return vo;
    }

    @Override
    public StartCountVo getAcceptanceCount(QueryFilter<ProjectManagement> queryFilter) {
        queryFilter.getPageBean().setPageSize(-1);
        StartCountVo vo = new StartCountVo();
        QueryFilter<ProjectManagement> newFilter = isUser(queryFilter);
        QueryFilter<ProjectManagement> queryFilter1 = newFilter;
        //竣工总数
        queryFilter1.addFilter("PROJECT_STATUS_", "11", QueryOP.GREAT);
        vo.setTotal(newStatisticsDao.getBasicInformation(convert2Wrapper(queryFilter1, currentModelClass())));
        QueryFilter<ProjectManagement> queryFilter2 = queryFilter1;

        boolean isDel = false;
        for (QueryField ele : queryFilter2.getQuerys()) {
            if ("IS_DELE_".equalsIgnoreCase(ele.getProperty()) || "ISDELE".equalsIgnoreCase(ele.getProperty())) {
                isDel = true;
            }
            if ("PROJECT_STATUS_".equalsIgnoreCase(ele.getProperty()) || "PROJECTSTATUS".equalsIgnoreCase(ele.getProperty())) {
                isDel = true;
            }
        }
        if (!isDel) {
            queryFilter2.addFilter("IS_DELE_", "0", QueryOP.EQUAL);
        }

        //本月竣工
        LocalDate curentDate = LocalDate.now();
        LocalDate firstDay = curentDate.with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天
        LocalDate lastDay = curentDate.with(TemporalAdjusters.lastDayOfMonth()); // 获取当前月的最后一天
        queryFilter2.addFilter("COMPLETION_ACCEPTANCE_TIME_", firstDay, QueryOP.GREAT_EQUAL);
        queryFilter2.addFilter("COMPLETION_ACCEPTANCE_TIME_", lastDay, QueryOP.LESS_EQUAL);
        vo.setNowTotal(newStatisticsDao.getBasicInformation(convert2Wrapper(queryFilter2, currentModelClass())));
        return vo;
    }

    @Override
    public ProjectCostVo getProjectCost(QueryFilter<ProjectManagement> queryFilter) {
        ProjectCostVo vo = new ProjectCostVo();
        QueryFilter<ProjectManagement> totalQueryFilter = isUser(queryFilter);
        totalQueryFilter.getPageBean().setPageSize(-1);
        PageList<ProjectManagement> projectManagementPageList = projectManagementManager.queryAllByPage(totalQueryFilter);

        // 总投资
        vo.setEarlyStage(newStatisticsDao.getSumInvestment(convert2Wrapper(totalQueryFilter, currentModelClass())));
        boolean isDel = false;
        for (QueryField ele : totalQueryFilter.getQuerys()) {
            if ("IS_DELE_".equalsIgnoreCase(ele.getProperty()) || "ISDELE".equalsIgnoreCase(ele.getProperty())) {
                isDel = true;
            }
            if ("parent_id_".equalsIgnoreCase(ele.getProperty()) || "parentId".equalsIgnoreCase(ele.getProperty())) {
                ele.setProperty("1");
                ele.setValue("1");
            }
            if ("ID_".equalsIgnoreCase(ele.getProperty()) || "ID".equalsIgnoreCase(ele.getProperty())) {
                ele.setProperty("1");
                ele.setValue("1");
            }
        }
        if (!isDel) {
            totalQueryFilter.addFilter("IS_DELE_", "0", QueryOP.EQUAL);
        }

        // 总支付
        BigDecimal totalPayee = new BigDecimal(0.0);
        // 合同金额
        BigDecimal contractMoney = new BigDecimal(0.0);
        //合同总数
        int contractNum = 0;
        //本月投资
        BigDecimal InvestmentMoney = new BigDecimal(0.0);
        //本月支付
        BigDecimal nowPayee = new BigDecimal(0.0);
        //本月合同金额
        BigDecimal nowContractMoney = new BigDecimal(0.0);
        //本月合同总数
        int nowContractNum = 0;

        for (ProjectManagement projectManagement : projectManagementPageList.getRows()) {
            QueryFilter<ProjectManagement> tempQueryFilter = totalQueryFilter;
            for (QueryField ele : tempQueryFilter.getQuerys()) {
                if ("PROJECT_ID_".equalsIgnoreCase(ele.getProperty()) || "PROJECTID".equalsIgnoreCase(ele.getProperty())) {
                    ele.setProperty("1");
                    ele.setValue("1");
                }
//                if ("PORT_DATE_".equalsIgnoreCase(ele.getProperty()) || "PORTDATE".equalsIgnoreCase(ele.getProperty())) {
//                    ele.setProperty("1");
//                    ele.setValue("1");
//                }
//                if ("REGISTER_DATE_".equalsIgnoreCase(ele.getProperty()) || "REGISTERDATE".equalsIgnoreCase(ele.getProperty())) {
//                    ele.setProperty("1");
//                    ele.setValue("1");
//                }
                if ("CONTRACT_DATE_".equalsIgnoreCase(ele.getProperty()) || "CONTRACTDATE".equalsIgnoreCase(ele.getProperty())) {
                    ele.setProperty("1");
                    ele.setValue("1");
                }

            }
            tempQueryFilter.addFilter("PROJECT_ID_", projectManagement.getId(), QueryOP.EQUAL);
            // 查询工程月报表
            if (!newStatisticsDao.havePayment(convert2Wrapper(tempQueryFilter, currentModelClass())).equals("0")) {
                BigDecimal tempCount = new BigDecimal((newStatisticsDao.getSumPayment(convert2Wrapper(tempQueryFilter, currentModelClass()))));
                totalPayee = totalPayee.add(tempCount);
            }
            if (!newStatisticsDao.haveNowInvestment(convert2Wrapper(tempQueryFilter, currentModelClass())).equals("0")) {
                BigDecimal tempCount = new BigDecimal(newStatisticsDao.getSumContractMoney(convert2Wrapper(tempQueryFilter, currentModelClass())));
                contractMoney = contractMoney.add(tempCount);
            }
            Integer tempNum = Integer.valueOf(newStatisticsDao.getCountContractNum(convert2Wrapper(tempQueryFilter, currentModelClass())));
            contractNum += tempNum;

            LocalDate curentDate = LocalDate.now();
            LocalDate firstDay = curentDate.with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天
            LocalDate lastDay = curentDate.with(TemporalAdjusters.lastDayOfMonth()); // 获取当前月的最后一天
            tempQueryFilter.addFilter("PORT_DATE_", firstDay, QueryOP.GREAT_EQUAL);
            tempQueryFilter.addFilter("PORT_DATE_", lastDay, QueryOP.LESS_EQUAL);
            // 查询工程月报表
            if (!newStatisticsDao.haveNowInvestment(convert2Wrapper(tempQueryFilter, currentModelClass())).equals("0")) {
                BigDecimal tempCount = new BigDecimal(newStatisticsDao.getNowInvestment(convert2Wrapper(tempQueryFilter, currentModelClass())));
                InvestmentMoney = InvestmentMoney.add(tempCount);
            }
            for (QueryField ele : tempQueryFilter.getQuerys()) {
                if ("PORT_DATE_".equalsIgnoreCase(ele.getProperty()) || "PORTDATE".equalsIgnoreCase(ele.getProperty())) {
                    ele.setProperty("1");
                    ele.setValue("1");
                }
            }
            tempQueryFilter.addFilter("REGISTER_DATE_", firstDay, QueryOP.GREAT_EQUAL);
            tempQueryFilter.addFilter("REGISTER_DATE_", lastDay, QueryOP.LESS_EQUAL);
            // 查询支付表
            if (!newStatisticsDao.havePayment(convert2Wrapper(tempQueryFilter, currentModelClass())).equals("0")) {
                BigDecimal tempCount = new BigDecimal(newStatisticsDao.getSumPayment(convert2Wrapper(tempQueryFilter, currentModelClass())));
                nowPayee = nowPayee.add(tempCount);
            }

            for (QueryField ele : tempQueryFilter.getQuerys()) {
                if ("REGISTER_DATE_".equalsIgnoreCase(ele.getProperty()) || "REGISTERDATE".equalsIgnoreCase(ele.getProperty())) {
                    ele.setProperty("1");
                    ele.setValue("1");
                }
            }

            tempQueryFilter.addFilter("CONTRACT_DATE_", firstDay, QueryOP.GREAT_EQUAL);
            tempQueryFilter.addFilter("CONTRACT_DATE_", lastDay, QueryOP.LESS_EQUAL);
            // 查询合同表
            if (!newStatisticsDao.haveContract(convert2Wrapper(tempQueryFilter, currentModelClass())).equals("0")) {
                BigDecimal tempCount = new BigDecimal(newStatisticsDao.getSumContractMoney(convert2Wrapper(tempQueryFilter, currentModelClass())));
                nowContractMoney = nowContractMoney.add(tempCount);
            }
            Integer tempNum2 = Integer.valueOf(newStatisticsDao.getCountContractNum(convert2Wrapper(tempQueryFilter, currentModelClass())));
            nowContractNum += tempNum2;

        }
        vo.setTotalPayee(String.valueOf(totalPayee));
        vo.setContractMoney(String.valueOf(contractMoney));
        vo.setContractNum(String.valueOf(contractNum));
        vo.setNowEarlyStage(String.valueOf(InvestmentMoney));
        vo.setNowTotalPayee(String.valueOf(nowPayee));
        vo.setNowContractMoney(String.valueOf(nowContractMoney));
        vo.setNowContractNum(String.valueOf(nowContractNum));
        return vo;
    }
}