package cn.iocoder.yudao.module.smartfactory.controller.admin.handlinggroupamountspecifications;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.smartfactory.controller.admin.handlinggroupamountspecifications.dto.HandlingGroupAmountSpecificationsPageReqDTO;
import cn.iocoder.yudao.module.smartfactory.controller.admin.handlinggroupamountspecifications.dto.HandlingGroupAmountSpecificationsTotalNumDTO;
import cn.iocoder.yudao.module.smartfactory.controller.admin.handlinggroupamountspecifications.vo.*;
import cn.iocoder.yudao.module.smartfactory.controller.admin.handlinggroupuseramount.vo.HandlingGroupUserAmountItemVO;
import cn.iocoder.yudao.module.smartfactory.dal.dataobject.handlinggroupamountspecifications.HandlingGroupAmountSpecificationsDO;
import cn.iocoder.yudao.module.smartfactory.dal.dataobject.handlinggroupuseramount.HandlingGroupUserAmountDO;
import cn.iocoder.yudao.module.smartfactory.service.handlinggroupamountspecifications.HandlingGroupAmountSpecificationsService;
import cn.iocoder.yudao.module.smartfactory.service.handlinggroupuseramount.HandlingGroupUserAmountService;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 搬运组工资规格关联")
@RestController
@RequestMapping("/smartfactory/handling-group-amount-specifications")
@Validated
public class HandlingGroupAmountSpecificationsController {

    @Resource
    private HandlingGroupAmountSpecificationsService handlingGroupAmountSpecificationsService;
    @Resource
    private HandlingGroupUserAmountService handlingGroupUserAmountService;

    @PostMapping("/batchCreate")
    @Operation(summary = "批量创建搬运组工资规格关联")
    public CommonResult<Boolean> batchCreate(@Valid @RequestBody HandlingGroupAmountSpecificationsBatchCreateVO vo) {
        handlingGroupAmountSpecificationsService.batchCreate(vo);
        return success(true);
    }

    @GetMapping("/getTotalNum")
    @Operation(summary = "获取合计数")
    public CommonResult<HandlingGroupAmountSpecificationsTotalNumVO> getTotalNum(@Valid HandlingGroupAmountSpecificationsTotalNumDTO dto) {
        HandlingGroupAmountSpecificationsTotalNumVO vo = handlingGroupAmountSpecificationsService.getTotalNum(dto);
        return success(vo);
    }


    @GetMapping("/getAmountSubtotal")
    @Operation(summary = "获取金额小计")
    public CommonResult<BigDecimal> getAmountSubtotal(@RequestParam Integer totalCount,
                                                      @RequestParam Long handlingSpecificationsId) {
        BigDecimal amount = handlingGroupAmountSpecificationsService.getAmountSubtotal(totalCount, handlingSpecificationsId);
        return success(amount);
    }

    @PostMapping("/batchUpdate")
    @Operation(summary = "批量更新搬运组工资规格关联")
    public CommonResult<Boolean> batchUpdate(@Valid @RequestBody HandlingGroupAmountSpecificationsBatchUpdateVO vo) {
        handlingGroupAmountSpecificationsService.batchUpdate(vo);
        return success(true);
    }

