package com.artfess.cqxy.statistics.controller;

import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.cqxy.bidManagement.manager.BiddingManagementManager;
import com.artfess.cqxy.contract.manager.ContractManager;
import com.artfess.cqxy.processManagermant.manager.ChangeManagementManager;
import com.artfess.cqxy.processManagermant.manager.ProgressManageManager;
import com.artfess.cqxy.processManagermant.manager.ProgressManageReportManager;
import com.artfess.cqxy.processManagermant.model.ProgressManageReport;
import com.artfess.cqxy.projectApproval.manager.ProjectEstablishmentManager;
import com.artfess.cqxy.projectManagement.manager.ProjectManagementManager;
import com.artfess.cqxy.projectManagement.model.ProjectManagement;
import com.artfess.cqxy.statistics.manager.NewStatisticsManager;
import com.artfess.cqxy.statistics.manager.StatisticsManager;
import com.artfess.cqxy.statistics.vo.*;
import com.artfess.cqxy.utils.BizUtils;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.param.DictModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author baseli
 * @date 2022年5月24日16:56:11
 */
@Slf4j
@RestController
@Api(tags = "统计报表-项目信息统计接口")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
@RequestMapping("/biz/statistics/v1")
public class StatisticsController {

    @Autowired
    private StatisticsManager statisticsManager;

    @Autowired
    private SysDictionaryManager sdm;

    @Autowired
    private ProgressManageReportManager progressManageReportManager;

    @Autowired
    private ProgressManageManager progressManageManager;

    @Autowired
    private ProjectManagementManager projectManagementManager;

    @Autowired
    private BiddingManagementManager biddingManagementManager;

    @Autowired
    private  ContractManager contractManager;

    @Autowired
    private  ChangeManagementManager changeManagementManager;

    @Autowired
    private ProjectEstablishmentManager projectEstablishmentManager;

    @Autowired
    private NewStatisticsManager newStatisticsManager;


    @PostMapping("/investmentProgress")
    @ApiOperation(value = "投资进度统计", httpMethod = "POST")
    public CommonResult<InvestmentProgressVo> investmentProgress(@ApiParam(name = "statisticsVo", value = "通用查询器") @RequestBody StatisticsVo statisticsVo) {
        InvestmentProgressVo investmentProgressVo = new InvestmentProgressVo();
        // 查询投资,查询产值
        List<Map<String, Object>> investments = progressManageReportManager.queryInvestment(statisticsVo);
        //查询支付
        List<Map<String, Object>> payments = progressManageManager.queryInvestment(statisticsVo);
        List<Map<Integer, Object>> investmentList = new ArrayList<>();
        List<Map<Integer, Object>> outputList = new ArrayList<>();
        List<Map<Integer, Object>> paymentList = new ArrayList<>();
        for (int m = 1; m <= 12; m++) {
            boolean isMouth = true;
            if (investments != null && investments.size() > 0) {
                for (Map<String, Object> map : investments) {
                    Integer moutn = map.get("mouth") == null ? 0 : (Integer) map.get("mouth");
                    Object investmentTotal = map.get("investmentTotal");
                    Object outputTotal = map.get("outputTotal");
                    if (m == moutn) {
                        Map<Integer, Object> mp1 = new HashMap<>();
                        mp1.put(m, ((BigDecimal) investmentTotal).stripTrailingZeros());
                        investmentList.add(mp1);
                        Map<Integer, Object> mp2 = new HashMap<>();
                        mp2.put(m, ((BigDecimal) outputTotal).stripTrailingZeros());
                        outputList.add(mp2);
                        isMouth = false;
                        break;
                    }
                }
            }
            if (isMouth) {
                Map<Integer, Object> mp1 = new HashMap<>();
                mp1.put(m, new BigDecimal(0));
                investmentList.add(mp1);
                Map<Integer, Object> mp2 = new HashMap<>();
                mp2.put(m, new BigDecimal(0));
                outputList.add(mp2);
            }
            isMouth = true;
            if (payments != null && payments.size() > 0) {
                for (Map<String, Object> payMap : payments) {
                    Integer moutn = payMap.get("mouth") == null ? 0 : (Integer) payMap.get("mouth");
                    Object paymentTotal = payMap.get("paymentTotal");
                    if (m == moutn) {
                        Map<Integer, Object> mp1 = new HashMap<>();
                        mp1.put(m, ((BigDecimal) paymentTotal).stripTrailingZeros());
                        paymentList.add(mp1);
                        isMouth = false;
                    }
                }
            }
            if (isMouth) {
                Map<Integer, Object> mp1 = new HashMap<>();
                mp1.put(m, new BigDecimal(0));
                paymentList.add(mp1);
            }
        }
        investmentProgressVo.setInvestmentList(investmentList);
        investmentProgressVo.setOutputList(outputList);
        investmentProgressVo.setPaymentList(paymentList);
        return new CommonResult<>(true, "查询成功", investmentProgressVo);
    }

