package cn.iocoder.lyzsys.module.tjt.controller.admin.outputsplit;

import cn.iocoder.lyzsys.framework.common.pojo.CommonResult;
import cn.iocoder.lyzsys.framework.common.util.object.BeanUtils;
import cn.iocoder.lyzsys.module.tjt.controller.admin.outputsplit.vo.ProjectOutputSplitPlanningDetailRespVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.outputsplit.vo.ProjectOutputSplitRespVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.outputsplit.vo.ProjectOutputSplitSaveReqVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planning.vo.ProjectPlanningRespVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planningquarter.vo.ProjectPlanningQuarterRespVO;
import cn.iocoder.lyzsys.module.tjt.dal.dataobject.planning.ProjectPlanningDO;
import cn.iocoder.lyzsys.module.tjt.dal.dataobject.planningquarter.ProjectPlanningQuarterDO;
import cn.iocoder.lyzsys.module.tjt.service.outputsplit.ProjectOutputSplitService;
import cn.iocoder.lyzsys.module.tjt.service.planning.ProjectPlanningService;
import cn.iocoder.lyzsys.module.tjt.service.planningquarter.ProjectPlanningQuarterService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static cn.iocoder.lyzsys.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 特建投页面4拆分比例")
@RestController
@RequestMapping("/tjt/output-split")
@Validated
public class ProjectOutputSplitController {

    private static final int RATIO_SCALE = 4;
    private static final BigDecimal ZERO_RATIO = BigDecimal.ZERO.setScale(RATIO_SCALE, RoundingMode.HALF_UP);

    @Resource
    private ProjectOutputSplitService projectOutputSplitService;
    @Resource
    private ProjectPlanningService projectPlanningService;
    @Resource
    private ProjectPlanningQuarterService projectPlanningQuarterService;

    @GetMapping("/get-by-planning")
    @Operation(summary = "根据合约规划获得页面4拆分比例")
    @Parameter(name = "planningId", description = "合约规划 ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:output-split:query')")
    public CommonResult<ProjectOutputSplitRespVO> getProjectOutputSplitByPlanningId(@RequestParam("planningId") Long planningId) {
        return success(projectOutputSplitService.getProjectOutputSplit(planningId));
    }

    @GetMapping("/planning-detail")
    @Operation(summary = "获得页面4合约规划分配聚合详情")
    @Parameter(name = "planningId", description = "合约规划 ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:planning:query') && @ss.hasPermission('tjt:output-split:query') && @ss.hasPermission('tjt:planning-quarter:query')")
    public CommonResult<ProjectOutputSplitPlanningDetailRespVO> getProjectOutputSplitPlanningDetail(
            @RequestParam("planningId") Long planningId) {
        ProjectPlanningDO planning = projectPlanningService.getProjectPlanning(planningId);
        if (planning == null) {
            return success(null);
        }
        ProjectOutputSplitPlanningDetailRespVO respVO = new ProjectOutputSplitPlanningDetailRespVO();
        Map<Long, BigDecimal> allocatedAmountMap =
                projectPlanningService.getAllocatedAmountMap(Collections.singleton(planningId));
        respVO.setPlanning(BeanUtils.toBean(planning, ProjectPlanningRespVO.class,
                planningRespVO -> fillDistributionSummary(planningRespVO, allocatedAmountMap)));
        respVO.setOutputSplit(projectOutputSplitService.getProjectOutputSplit(planningId));

        List<ProjectPlanningQuarterDO> quarterList =
                projectPlanningQuarterService.getProjectPlanningQuarterListByPlanningId(planningId);
        respVO.setQuarters(BeanUtils.toBean(quarterList, ProjectPlanningQuarterRespVO.class));
        return success(respVO);
    }

    @PutMapping("/save")
    @Operation(summary = "保存页面4拆分比例")
    @PreAuthorize("@ss.hasPermission('tjt:output-split:update')")
    public CommonResult<Long> saveProjectOutputSplit(@Valid @RequestBody ProjectOutputSplitSaveReqVO reqVO) {
        return success(projectOutputSplitService.saveProjectOutputSplit(reqVO));
    }

    private void fillDistributionSummary(ProjectPlanningRespVO respVO, Map<Long, BigDecimal> allocatedAmountMap) {
        BigDecimal allocatedRatio = allocatedAmountMap.getOrDefault(respVO.getId(), ZERO_RATIO);
        BigDecimal totalDistributionAmount = respVO.getTotalDistributionAmount() == null
                ? ZERO_RATIO : respVO.getTotalDistributionAmount().setScale(RATIO_SCALE, RoundingMode.HALF_UP);
        BigDecimal allocatedAmount = totalDistributionAmount.multiply(allocatedRatio)
                .setScale(RATIO_SCALE, RoundingMode.HALF_UP);
        respVO.setAllocatedAmount(allocatedAmount);
        respVO.setPendingAmount(totalDistributionAmount.subtract(allocatedAmount)
                .setScale(RATIO_SCALE, RoundingMode.HALF_UP));
    }

}
