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

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.planning.vo.ProjectPlanningRespVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planningquarter.vo.ProjectPlanningQuarterPlanningDetailRespVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planningquarter.vo.ProjectPlanningQuarterRespVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planningquarter.vo.ProjectPlanningQuarterSaveReqVO;
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.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 = "管理后台 - 特建投季度分配")
@RestController
@RequestMapping("/tjt/planning-quarter")
@Validated
public class ProjectPlanningQuarterController {

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

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

    @PostMapping("/create")
    @Operation(summary = "创建季度分配")
    @PreAuthorize("@ss.hasPermission('tjt:planning-quarter:create')")
    public CommonResult<Long> createProjectPlanningQuarter(@Valid @RequestBody ProjectPlanningQuarterSaveReqVO createReqVO) {
        return success(projectPlanningQuarterService.createProjectPlanningQuarter(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "修改季度分配")
    @PreAuthorize("@ss.hasPermission('tjt:planning-quarter:update')")
    public CommonResult<Boolean> updateProjectPlanningQuarter(@Valid @RequestBody ProjectPlanningQuarterSaveReqVO updateReqVO) {
        projectPlanningQuarterService.updateProjectPlanningQuarter(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除季度分配")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:planning-quarter:delete')")
    public CommonResult<Boolean> deleteProjectPlanningQuarter(@RequestParam("id") Long id) {
        projectPlanningQuarterService.deleteProjectPlanningQuarter(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Operation(summary = "批量删除季度分配")
    @Parameter(name = "ids", description = "编号列表", required = true)
    @PreAuthorize("@ss.hasPermission('tjt:planning-quarter:delete')")
    public CommonResult<Boolean> deleteProjectPlanningQuarterList(@RequestParam("ids") List<Long> ids) {
        projectPlanningQuarterService.deleteProjectPlanningQuarterList(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得季度分配详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:planning-quarter:query')")
    public CommonResult<ProjectPlanningQuarterRespVO> getProjectPlanningQuarter(@RequestParam("id") Long id) {
        ProjectPlanningQuarterDO quarter = projectPlanningQuarterService.getProjectPlanningQuarter(id);
        return success(BeanUtils.toBean(quarter, ProjectPlanningQuarterRespVO.class));
    }

    @GetMapping("/list-by-planning")
    @Operation(summary = "根据合约规划获得季度分配列表")
    @Parameter(name = "planningId", description = "合约规划 ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:planning-quarter:query')")
    public CommonResult<List<ProjectPlanningQuarterRespVO>> getProjectPlanningQuarterListByPlanningId(
            @RequestParam("planningId") Long planningId) {
        List<ProjectPlanningQuarterDO> list = projectPlanningQuarterService.getProjectPlanningQuarterListByPlanningId(planningId);
        return success(BeanUtils.toBean(list, ProjectPlanningQuarterRespVO.class));
    }

    @GetMapping("/planning-detail")
    @Operation(summary = "获得合约规划详情及季度分配列表")
    @Parameter(name = "planningId", description = "合约规划 ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:planning:query') && @ss.hasPermission('tjt:planning-quarter:query')")
    public CommonResult<ProjectPlanningQuarterPlanningDetailRespVO> getProjectPlanningQuarterPlanningDetail(
            @RequestParam("planningId") Long planningId) {
        ProjectPlanningDO planning = projectPlanningService.getProjectPlanning(planningId);
        if (planning == null) {
            return success(null);
        }
        List<ProjectPlanningQuarterDO> quarterList =
                projectPlanningQuarterService.getProjectPlanningQuarterListByPlanningId(planningId);

        ProjectPlanningQuarterPlanningDetailRespVO respVO = new ProjectPlanningQuarterPlanningDetailRespVO();
        Map<Long, BigDecimal> allocatedAmountMap =
                projectPlanningService.getAllocatedAmountMap(Collections.singleton(planningId));
        respVO.setPlanning(BeanUtils.toBean(planning, ProjectPlanningRespVO.class,
                planningRespVO -> fillDistributionSummary(planningRespVO, allocatedAmountMap)));
        respVO.setQuarters(BeanUtils.toBean(quarterList, ProjectPlanningQuarterRespVO.class));
        return success(respVO);
    }

    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));
    }

}