    @PostMapping("/constructionProgress")
    @ApiOperation(value = "施工进度统计", httpMethod = "POST")
    public CommonResult<PageList<ProjectManagement>> constructionProgress(@ApiParam(name = "queryFilter", value = "项目管理查询对象")
                                                                          @RequestBody QueryFilter<ProjectManagement> queryFilter) {
        PageList<ProjectManagement> result = projectManagementManager.queryAllByPage(queryFilter);
        List<ProjectManagement> rows = result.getRows();
        if (rows != null) {
            List<DictModel> xmzt = sdm.queryDictListItemsByCode("xmgl-xmzt");
            // 施工进度数值化
            for (ProjectManagement pm : rows) {
                Integer status = pm.getProjectStatus() == null ? 0 : Integer.valueOf(pm.getProjectStatus());
                List<Double> list = new ArrayList<>();
                if (status < 11 && status > 1) {
                    // 第一步决策不显示，
                    for (int i = 1; i <= status; i++) {
                        list.add(0.5);
                    }
                } else if (status == 11) {
                    // 查询最新的施工进度，将施工进度转化为数值
                    for (int i = 1; i <= status; i++) {
                        if (i == 11) {
                            list.add(getProjectConstructionProgress(pm.getId()));
                        } else {
                            list.add(0.5);
                        }
                    }
                } else if (status > 11) {
                    for (int i = 1; i <= status; i++) {
                        if (i == 11) {
                            list.add(4.0);
                        } else if (i == 15) {
                            //移交暂不显示在统计界面
//                            list.add(0.5);
                        } else {
                            list.add(0.5);
                        }
                    }
                }
                pm.setProjectConstructionProgress(list);
                pm.setProjectStatusValue(BizUtils.getDicValueByCode(xmzt, status));
            }
        }
        return new CommonResult<>(true, "查询成功", result);
    }

    @PostMapping("/biddingStatistics")
    @ApiOperation(value = "招投标统计", httpMethod = "POST")
    public CommonResult<List<Map<String, Object>>> biddingStatistics(@ApiParam(name = "statisticsVo", value = "通用查询器")
                                                                         @RequestBody StatisticsVo statisticsVo) {
        return new CommonResult<>(true, "查询成功", biddingManagementManager.queryInvestment(statisticsVo));
    }

    @PostMapping("/contractAmount")
    @ApiOperation(value = "合同金额统计", httpMethod = "POST")
    public CommonResult<List<Map<String, Object>>> contractAmount(@ApiParam(name = "statisticsVo", value = "通用查询器")
                                                                      @RequestBody StatisticsVo statisticsVo) {
        return new CommonResult<>(true, "查询成功", contractManager.queryInvestment(statisticsVo));
    }

    @PostMapping("/engineeringChange")
    @ApiOperation(value = "变更费用统计", httpMethod = "POST", notes = "用于展示饼图按照变更类型统计（单位：万元）")
    public CommonResult<List<Map<String, Object>>> engineeringChange(@ApiParam(name = "statisticsVo", value = "通用查询器")
                                                                         @RequestBody StatisticsVo statisticsVo) {
        return new CommonResult<>(true, "查询成功", changeManagementManager.queryInvestment(statisticsVo));
    }

    @PostMapping("/engineeringChangeNumber")
    @ApiOperation(value = "变更数量统计", httpMethod = "POST", notes = "用于柱状图按月统计(单位：个)")
    public CommonResult<List<Map<Integer, Object>>> engineeringChangeNumber(@ApiParam(name = "statisticsVo", value = "通用查询器")
                                                                                @RequestBody StatisticsVo statisticsVo) {
        return new CommonResult<>(true, "查询成功", changeManagementManager.engineeringChangeNumber(statisticsVo));
    }

