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

import cn.hutool.extra.spring.SpringUtil;
import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.excel.core.util.ExcelUtils;
import com.zt.plat.module.contractorder.api.ContractApi;
import com.zt.plat.module.contractorder.api.ContractApiImpl;
import com.zt.plat.module.contractorder.api.OrderApi;
import com.zt.plat.module.contractorder.api.dto.order.PurchaseOrderWithDetailsDTO;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.*;
import com.zt.plat.module.contractorder.controller.admin.salesorder.vo.SalesOrderPageReqVO;
import com.zt.plat.module.contractorder.controller.admin.salesorder.vo.SalesOrderRespVO;
import com.zt.plat.module.contractorder.controller.admin.salesorder.vo.SalesOrderReviewReqVO;
import com.zt.plat.module.contractorder.controller.admin.salesorder.vo.SalesOrderSaveReqVO;
import com.zt.plat.module.contractorder.dal.dataobject.salesorder.SalesOrderDO;
import com.zt.plat.module.contractorder.service.purchaseorder.PurchaseOrderService;
import com.zt.plat.module.contractorder.service.salesorder.SalesOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.redisson.api.RObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.zt.plat.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - 销售订单")
@RestController
@RequestMapping("/base/sales-order")
@Validated
public class SalesOrderController implements BusinessControllerMarker {


    @Resource
    private SalesOrderService salesOrderService;

    @Resource
    private OrderApi orderApi;


    @PostMapping("/create")
    @Operation(summary = "创建销售订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:sales-order:create','sale:order:list:OrderList:add')")
    public CommonResult<SalesOrderRespVO> createSalesOrder(@Valid @RequestBody SalesOrderSaveReqVO createReqVO) {
        return success(salesOrderService.createSalesOrder(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新销售订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:sales-order:update','sale:order:list:OrderList:edit')")
    public CommonResult<Boolean> updateSalesOrder(@Valid @RequestBody SalesOrderSaveReqVO updateReqVO) {
        salesOrderService.updateSalesOrder(updateReqVO);
        return success(true);
    }

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

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除销售订单")
    @PreAuthorize("@ss.hasAnyPermissions('base:sales-order:delete','sale:order:list:OrderList:delete')")
    public CommonResult<Boolean> deleteSalesOrderList(@RequestBody BatchDeleteReqVO req) {
        salesOrderService.deleteSalesOrderListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得销售订单")
    @Parameter(name = "id", description = "id是订单主键，splyBsnTp是订单类型销售或者是消费", required = true, example = "1024")
    @PreAuthorize("@ss.hasAnyPermissions('base:sales-order:query','sale:order:list:OrderList:query')")
    public CommonResult<SalesOrderRespVO> getSalesOrder(@RequestParam("id") Long id, @RequestParam(value = "splyBsnTp", required = false) String splyBsnTp) {
        SalesOrderDO purchaseOrder = salesOrderService.getSalesOrder(id, splyBsnTp);
        SalesOrderRespVO salesOrderRespVO = BeanUtils.toBean(purchaseOrder, SalesOrderRespVO.class);
        if (salesOrderRespVO == null) {
            return success(null);
        }
        salesOrderService.setSalesOrderDetail(salesOrderRespVO);
        return success(salesOrderRespVO);
    }

    @GetMapping("/order-no")
    @Operation(summary = "通过订单号获得销售订单")
    @Parameter(name = "orderNo", description = "订单号", required = true, example = "1024")
    @PreAuthorize("@ss.hasAnyPermissions('base:sales-order:query','sale:order:list:OrderList:query')")
    public CommonResult<SalesOrderRespVO> getSalesOrderByNo(@RequestParam("orderNo") String orderNo) {
        SalesOrderDO purchaseOrder = salesOrderService.getSalesOrderByOrderNo(orderNo);
        SalesOrderRespVO salesOrderRespVO = BeanUtils.toBean(purchaseOrder, SalesOrderRespVO.class);
        if (salesOrderRespVO == null) {
            return success(null);
        }
        salesOrderService.setSalesOrderDetail(salesOrderRespVO);
        return success(salesOrderRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得销售订单分页")
    @PreAuthorize("@ss.hasAnyPermissions('base:sales-order:query','sale:order:list:OrderList:query')")
    public CommonResult<PageResult<SalesOrderRespVO>> getSalesOrderPage(@Valid SalesOrderPageReqVO pageReqVO) {
        PageResult<SalesOrderDO> pageResult = salesOrderService.getSalesOrderPage(pageReqVO);
        PageResult<SalesOrderRespVO> salesOrderRespVOPageResult = BeanUtils.toBean(pageResult, SalesOrderRespVO.class);
        if (salesOrderRespVOPageResult.getList() != null) {
            salesOrderRespVOPageResult.getList().forEach(purchaseOrderRespVO -> salesOrderService.setSalesOrderDetail(purchaseOrderRespVO));
        }

        return success(salesOrderRespVOPageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出销售订单 Excel")
    @PreAuthorize("@ss.hasAnyPermissions('base:sales-order:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSalesOrderExcel(@Valid SalesOrderPageReqVO pageReqVO,
                                      HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<SalesOrderDO> list = salesOrderService.getSalesOrderPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "销售订单.xls", "数据", PurchaseOrderRespVO.class,
                BeanUtils.toBean(list, PurchaseOrderRespVO.class));
    }

    //推送erp091
    @PostMapping("/push-erp091")
    @Operation(summary = "推送erp091")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','sale:order:list:OrderList:edit')")
    public CommonResult<Boolean> pushErp091(@RequestParam("id") String id) {
        salesOrderService.pushErp091(id);
        return success(true);
    }

    //提交审批
    @PostMapping("/submit-order")
    @Operation(summary = "提交审批")
    @PreAuthorize("@ss.hasAnyPermissions('base:purchase-order:update','sale:order:list:OrderList:edit')")
    public CommonResult<String> submitOrder(@RequestParam("id") String id) {
        return success(salesOrderService.submitOrder(id));
    }

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

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

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

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


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

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

    //feign测试
    @GetMapping("/get-sales-order-details-by-order-id")
    public CommonResult<?> getSalesOrderDetailsByOrderId(@RequestParam("orderId") String orderId) {
        return success(orderApi.getOrderByOrderNos(List.of(orderId.toString())));
    }
}