    @PostMapping("/batchDelete")
    @Operation(summary = "批量删除搬运组工资规格关联")
    public CommonResult<Boolean> batchDelete(@RequestBody HandlingGroupAmountSpecificationsBatchDelVO vo) {
        handlingGroupAmountSpecificationsService.batchDelete(vo);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得搬运组工资规格关联")
    @Parameter(name = "factoryId", description = "工厂id", required = true, example = "1024")
    @Parameter(name = "dateStr", description = "日期", required = true, example = "1024")
    @Parameter(name = "handlingGroupId", description = "搬运组id", required = true, example = "1024")
    public CommonResult<List<HandlingGroupAmountSpecificationsDetailsRespVO>> getHandlingGroupAmountSpecifications(@RequestParam Long factoryId,
                                                                                                                   @RequestParam String dateStr,
                                                                                                                   @RequestParam Long handlingGroupId) {
        List<HandlingGroupAmountSpecificationsDO> handlingGroupAmountSpecifications = handlingGroupAmountSpecificationsService.getHandlingGroupAmountSpecificationsList(factoryId, dateStr, handlingGroupId);
        return success(BeanUtils.toBean(handlingGroupAmountSpecifications, HandlingGroupAmountSpecificationsDetailsRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得搬运组工资规格关联分页")
    public CommonResult<PageResult<HandlingGroupAmountSpecificationsRespVO>> getHandlingGroupAmountSpecificationsPage(@Valid HandlingGroupAmountSpecificationsPageReqVO pageReqVO) {
        PageResult<HandlingGroupAmountSpecificationsDO> pageResult = handlingGroupAmountSpecificationsService.getHandlingGroupAmountSpecificationsPage(pageReqVO);
        PageResult<HandlingGroupAmountSpecificationsRespVO> result = BeanUtils.toBean(pageResult, HandlingGroupAmountSpecificationsRespVO.class);
        // 计算合计 - 先根据工厂+搬运组+日期进行分组
        Map<String, List<HandlingGroupAmountSpecificationsRespVO>> map = result.getList().stream().collect(Collectors.groupingBy(a -> a.getFactoryId() + "_" + a.getHandlingGroupId() + "_" + a.getDateStr()));
        List<Long> ids = result.getList().stream().map(HandlingGroupAmountSpecificationsRespVO::getHandlingGroupId).distinct().collect(Collectors.toList());
        Map<Long, List<HandlingGroupUserAmountDO>> handlingGroupUserAmountMap = new HashMap<>();
        if (CollUtil.isNotEmpty(ids)) {
            List<HandlingGroupUserAmountDO> list = handlingGroupUserAmountService.getByHandlingGroupIds(ids);
            handlingGroupUserAmountMap = list.stream().collect(Collectors.groupingBy(HandlingGroupUserAmountDO::getHandlingGroupId));
        }
        for (HandlingGroupAmountSpecificationsRespVO handlingGroupAmountSpecificationsDO : result.getList()) {
            String key = handlingGroupAmountSpecificationsDO.getFactoryId() + "_" + handlingGroupAmountSpecificationsDO.getHandlingGroupId() + "_" + handlingGroupAmountSpecificationsDO.getDateStr();
//            handlingGroupAmountSpecificationsDO.setTotalAmount(getSumValue(map.get(key), HandlingGroupAmountSpecificationsRespVO::getAmount, BigDecimal::add));
//            handlingGroupAmountSpecificationsDO.setTotalNum(getSumValue(map.get(key), HandlingGroupAmountSpecificationsRespVO::getTotalCount, Integer::sum));
            List<HandlingGroupUserAmountDO> items = handlingGroupUserAmountMap.get(handlingGroupAmountSpecificationsDO.getHandlingGroupId());
            if (CollUtil.isNotEmpty(items)) {
                List<HandlingGroupUserAmountItemVO> handlingGroupUserAmountItemVOS = BeanUtils.toBean(items, HandlingGroupUserAmountItemVO.class);
                handlingGroupAmountSpecificationsDO.setHandlingGroupUserAmountItemVOS(handlingGroupUserAmountItemVOS);
            }
        }
        return success(result);
    }


    @GetMapping("/pageV2")
    @Operation(summary = "获得搬运组工资规格关联分页")
    public CommonResult<PageResult<HandlingGroupAmountSpecificationsRespVO>> getHandlingGroupAmountSpecificationsPageV2(@Valid HandlingGroupAmountSpecificationsPageReqDTO pageReqVO) {
        PageResult<HandlingGroupAmountSpecificationsRespVO> pageResult = handlingGroupAmountSpecificationsService.getHandlingGroupAmountSpecificationsPageV2(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出搬运组工资规格关联 Excel")
    @OperateLog(type = EXPORT)
    public void exportHandlingGroupAmountSpecificationsExcel(@Valid HandlingGroupAmountSpecificationsPageReqVO pageReqVO,
                                                             HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<HandlingGroupAmountSpecificationsDO> list = handlingGroupAmountSpecificationsService.getHandlingGroupAmountSpecificationsPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "搬运组工资规格关联.xls", "数据", HandlingGroupAmountSpecificationsRespVO.class,
                BeanUtils.toBean(list, HandlingGroupAmountSpecificationsRespVO.class));
    }

}
