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

import cn.iocoder.lyzsys.framework.common.pojo.CommonResult;
import cn.iocoder.lyzsys.framework.common.pojo.PageResult;
import cn.iocoder.lyzsys.framework.common.util.collection.CollectionUtils;
import cn.iocoder.lyzsys.framework.common.util.object.BeanUtils;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planning.vo.ProjectPlanningOutputEditDetailRespVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planning.vo.ProjectPlanningPageReqVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planning.vo.ProjectPlanningRespVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planning.vo.ProjectPlanningSaveReqVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.planningguidedetail.vo.ProjectPlanningGuideDetailRespVO;
import cn.iocoder.lyzsys.module.tjt.dal.dataobject.planning.ProjectPlanningDO;
import cn.iocoder.lyzsys.module.tjt.dal.dataobject.planningguidedetail.ProjectPlanningGuideDetailDO;
import cn.iocoder.lyzsys.module.tjt.enums.ProjectPlanningBizTypeConstants;
import cn.iocoder.lyzsys.module.tjt.service.planning.ProjectPlanningService;
import cn.iocoder.lyzsys.module.tjt.service.planningguidedetail.ProjectPlanningGuideDetailService;
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")
@Validated
public class ProjectPlanningController {

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

    @Resource
    private ProjectPlanningService projectPlanningService;
    @Resource
    private ProjectPlanningGuideDetailService projectPlanningGuideDetailService;

    @PostMapping("/create")
    @Operation(summary = "创建合约规划")
    @PreAuthorize("@ss.hasPermission('tjt:planning:create')")
    public CommonResult<Long> createProjectPlanning(@Valid @RequestBody ProjectPlanningSaveReqVO createReqVO) {
        return success(projectPlanningService.createProjectPlanning(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "修改合约规划")
    @PreAuthorize("@ss.hasPermission('tjt:planning:update')")
    public CommonResult<Boolean> updateProjectPlanning(@Valid @RequestBody ProjectPlanningSaveReqVO updateReqVO) {
        projectPlanningService.updateProjectPlanning(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除合约规划")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:planning:delete')")
    public CommonResult<Boolean> deleteProjectPlanning(@RequestParam("id") Long id) {
        projectPlanningService.deleteProjectPlanning(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Operation(summary = "批量删除合约规划")
    @Parameter(name = "ids", description = "编号列表", required = true)
    @PreAuthorize("@ss.hasPermission('tjt:planning:delete')")
    public CommonResult<Boolean> deleteProjectPlanningList(@RequestParam("ids") List<Long> ids) {
        projectPlanningService.deleteProjectPlanningList(ids);
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得合约规划分页")
    @PreAuthorize("@ss.hasPermission('tjt:planning:query')")
    public CommonResult<PageResult<ProjectPlanningRespVO>> getProjectPlanningPage(@Valid ProjectPlanningPageReqVO pageReqVO) {
        PageResult<ProjectPlanningDO> pageResult = projectPlanningService.getProjectPlanningPage(pageReqVO);
        Map<Long, BigDecimal> allocatedAmountMap = projectPlanningService.getAllocatedAmountMap(
                CollectionUtils.convertSet(pageResult.getList(), ProjectPlanningDO::getId));
        return success(BeanUtils.toBean(pageResult, ProjectPlanningRespVO.class,
                respVO -> fillDistributionSummary(respVO, allocatedAmountMap)));
    }

    @GetMapping("/get")
    @Operation(summary = "获得合约规划详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:planning:query')")
    public CommonResult<ProjectPlanningRespVO> getProjectPlanning(@RequestParam("id") Long id) {
        ProjectPlanningDO planning = projectPlanningService.getProjectPlanning(id);
        if (planning == null) {
            return success(null);
        }
        Map<Long, BigDecimal> allocatedAmountMap = projectPlanningService.getAllocatedAmountMap(
                Collections.singleton(planning.getId()));
        return success(BeanUtils.toBean(planning, ProjectPlanningRespVO.class,
                respVO -> fillDistributionSummary(respVO, allocatedAmountMap)));
    }

    @GetMapping("/output-edit-detail")
    @Operation(summary = "获得合约规划测算参数编辑详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:planning:query')")
    public CommonResult<ProjectPlanningOutputEditDetailRespVO> getProjectPlanningOutputEditDetail(@RequestParam("id") Long id) {
        ProjectPlanningDO planning = projectPlanningService.getProjectPlanning(id);
        if (planning == null) {
            return success(null);
        }

        Map<Long, BigDecimal> allocatedAmountMap = projectPlanningService.getAllocatedAmountMap(
                Collections.singleton(planning.getId()));
        ProjectPlanningOutputEditDetailRespVO respVO = new ProjectPlanningOutputEditDetailRespVO();
        respVO.setPlanning(BeanUtils.toBean(planning, ProjectPlanningRespVO.class,
                planningRespVO -> fillDistributionSummary(planningRespVO, allocatedAmountMap)));
        if (ProjectPlanningBizTypeConstants.isMajorGuidanceScene(
                planning.getOwnershipType(), planning.getCalculationMethod())) {
            List<ProjectPlanningGuideDetailDO> guideDetails =
                    projectPlanningGuideDetailService.getProjectPlanningGuideDetailListByPlanningId(id);
            respVO.setGuideDetails(BeanUtils.toBean(guideDetails, ProjectPlanningGuideDetailRespVO.class));
        }
        return success(respVO);
    }

    @GetMapping("/list-by-project")
    @Operation(summary = "根据项目获得合约规划列表")
    @Parameter(name = "projectId", description = "项目 ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('tjt:planning:query')")
    public CommonResult<List<ProjectPlanningRespVO>> getProjectPlanningListByProjectId(@RequestParam("projectId") Long projectId) {
        List<ProjectPlanningDO> list = projectPlanningService.getProjectPlanningListByProjectId(projectId);
        Map<Long, BigDecimal> allocatedAmountMap = projectPlanningService.getAllocatedAmountMap(
                CollectionUtils.convertSet(list, ProjectPlanningDO::getId));
        return success(BeanUtils.toBean(list, ProjectPlanningRespVO.class,
                respVO -> fillDistributionSummary(respVO, allocatedAmountMap)));
    }

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

}
