package com.ruoyi.app.mendian;

import com.ruoyi.app.order.OrderInvoiceService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.vo.PosOrderInvoiceVo;
import com.ruoyi.system.domain.dto.InvalidInvoiceDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


/**
 * 平台后台 / 商家端 - 订单电子发票管理（查看 / 重新开票 / 作废）。
 *
 * @author ruoyi
 * @date 2026-06-16
 */
@RestController
@RequestMapping("/system/orderInvoice")
public class PosOrderInvoiceController extends BaseController {

    @Autowired
    private OrderInvoiceService orderInvoiceService;

    /** 订单发票列表（分页 + 筛选）。 */
    @PreAuthorize("@ss.hasPermi('chanting:orderInvoice:list')")
    @GetMapping("/list")
    public TableDataInfo list(PosOrderInvoiceVo query) {
        // 管理端发票管理只看进过开票流程的（issueTriggered=1），排除仅下单捕获意图、未触发行
        if (query.getIssueTriggered() == null) {
            query.setIssueTriggered(1);
        }
        startPage();
        return getDataTable(orderInvoiceService.list(query));
    }

    /** 订单发票详情。 */
    @PreAuthorize("@ss.hasPermi('chanting:orderInvoice:query')")
    @GetMapping("/{orderId}")
    public AjaxResult getInfo(@PathVariable Long orderId) {
        return success(orderInvoiceService.detail(orderId));
    }

    /** 重新开票（仅 失败/作废 单）。 */
    @PreAuthorize("@ss.hasPermi('chanting:orderInvoice:retry')")
    @Log(title = "订单发票重新开票", businessType = BusinessType.UPDATE)
    @PutMapping("/retry/{orderId}")
    public AjaxResult retry(@PathVariable Long orderId) {
        return toAjax(orderInvoiceService.retry(orderId));
    }

    /** 作废发票（仅 已开 单，调 ezPay invoice_invalid）。入参可选 {invalidReason}。 */
    @PreAuthorize("@ss.hasPermi('chanting:orderInvoice:invalid')")
    @Log(title = "订单发票作废", businessType = BusinessType.UPDATE)
    @PutMapping("/invalid/{orderId}")
    public AjaxResult invalid(@PathVariable Long orderId, @RequestBody(required = false) InvalidInvoiceDto dto) {
        String reason = dto == null ? null : dto.getInvalidReason();
        return toAjax(orderInvoiceService.invalid(orderId, reason));
    }
}
