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

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.stock.ErpStockOutDO;
import cn.iocoder.yudao.module.mes.controller.admin.feedingrecord.vo.FeedingRecordRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.itemrequisition.vo.ItemRequisitionDetailRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.itemrequisition.vo.ItemRequisitionPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.itemrequisition.vo.ItemRequisitionRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.itemrequisition.vo.ItemRequisitionSaveReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.plan.vo.PlanStatusUpdateVO;
import cn.iocoder.yudao.module.mes.controller.admin.task.vo.TaskStatusEnum;
import cn.iocoder.yudao.module.mes.dal.dataobject.itemrequisition.ItemRequisitionDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.itemrequisition.ItemRequisitionDetailDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.organization.OrganizationDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.orgworker.OrgWorkerDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.plan.PlanDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.task.TaskDO;
import cn.iocoder.yudao.module.mes.dal.mysql.itemrequisition.ItemRequisitionMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.orgworker.OrgWorkerMapper;
import cn.iocoder.yudao.module.mes.service.itemrequisition.ItemRequisitionService;
import cn.iocoder.yudao.module.mes.service.organization.OrganizationService;
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.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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/item-requisition")
@Validated
public class ItemRequisitionController {

    @Resource
    private ItemRequisitionService itemRequisitionService;
    @Resource
    private PlanService planService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private OrgWorkerMapper workerMapper;

    @Resource
    ItemRequisitionMapper itemRequisitionMapper;

    @PostMapping("/create")
    @Operation(summary = "创建生产领料")
    @PreAuthorize("@ss.hasPermission('mes:item-requisition:create')")
    public CommonResult<Long> createItemRequisition(@Valid @RequestBody ItemRequisitionSaveReqVO createReqVO) {
        return success(itemRequisitionService.createItemRequisition(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产领料")
    @PreAuthorize("@ss.hasPermission('mes:item-requisition:update')")
    public CommonResult<Boolean> updateItemRequisition(@Valid @RequestBody ItemRequisitionSaveReqVO updateReqVO) {
        itemRequisitionService.updateItemRequisition(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除生产领料")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:item-requisition:delete')")
    public CommonResult<Boolean> deleteItemRequisition(@RequestParam("id") Long id) {
        itemRequisitionService.deleteItemRequisition(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得生产领料")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:item-requisition:query')")
    public CommonResult<ItemRequisitionRespVO> getItemRequisition(@RequestParam("id") Long id) {
        ItemRequisitionDO itemRequisition = itemRequisitionService.getItemRequisition(id);
        return success(BeanUtils.toBean(itemRequisition, ItemRequisitionRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得生产领料分页")
    @PreAuthorize("@ss.hasPermission('mes:item-requisition:query')")
    public CommonResult<PageResult<ItemRequisitionRespVO>> getItemRequisitionPage(@Valid ItemRequisitionPageReqVO pageReqVO) {
        PageResult<ItemRequisitionDO> pageResult = itemRequisitionService.getItemRequisitionPage(pageReqVO);
        return success(new PageResult<>(buildVOList(pageResult.getList()), pageResult.getTotal()));
    }

    private List<ItemRequisitionRespVO> buildVOList(List<ItemRequisitionDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        Map<Long, OrganizationDO> organizationMap = organizationService.getOrganizationVOMap(
                convertSet(list, ItemRequisitionDO::getFeedingPipeline));
        Map<Long, PlanDO> map = planService.getPlanMap(
                convertSet(list, ItemRequisitionDO::getPlanId));
        // 1.4 领料员信息
        Map<Long, AdminUserRespDTO> workerMap = adminUserApi.getUserMap(
                convertSet(list, ItemRequisitionDO::getWorkerId));
        return BeanUtils.toBean(list, ItemRequisitionRespVO.class, item -> {
            MapUtils.findAndThen(map, item.getPlanId(), plan -> item.setPlanCode(plan.getCode()));
            MapUtils.findAndThen(organizationMap, item.getFeedingPipeline(), organization -> item.setFeedingPipelineName(organization.getName()));
            MapUtils.findAndThen(workerMap, item.getWorkerId(),
                    //如果这个org在orgWorkMap里面则根据org的workerId去userMap找到对应的人名
                    user -> item.setWorkerName(user.getUsername()));
        });
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出生产领料 Excel")
    @PreAuthorize("@ss.hasPermission('mes:item-requisition:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportItemRequisitionExcel(@Valid ItemRequisitionPageReqVO pageReqVO,
                                           HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ItemRequisitionDO> list = itemRequisitionService.getItemRequisitionPage(pageReqVO).getList();
        List<ItemRequisitionRespVO> list1 = buildVOList(list);
        // 导出 Excel
        ExcelUtils.write(response, "生产领料.xls", "数据", ItemRequisitionRespVO.class,
                list1);
    }

    // ==================== 子表（领料明细） ====================

    @GetMapping("/item-requisition-detail/list-by-item-requisition-id")
    @Operation(summary = "获得领料明细列表")
    @Parameter(name = "itemRequisitionId", description = "领料单ID")
    @PreAuthorize("@ss.hasPermission('mes:item-requisition:query')")
    public CommonResult<List<ItemRequisitionDetailRespVO>> getItemRequisitionDetailListByItemRequisitionId(@RequestParam("itemRequisitionId") Long itemRequisitionId) {
        List<ItemRequisitionDetailDO> list = itemRequisitionService.getItemRequisitionDetailListByItemRequisitionId(itemRequisitionId);
        ItemRequisitionDO requisitionDO = itemRequisitionService.getItemRequisition(itemRequisitionId);
        return success(itemRequisitionService.buildDetailVOList(list, requisitionDO.getPlanId()));
    }

    @GetMapping("/changeStatus")
    @Operation(summary = "更改领料单状态")
    public CommonResult<Boolean> changeStatus(@RequestParam("id") Long id) {
        ItemRequisitionDO itemRequisition = itemRequisitionMapper.selectById(id);
        itemRequisition.setStatus(5);
        itemRequisition.setRequisitionDate(LocalDate.now());
        int result = itemRequisitionMapper.updateById(itemRequisition);
        return success(true);
    }
}