package com.yhy.module.core.controller.admin.quota;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.yhy.module.core.controller.admin.quota.vo.*;
import com.yhy.module.core.convert.quota.QuotaAdjustmentConvert;
import com.yhy.module.core.dal.dataobject.quota.QuotaAdjustmentDO;
import com.yhy.module.core.service.quota.QuotaAdjustmentService;
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.util.List;
import java.util.Map;

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

@Tag(name = "管理后台 - 定额调整设置")
@RestController
@RequestMapping("/core/quota/adjustment")
@Validated
public class QuotaAdjustmentController {

    @Resource
    private QuotaAdjustmentService quotaAdjustmentService;

    @PostMapping("/create")
    @Operation(summary = "创建定额调整设置")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:create')")
    public CommonResult<Long> createQuotaAdjustment(@Valid @RequestBody QuotaAdjustmentSaveReqVO createReqVO) {
        return success(quotaAdjustmentService.createQuotaAdjustment(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新定额调整设置")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:update')")
    public CommonResult<Boolean> updateQuotaAdjustment(@Valid @RequestBody QuotaAdjustmentSaveReqVO updateReqVO) {
        quotaAdjustmentService.updateQuotaAdjustment(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除定额调整设置")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:delete')")
    public CommonResult<Boolean> deleteQuotaAdjustment(@RequestParam("id") Long id) {
        quotaAdjustmentService.deleteQuotaAdjustment(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得定额调整设置")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<QuotaAdjustmentRespVO> getQuotaAdjustment(@RequestParam("id") Long id) {
        QuotaAdjustmentDO adjustment = quotaAdjustmentService.getQuotaAdjustment(id);
        return success(QuotaAdjustmentConvert.INSTANCE.convert(adjustment));
    }

    @GetMapping("/list")
    @Operation(summary = "获得定额调整设置列表")
    @Parameter(name = "quotaItemId", description = "定额子目ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<List<QuotaAdjustmentRespVO>> getQuotaAdjustmentList(@RequestParam("quotaItemId") Long quotaItemId) {
        List<QuotaAdjustmentDO> list = quotaAdjustmentService.getQuotaAdjustmentList(quotaItemId);
        return success(QuotaAdjustmentConvert.INSTANCE.convertList(list));
    }

    @PostMapping("/swap-sort")
    @Operation(summary = "交换排序")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:update')")
    public CommonResult<Boolean> swapSort(@Valid @RequestBody QuotaAdjustmentSwapSortReqVO reqVO) {
        quotaAdjustmentService.swapSort(reqVO.getId1(), reqVO.getId2());
        return success(true);
    }

    @PostMapping("/save-material-items")
    @Operation(summary = "保存材料调整明细")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:update')")
    public CommonResult<Boolean> saveMaterialItems(@Valid @RequestBody QuotaAdjustmentMaterialItemsReqVO reqVO) {
        List<Map<String, Object>> items = new java.util.ArrayList<>();
        for (QuotaAdjustmentMaterialItemVO item : reqVO.getItems()) {
            Map<String, Object> itemMap = new java.util.HashMap<>();
            itemMap.put("sortOrder", item.getSortOrder());
            itemMap.put("resourceCode", item.getResourceCode());
            itemMap.put("resourceName", item.getResourceName());
            itemMap.put("adjustValue", item.getAdjustValue());
            itemMap.put("remark", item.getRemark());
            items.add(itemMap);
        }
        quotaAdjustmentService.saveMaterialItems(reqVO.getAdjustmentId(), items);
        return success(true);
    }

    @GetMapping("/get-material-items")
    @Operation(summary = "获取材料调整明细")
    @Parameter(name = "adjustmentId", description = "调整设置ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<List<Map<String, Object>>> getMaterialItems(@RequestParam("adjustmentId") Long adjustmentId) {
        return success(quotaAdjustmentService.getMaterialItems(adjustmentId));
    }

    @GetMapping("/get-available-categories")
    @Operation(summary = "获取可配置的类别列表")
    @Parameter(name = "quotaItemId", description = "定额子目ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<List<Map<String, Object>>> getAvailableCategories(@RequestParam("quotaItemId") Long quotaItemId) {
        return success(quotaAdjustmentService.getAvailableCategories(quotaItemId));
    }

    @PostMapping("/save-dynamic-config")
    @Operation(summary = "保存动态调整配置")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:update')")
    public CommonResult<Boolean> saveDynamicConfig(@Valid @RequestBody QuotaAdjustmentDynamicConfigReqVO reqVO) {
        List<Map<String, Object>> categories = new java.util.ArrayList<>();
        for (QuotaAdjustmentDynamicCategoryVO category : reqVO.getCategories()) {
            Map<String, Object> categoryMap = new java.util.HashMap<>();
            categoryMap.put("categoryId", category.getCategoryId());
            categoryMap.put("categoryName", category.getCategoryName());
            categoryMap.put("categoryType", category.getCategoryType());
            categoryMap.put("coefficient", category.getCoefficient());
            categoryMap.put("minValue", category.getMinValue());
            categoryMap.put("maxValue", category.getMaxValue());
            categoryMap.put("denominator", category.getDenominator());
            categoryMap.put("baseValue", category.getBaseValue());
            categoryMap.put("roundingRule", category.getRoundingRule());
            categories.add(categoryMap);
        }
        quotaAdjustmentService.saveDynamicConfig(reqVO.getAdjustmentId(), categories);
        return success(true);
    }

    @GetMapping("/get-dynamic-config")
    @Operation(summary = "获取动态调整配置")
    @Parameter(name = "adjustmentId", description = "调整设置ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<List<Map<String, Object>>> getDynamicConfig(@RequestParam("adjustmentId") Long adjustmentId) {
        return success(quotaAdjustmentService.getDynamicConfig(adjustmentId));
    }

    @PostMapping("/calculate-dynamic")
    @Operation(summary = "计算动态调整结果")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<Map<String, BigDecimal>> calculateDynamic(@Valid @RequestBody QuotaAdjustmentDynamicCalculateReqVO reqVO) {
        return success(quotaAdjustmentService.calculateDynamic(reqVO.getAdjustmentId(), reqVO.getInputValues()));
    }

    @PostMapping("/save-coefficient-config")
    @Operation(summary = "保存系数调整配置")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:update')")
    public CommonResult<Boolean> saveCoefficientConfig(@Valid @RequestBody QuotaAdjustmentCoefficientConfigReqVO reqVO) {
        List<Map<String, Object>> categories = new java.util.ArrayList<>();
        for (QuotaAdjustmentCoefficientCategoryVO category : reqVO.getCategories()) {
            Map<String, Object> categoryMap = new java.util.HashMap<>();
            categoryMap.put("categoryId", category.getCategoryId());
            categoryMap.put("categoryName", category.getCategoryName());
            categoryMap.put("categoryType", category.getCategoryType());
            categoryMap.put("coefficient", category.getCoefficient());
            categories.add(categoryMap);
        }
        quotaAdjustmentService.saveCoefficientConfig(reqVO.getAdjustmentId(), categories);
        return success(true);
    }

    @GetMapping("/get-coefficient-config")
    @Operation(summary = "获取系数调整配置")
    @Parameter(name = "adjustmentId", description = "调整设置ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<List<Map<String, Object>>> getCoefficientConfig(@RequestParam("adjustmentId") Long adjustmentId) {
        return success(quotaAdjustmentService.getCoefficientConfig(adjustmentId));
    }

    @GetMapping("/get-available-resources")
    @Operation(summary = "获取可选的工料机列表")
    @Parameter(name = "quotaItemId", description = "定额子目ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<List<Map<String, Object>>> getAvailableResources(@RequestParam("quotaItemId") Long quotaItemId) {
        return success(quotaAdjustmentService.getAvailableResources(quotaItemId));
    }

    @PostMapping("/save-merge-config")
    @Operation(summary = "保存动态合并配置")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:update')")
    public CommonResult<Boolean> saveMergeConfig(@Valid @RequestBody QuotaAdjustmentMergeConfigReqVO reqVO) {
        List<Map<String, Object>> resources = new java.util.ArrayList<>();
        for (QuotaAdjustmentMergeResourceVO resource : reqVO.getResources()) {
            Map<String, Object> resourceMap = new java.util.HashMap<>();
            resourceMap.put("resourceId", resource.getResourceId());
            resourceMap.put("resourceCode", resource.getResourceCode());
            resourceMap.put("resourceName", resource.getResourceName());
            resourceMap.put("coefficient", resource.getCoefficient());
            resourceMap.put("minValue", resource.getMinValue());
            resourceMap.put("maxValue", resource.getMaxValue());
            resourceMap.put("denominator", resource.getDenominator());
            resourceMap.put("baseValue", resource.getBaseValue());
            resourceMap.put("roundingRule", resource.getRoundingRule());
            resources.add(resourceMap);
        }
        quotaAdjustmentService.saveMergeConfig(reqVO.getAdjustmentId(), resources);
        return success(true);
    }

    @GetMapping("/get-merge-config")
    @Operation(summary = "获取动态合并配置")
    @Parameter(name = "adjustmentId", description = "调整设置ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<List<Map<String, Object>>> getMergeConfig(@RequestParam("adjustmentId") Long adjustmentId) {
        return success(quotaAdjustmentService.getMergeConfig(adjustmentId));
    }

    @PostMapping("/calculate-merge")
    @Operation(summary = "计算动态合并结果")
    @PreAuthorize("@ss.hasPermission('core:quota:adjustment:query')")
    public CommonResult<Map<String, BigDecimal>> calculateMerge(@Valid @RequestBody QuotaAdjustmentMergeCalculateReqVO reqVO) {
        return success(quotaAdjustmentService.calculateMerge(reqVO.getAdjustmentId(), reqVO.getInputValues()));
    }
}
