package org.dromara.erp.controller;

import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.erp.domain.query.ErpOrderQuery;
import org.dromara.erp.domain.vo.ErpOrderVo;
import org.dromara.erp.service.IErpOrderService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 * @Author: Antigravity
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/erp/order")
public class ErpOrderController {

    private final IErpOrderService erpOrderService;

    /**
     * 分页查询订单列表
     */
    @GetMapping("/list")
    public TableDataInfo<ErpOrderVo> list(ErpOrderQuery query, PageQuery pageQuery) {
        return erpOrderService.queryPageList(query, pageQuery);
    }

    /**
     * 查询订单列表 (不分页)
     */
    @GetMapping("/all")
    public R<List<ErpOrderVo>> all(ErpOrderQuery query) {
        return R.ok(erpOrderService.queryList(query));
    }

    /**
     * 小程序端查询我的订单列表（按当前登录用户过滤，每页5条）
     */
    @GetMapping("/myList")
    public TableDataInfo<ErpOrderVo> myList(ErpOrderQuery query, PageQuery pageQuery) {
        query.setPlacer(LoginHelper.getUserId());
        pageQuery.setPageSize(5);
        return erpOrderService.queryPageList(query, pageQuery);
    }

    /**
     * 按客户ID分页查询订单（不限制下单人，供客户卡片跳转使用）
     */
    @GetMapping("/listByClient")
    public TableDataInfo<ErpOrderVo> listByClient(ErpOrderQuery query, PageQuery pageQuery) {
        pageQuery.setPageSize(5);
        return erpOrderService.queryPageListByClientId(query, pageQuery);
    }

    /**
     * 按状态统计订单数量
     */
    @GetMapping("/count")
    public R<Map<Integer, Long>> count() {
        return R.ok(erpOrderService.countByStatus());
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{rowId}")
    public R<ErpOrderVo> getInfo(@PathVariable("rowId") String rowId) {
        return R.ok(erpOrderService.queryById(rowId));
    }

    /**
     * 新增订单
     */
    @RepeatSubmit()
    @PostMapping("/add")
    public R<String> add(@RequestBody org.dromara.erp.domain.bo.ErpOrderBo bo) {
        String rowId = erpOrderService.insert(bo);
        return rowId != null ? R.ok("操作成功", rowId) : R.fail();
    }

    /**
     * 撤销订单（单纯修改订单状态为已撤销）
     */
    @RepeatSubmit()
    @PostMapping("/cancel/{rowId}")
    public R<Void> cancel(@PathVariable("rowId") String rowId) {
        return erpOrderService.cancelOrder(rowId) ? R.ok() : R.fail();
    }

    /**
     * 加急订单
     * @Author: Trae
     */
    @RepeatSubmit()
    @PostMapping("/urgent/{rowId}")
    public R<Void> markUrgent(@PathVariable("rowId") String rowId) {
        return erpOrderService.markUrgent(rowId) ? R.ok() : R.fail();
    }
}