    @PostMapping("/measurementPayment")
    @ApiOperation(value = "建设情况统计", httpMethod = "POST")
    public CommonResult<List<Map<String, Object>>> measurementPayment(@ApiParam(name = "statisticsVo", value = "通用查询器")
                                                             @RequestBody StatisticsVo statisticsVo) {
        return new CommonResult<>(true, "操作成功", projectEstablishmentManager.queryInvestment(statisticsVo));
    }



    @PostMapping("/getBasicInformation")
    @ApiOperation(value = "项目基本情况统计", httpMethod = "POST")
    public CommonResult<BasicInformationVo> getBasicInformation(@ApiParam(name = "queryFilter", value = "通用查询器") @RequestBody QueryFilter<ProjectManagement> queryFilter){
        BasicInformationVo basicInformation = newStatisticsManager.getBasicInformation(queryFilter);
        return new CommonResult<>(true,"操作成功",basicInformation);
    }

    @PostMapping("/getProjectProgress")
    @ApiOperation(value = "项目进度统计", httpMethod = "POST")
    public CommonResult<ProjectProgressVo> getProjectProgress(@ApiParam(name = "queryFilter", value = "通用查询器")
                                                                  @RequestBody QueryFilter<ProjectManagement> queryFilter){
        ProjectProgressVo projectProgress = newStatisticsManager.getProjectProgress(queryFilter);
        return new CommonResult<>(true,"操作成功",projectProgress);
    }

    @PostMapping("/getStartCount")
    @ApiOperation(value = "开工总数统计", httpMethod = "POST")
    public CommonResult<StartCountVo> getStartCount(@ApiParam(name = "queryFilter", value = "通用查询器")
                                                        @RequestBody QueryFilter<ProjectManagement> queryFilter){
        StartCountVo startCount = newStatisticsManager.getStartCount(queryFilter);
        return new CommonResult<>(true,"操作成功",startCount);
    }

    @PostMapping("/getCompletedCount")
    @ApiOperation(value = "竣工总数统计", httpMethod = "POST")
    public CommonResult<StartCountVo> getCompletedCount(@ApiParam(name = "queryFilter", value = "通用查询器")
                                                            @RequestBody QueryFilter<ProjectManagement> queryFilter){
        StartCountVo acceptanceCount = newStatisticsManager.getAcceptanceCount(queryFilter);
        return new CommonResult<>(true,"操作成功",acceptanceCount);
    }

    @PostMapping("/getProjectCost")
    @ApiOperation(value = "项目费用统计", httpMethod = "POST")
    public CommonResult<ProjectCostVo> getProjectCost(@ApiParam(name = "queryFilter", value = "通用查询器")
                                                          @RequestBody QueryFilter<ProjectManagement> queryFilter){
//        ProjectCostVo projectCostVo = new ProjectCostVo();
//        projectCostVo.setEarlyStage("2563");
//        projectCostVo.setBiddingAndContract("1234");
//        projectCostVo.setConstruction("2254");
//        projectCostVo.setCompleted("12");
//        projectCostVo.setNowEarlyStage("2345");
//        projectCostVo.setNowBiddingAndContract("1111");
//        projectCostVo.setNowConstruction("2222");
//        projectCostVo.setNowCompleted("8");
        ProjectCostVo projectCost = newStatisticsManager.getProjectCost(queryFilter);
        return new CommonResult<>(true,"操作成功",projectCost);
    }




    public Double getProjectConstructionProgress(String projectId) {
        Double projectConstructionProgress = 0.5;
        ProgressManageReport progressManageReport = progressManageReportManager.getByProjectId(projectId);
        if(null != progressManageReport){
            String imageProgress = progressManageReport.getImageProgress();
            if(StringUtils.isNotBlank(imageProgress)){
                imageProgress = imageProgress.replace("%", "");
                Double progress = Double.valueOf(imageProgress);
                if(progress <= 15){
                    projectConstructionProgress = 0.5;
                }else if(progress <= 35){
                    projectConstructionProgress = 1.0;
                }else if(progress <= 45){
                    projectConstructionProgress = 1.5;
                }else if(progress <= 55){
                    projectConstructionProgress = 2.0;
                }else if(progress <= 65){
                    projectConstructionProgress = 2.5;
                }else if(progress <= 75){
                    projectConstructionProgress = 3.0;
                }else if(progress <= 85){
                    projectConstructionProgress = 3.5;
                }else{
                    projectConstructionProgress = 4.0;
                }
            }
        }
        return projectConstructionProgress;
    }
}
