package cn.iocoder.foodnexus.module.order.controller.admin.checktask;

import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.framework.common.util.collection.MapUtils;
import cn.iocoder.foodnexus.module.erp.api.service.ErpCustomerApi;
import cn.iocoder.foodnexus.module.erp.api.service.ErpSupplierApi;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.purchase.ErpPurchaseOrderDO;
import cn.iocoder.foodnexus.module.erp.service.purchase.ErpPurchaseOrderService;
import cn.iocoder.foodnexus.module.order.controller.app.customerOrder.vo.AppCustomerOrderScoreReqVO;
import cn.iocoder.foodnexus.module.order.controller.app.customerOrder.vo.AppCustomerOrderScoreRespVO;
import cn.iocoder.foodnexus.module.order.service.checktaskitems.CheckTaskItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.foodnexus.framework.common.pojo.PageParam;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.pojo.CommonResult;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;
import static cn.iocoder.foodnexus.framework.common.pojo.CommonResult.success;

import cn.iocoder.foodnexus.framework.excel.core.util.ExcelUtils;

import cn.iocoder.foodnexus.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.foodnexus.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.foodnexus.module.order.controller.admin.checktask.vo.*;
import cn.iocoder.foodnexus.module.order.dal.dataobject.checktask.CheckTaskDO;
import cn.iocoder.foodnexus.module.order.service.checktask.CheckTaskService;

@Tag(name = "管理后台 - 来料质检")
@RestController
@RequestMapping("/order/check-task")
@Validated
public class CheckTaskController {

    @Resource
    private CheckTaskService checkTaskService;

    @Autowired
    private CheckTaskItemsService checkTaskItemsService;

    @Autowired
    private ErpSupplierApi supplierApi;

    @Autowired
    private ErpPurchaseOrderService purchaseOrderService;

    @Autowired
    private ErpCustomerApi customerApi;

    @PostMapping("/create")
    @Operation(summary = "创建来料质检")
    @PreAuthorize("@ss.hasPermission('order:check-task:create')")
    public CommonResult<Long> createCheckTask(@Valid @RequestBody CheckTaskSaveReqVO createReqVO) {
        return success(checkTaskService.createCheckTask(createReqVO));
    }

    @PutMapping("/check")
    @Operation(summary = "质检")
    @PreAuthorize("@ss.hasPermission('order:check-task:update')")
    public CommonResult<Boolean> check(@Valid @RequestBody CheckTaskCheckReqVO updateReqVO) {
        checkTaskService.check(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除来料质检")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('order:check-task:delete')")
    public CommonResult<Boolean> deleteCheckTask(@RequestParam("id") Long id) {
        checkTaskService.deleteCheckTask(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除来料质检")
                @PreAuthorize("@ss.hasPermission('order:check-task:delete')")
    public CommonResult<Boolean> deleteCheckTaskList(@RequestParam("ids") List<Long> ids) {
        checkTaskService.deleteCheckTaskListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得来料质检")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('order:check-task:query')")
    public CommonResult<CheckTaskRespVO> getCheckTask(@RequestParam("id") Long id) {
        CheckTaskDO checkTask = checkTaskService.getCheckTask(id);
        return success(BeanUtils.toBean(checkTask, CheckTaskRespVO.class, item -> {
            item.setItems(BeanUtils.toBean(checkTaskItemsService.queryByCheckId(item.getId()), CheckTaskItemsRespVO.class));
            item.setSupplierName(supplierApi.queryNameById(item.getSupplierId()));
            item.setCustomerName(customerApi.queryNameStrById(item.getCustomerId()));
            Map<Long, String> itemMap = checkTaskItemsService.queryProductInfoByCheckId(CommonUtil.asList(item.getId()));
            item.setProductNames(itemMap.getOrDefault(item.getId(), ""));
            item.setPurchaseOrderNo(purchaseOrderService.getPurchaseOrder(item.getPurchaseOrderId()).getNo());
        }));
    }

    @GetMapping("/page")
    @Operation(summary = "获得来料质检分页")
    @PreAuthorize("@ss.hasPermission('order:check-task:query')")
    public CommonResult<PageResult<CheckTaskRespVO>> getCheckTaskPage(@Valid CheckTaskPageReqVO pageReqVO) {
        PageResult<CheckTaskDO> pageResult = checkTaskService.getCheckTaskPage(pageReqVO);
        Map<Long, String> supplierNameMap = supplierApi.queryNameMapByIds(CommonUtil.listConvertSet(pageResult.getList(), CheckTaskDO::getSupplierId));
        Map<Long, String> productInfoMap = checkTaskItemsService.queryProductInfoByCheckId(CommonUtil.listConvertSet(pageResult.getList(), CheckTaskDO::getId));
        Map<Long, ErpPurchaseOrderDO> purchaseOrderMap = purchaseOrderService.getMap(CommonUtil.listConvert(pageResult.getList(), CheckTaskDO::getPurchaseOrderId));
        Map<Long, String> customerMap = customerApi.queryNameMapByIds(CommonUtil.listConvertSet((pageResult.getList()), CheckTaskDO::getCustomerId));

        return success(BeanUtils.toBean(pageResult, CheckTaskRespVO.class, item -> {
            MapUtils.findAndThen(supplierNameMap, item.getSupplierId(), item::setSupplierName);
            MapUtils.findAndThen(customerMap, item.getCustomerId(), item::setCustomerName);
            MapUtils.findAndThen(productInfoMap, item.getId(), item::setProductNames);
            MapUtils.findAndThen(purchaseOrderMap, item.getPurchaseOrderId(), purchaseOrder -> {
                item.setPurchaseOrderNo(purchaseOrder.getNo());
            });
        }));
    }

    @GetMapping("score")
    @Operation(summary = "查询订单评价")
    @Parameter(name = "id", description = "来料质检id", required = true)
    public CommonResult<CheckTaskSupplierScoreRespVO> queryScore(@RequestParam("id") Long id) {
        return success(checkTaskService.queryScore(id));
    }

    @GetMapping("query-checktask-and-score")
    @Operation(summary = "根据采购订单id获取质检报告和评价")
    @Parameter(name = "purchaseOrderId", description = "采购订单id", required = true)
    public CommonResult<CheckTaskWithScoreRespVO> queryCheckTaskAndScore(@RequestParam("purchaseOrderId") Long purchaseOrderId) {
        CheckTaskDO checkTaskDO = checkTaskService.queryScorebyPurchaseOrderId(purchaseOrderId);
        if (CommonUtil.isNotEmpty(checkTaskDO)) {
            return success(new CheckTaskWithScoreRespVO(
                    this.getCheckTask(checkTaskDO.getId()).getData(), this.queryScore(checkTaskDO.getId()).getData()));
        }
        return success(null);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出来料质检 Excel")
    @PreAuthorize("@ss.hasPermission('order:check-task:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportCheckTaskExcel(@Valid CheckTaskPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CheckTaskDO> list = checkTaskService.getCheckTaskPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "来料质检.xls", "数据", CheckTaskRespVO.class,
                        BeanUtils.toBean(list, CheckTaskRespVO.class));
    }

}