package com.zt.plat.module.contractorder.controller.admin.purchaseorder;

import com.zt.plat.module.contractorder.api.ContractApiImpl;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.*;
import com.zt.plat.module.contractorder.dal.dataobject.purchaseorder.PurchaseOrderDO;
import com.zt.plat.module.contractorder.service.purchaseorder.PurchaseOrderService;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;

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 com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import static com.zt.plat.framework.common.pojo.CommonResult.customize;
import static com.zt.plat.framework.common.pojo.CommonResult.success;

import com.zt.plat.framework.excel.core.util.ExcelUtils;

import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;

import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 采购订单")
@RestController
@RequestMapping("/base/purchase-order")
@Validated
public class PurchaseOrderController implements BusinessControllerMarker {


    @Resource
    private PurchaseOrderService purchaseOrderService;
    @Resource
    private ContractApiImpl contractApi;


    @PostMapping("/create")
    @Operation(summary = "创建采购订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:create','purchase:order:list:OrderList:add')")
    public CommonResult<PurchaseOrderRespVO> createPurchaseOrder(@Valid @RequestBody PurchaseOrderSaveReqVO createReqVO) {
        return success(purchaseOrderService.createPurchaseOrder(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新采购订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','purchase:order:list:OrderList:edit')")
    public CommonResult<Boolean> updatePurchaseOrder(@Valid @RequestBody PurchaseOrderSaveReqVO updateReqVO) {
        purchaseOrderService.updatePurchaseOrder(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除采购订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:delete','purchase:order:list:OrderList:delete')")
    public CommonResult<Boolean> deletePurchaseOrder(@RequestParam("id") Long id) {
        purchaseOrderService.deletePurchaseOrder(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除采购订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:delete','purchase:order:list:OrderList:delete')")
    public CommonResult<Boolean> deletePurchaseOrderList(@RequestBody BatchDeleteReqVO req) {
        purchaseOrderService.deletePurchaseOrderListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得采购订单")
    @Parameter(name = "id", description = "id是订单主键，splyBsnTp是订单类型采购或者是消费", required = true, example = "1024")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:query')")
    public CommonResult<PurchaseOrderRespVO> getPurchaseOrder(@RequestParam("id") Long id, @RequestParam(value = "splyBsnTp", required = false) String splyBsnTp) {
        PurchaseOrderDO purchaseOrder = purchaseOrderService.getPurchaseOrder(id, splyBsnTp);
        PurchaseOrderRespVO purchaseOrderRespVO = BeanUtils.toBean(purchaseOrder, PurchaseOrderRespVO.class);
        if (purchaseOrderRespVO == null) {
            return success(null);
        }
        purchaseOrderService.setOrderDetails(purchaseOrderRespVO);
        return success(purchaseOrderRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得采购订单分页")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:query')")
    public CommonResult<PageResult<PurchaseOrderRespVO>> getPurchaseOrderPage(@Valid PurchaseOrderPageReqVO pageReqVO) {
        PageResult<PurchaseOrderDO> pageResult = purchaseOrderService.getPurchaseOrderPage(pageReqVO);
        PageResult<PurchaseOrderRespVO> purchaseOrderRespVOPageResult = BeanUtils.toBean(pageResult, PurchaseOrderRespVO.class);
        if (purchaseOrderRespVOPageResult.getList().isEmpty()) {
            return success(purchaseOrderRespVOPageResult);
        }
        purchaseOrderRespVOPageResult.getList().forEach(purchaseOrderRespVO -> purchaseOrderService.setOrderDetails(purchaseOrderRespVO));
        return success(purchaseOrderRespVOPageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出采购订单 Excel")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportPurchaseOrderExcel(@Valid PurchaseOrderPageReqVO pageReqVO,
                                         HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PurchaseOrderDO> list = purchaseOrderService.getPurchaseOrderPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "采购订单.xls", "数据", PurchaseOrderRespVO.class,
                BeanUtils.toBean(list, PurchaseOrderRespVO.class));
    }

    //提交订单审核
    @PostMapping("/submit-order")
    @Operation(summary = "提交订单审核")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','purchase:order:list:OrderList:edit')")
    public CommonResult<Boolean> submitOrder(@RequestParam("id") String id) {
        purchaseOrderService.submitOrder(Long.valueOf(id));
        return success(true);
    }

    @PostMapping("/submit-order-batch")
    @Operation(summary = "批量提交订单审核")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','purchase:order:list:OrderList:edit')")
    public CommonResult<Boolean> submitOrder(@RequestBody @Validated @NotEmpty(message = "采购订单id不能为空") List<String> ids) {
        System.out.println("ids:" + ids);
        ids.forEach(id -> purchaseOrderService.submitOrder(Long.valueOf(id)));
        return success(true);
    }

    //提交ERP订单
    @PostMapping("/submit-erp061")
    @Operation(summary = "推送ERP订单", description = "061')")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','purchase:order:list:OrderList:edit')")
    public CommonResult<?> submitErp061(@RequestParam("id") String id) {
        return success(purchaseOrderService.submitErp061(List.of(Long.valueOf(id))));
    }

    @PostMapping("/submit-erp062")
    @Operation(summary = "推送ERP订单", description = "062当每次调更新接口后都需要调此接口")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','purchase:order:list:OrderList:edit')")
    public CommonResult<?> submitErp062(@RequestParam @Validated @NotNull(message = "采购订单id不能为空") String id) {
        // todo 推送ERP订单
        return success(purchaseOrderService.submitErp062ByUpdate(Long.valueOf(id)));
    }

    //通过订单号查询订单信息
    @PostMapping("/get-order-by-order-no")
    @Operation(summary = "通过订单号查询订单信息", description = "通过订单号查询订单信息")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:query')")
    public CommonResult<List<PurchaseOrderDetailsRespVO>> getOrderByOrderNo(@RequestBody @Validated @NotEmpty(message = "采购订单不能为空") List<String> orderNos) {
        return success(purchaseOrderService.getOrderByOrderNo(orderNos));
    }

    //根据订单id修改订单状态
    @PutMapping("/update-order-status")
    @Operation(summary = "批量修改订单状态", description = "sts取值于字典名称'采购订单状态',字典类型'PRCH_ORD_STS' 可以根据订单号和订单id修改")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','purchase:order:list:OrderList:edit')")
    public CommonResult<Boolean> updateOrderStatus(@RequestBody @Validated OrderStsReqVO req) {
        purchaseOrderService.updateOrderStatusByIdOrOrderNo(req);
        return success(true);
    }

    //查询物料接口
    @GetMapping("/material")
    @Operation(summary = "查询物料接口")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:query')")
    public CommonResult<MaterialRespVO> getMaterialList(@RequestParam
                                                        @Schema(description = "采购订单号")
                                                        @Validated
                                                        @NotEmpty(message = "采购订单号不能为空")
                                                        String orderNo) {
        return purchaseOrderService.getMaterial(orderNo);
    }

    //关联订单
    @PostMapping("/link-order")
    @Operation(summary = "关联订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','purchase:order:list:OrderList:edit')")
    public CommonResult<Boolean> linkOrder(@RequestBody @Validated LinkOrderReqVO req) {
        return success(purchaseOrderService.linkOrder(req));
    }

    @PostMapping("/order-pass-reject")
    @Operation(summary = "订单审核")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','purchase:order:list:OrderList:edit')")
    public CommonResult<Boolean> orderPassReject(@RequestBody PurchaseorderReqVO reqVO) {
        return success(purchaseOrderService.orderPassReject(reqVO));
    }

    //根据订单id和方式获取上或下游订单
    @PostMapping("/order-by-order-id-and-type")
    @Operation(summary = "根据订单id和方式获取上或下游订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:query')")
    public CommonResult<List<DownOrUpOrderRespVO>> getOrderByOrderIdAndType(@RequestBody DownOrUpOrderReqVO reqVO) {
        return success(purchaseOrderService.getOrderByOrderIdAndType(reqVO));
    }


    @PostMapping("/bound-order")
    @Operation(summary = "获取已绑定的订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:query')")
    public CommonResult<List<PurchaseOrderRespVO>> boundOrder(@RequestBody DownOrUpOrderReqVO reqVO) {
        return success(purchaseOrderService.getBindOrderByOrder(reqVO));
    }

    //无权限查询订单
    @PostMapping("/page-no-permission")
    @Operation(summary = "无权限查询订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:query')")
    public CommonResult<PageResult<PurchaseOrderRespVO>> pageOrderNoPermission(@RequestBody PurchaseOrderPageReqVO pageReqVO) {
        PageResult<PurchaseOrderDO> pageResult = purchaseOrderService.pageOrderNoPermission(pageReqVO);
        return success( BeanUtils.toBean(pageResult, PurchaseOrderRespVO.class));
    }
    //关联订单
    @PostMapping("/bound-order-by-id")
    @Operation(summary = "关联订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','purchase:order:list:OrderList:edit')")
    public CommonResult<Boolean> boundOrder(@RequestBody @Validated BoundOrderReqVO req) {
        purchaseOrderService.boundOrder(req);
        return success(true);
    }

}
