package cn.iocoder.yudao.module.mes.controller.admin.feedingplan;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
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.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductUnitDO;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import cn.iocoder.yudao.module.erp.service.product.ErpProductUnitService;
import cn.iocoder.yudao.module.mes.controller.admin.feedingplan.vo.FeedingRecordPlanPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.feedingplan.vo.FeedingRecordPlanRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.feedingplan.vo.FeedingRecordPlanSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.feedingplan.FeedingRecordPlanDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.feedingrecord.FeedingRecordDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.plan.PlanDO;
import cn.iocoder.yudao.module.mes.service.feedingplan.FeedingRecordPlanService;
import cn.iocoder.yudao.module.mes.service.feedingrecord.FeedingRecordService;
import cn.iocoder.yudao.module.mes.service.plan.PlanService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

@Tag(name = "管理后台 - 投料分配计划")
@RestController
@RequestMapping("/mes/feeding-record-plan")
@Validated
public class FeedingRecordPlanController {

    @Resource
    private FeedingRecordPlanService feedingRecordPlanService;
    @Resource
    private ErpProductService productService;
    @Resource
    private ErpProductUnitService productUnitService;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private PlanService planService;
    @Resource
    private FeedingRecordService feedingRecordService;

    @PostMapping("/create")
    @Operation(summary = "创建投料分配计划")
    @PreAuthorize("@ss.hasPermission('mes:feeding-record-plan:create')")
    public CommonResult<Long> createFeedingRecordPlan(@Valid @RequestBody FeedingRecordPlanSaveReqVO createReqVO) {
        return success(feedingRecordPlanService.createFeedingRecordPlan(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新投料分配计划")
    @PreAuthorize("@ss.hasPermission('mes:feeding-record-plan:update')")
    public CommonResult<Boolean> updateFeedingRecordPlan(@Valid @RequestBody FeedingRecordPlanSaveReqVO updateReqVO) {
        feedingRecordPlanService.updateFeedingRecordPlan(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除投料分配计划")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:feeding-record-plan:delete')")
    public CommonResult<Boolean> deleteFeedingRecordPlan(@RequestParam("id") Long id) {
        feedingRecordPlanService.deleteFeedingRecordPlan(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得投料分配计划")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:feeding-record-plan:query')")
    public CommonResult<FeedingRecordPlanRespVO> getFeedingRecordPlan(@RequestParam("id") Long id) {
        FeedingRecordPlanDO feedingRecordPlan = feedingRecordPlanService.getFeedingRecordPlan(id);
        return success(BeanUtils.toBean(feedingRecordPlan, FeedingRecordPlanRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得投料分配计划分页")
    @PreAuthorize("@ss.hasPermission('mes:feeding-record-plan:query')")
    public CommonResult<PageResult<FeedingRecordPlanRespVO>> getFeedingRecordPlanPage(@Valid FeedingRecordPlanPageReqVO pageReqVO) {

        PageResult<FeedingRecordPlanDO> pageResult = feedingRecordPlanService.getFeedingRecordPlanPage(pageReqVO);
        PageResult<FeedingRecordPlanRespVO> pageResult1 = new PageResult<>(buildVOList(pageResult.getList()), pageResult.getTotal());
        return success(pageResult1);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出投料分配计划 Excel")
    @PreAuthorize("@ss.hasPermission('mes:feeding-record-plan:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportFeedingRecordPlanExcel(@Valid FeedingRecordPlanPageReqVO pageReqVO,
                                             HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<FeedingRecordPlanDO> list = feedingRecordPlanService.getFeedingRecordPlanPage(pageReqVO).getList();
        List<FeedingRecordPlanRespVO> list1 = buildVOList(list);
        // 导出 Excel
        ExcelUtils.write(response, "投料分配计划.xls", "数据", FeedingRecordPlanRespVO.class,
                list1);
    }

    private List<FeedingRecordPlanRespVO> buildVOList(List<FeedingRecordPlanDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        Map<Long, ErpProductDO> map = productService.getProductMap(
                convertSet(list, FeedingRecordPlanDO::getItemId));
        Map<Long, ErpProductUnitDO> unitMap = productUnitService.getProductUnitMap(
                convertSet(list, FeedingRecordPlanDO::getUnitId));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(list, FeedingRecordPlanDO::getUserId));
        //投料单
        Map<Long, FeedingRecordDO> recordMap = feedingRecordService.getRecordMap(
                convertSet(list, FeedingRecordPlanDO::getRecordId));
        //生产计划
        Map<Long, PlanDO> planMap = planService.getPlanMap(
                convertSet(list, FeedingRecordPlanDO::getPlanId));

        return BeanUtils.toBean(list, FeedingRecordPlanRespVO.class, item -> {
            MapUtils.findAndThen(map, item.getItemId(),
                    product -> item.setItemName(product.getName()));
            MapUtils.findAndThen(unitMap, item.getUnitId(),
                    unit -> item.setUnitName(unit.getName()));
            MapUtils.findAndThen(userMap, item.getUserId(),
                    user -> item.setUserName(user.getNickname()));

            MapUtils.findAndThen(recordMap, item.getRecordId(),
                    record -> item.setRecordCode(record.getFeedingRecordCode()));
            MapUtils.findAndThen(planMap, item.getPlanId(),
                    plan -> item.setPlanCode(plan.getCode()));
        });
    }
}