
package com.tmerclub.cloud.order.controller.supplier;

import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.dto.OrderInvoiceDTO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.order.constant.OrderInvoiceState;
import com.tmerclub.cloud.order.model.OrderInvoice;
import com.tmerclub.cloud.order.service.OrderInvoiceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

/**
 * @author Pineapple
 * @date 2021/8/2 8:59
 */
@RestController("supplierOrderInvoiceController")
@RequestMapping("/s/order_invoice")
@Tag(name = "供应商端订单发票")
public class OrderInvoiceController {
    @Autowired
    private OrderInvoiceService orderInvoiceService;


    @GetMapping
    @Operation(summary = "获取详细发票信息", description = "根据orderInvoiceId获取发票信息")
    public ServerResponseEntity<OrderInvoice> getByOrderInvoiceId(@RequestParam Long orderInvoiceId) {
        return ServerResponseEntity.success(orderInvoiceService.getByOrderInvoiceId(orderInvoiceId));
    }

    @PutMapping
    @Operation(summary = "更新发票信息", description = "更新发票信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody OrderInvoiceDTO orderInvoiceDTO) {
        OrderInvoice orderInvoice = BeanUtil.map(orderInvoiceDTO, OrderInvoice.class);
        if (Objects.isNull(orderInvoiceDTO.getFileId())) {
            //商家提交，不上传文件不给保存
            throw new LuckException("请上传文件");
        }
        orderInvoice.setInvoiceState(OrderInvoiceState.ISSUED.value());
        orderInvoice.setUploadTime(new Date());
        orderInvoiceService.update(orderInvoice);
        return ServerResponseEntity.success();
    }

    @Operation(summary = "该订单是否已经上传发票")
    @GetMapping("/is_upload")
    public ServerResponseEntity<Boolean> isUpload(@RequestParam Long orderId) {
        Long supplierId = AuthUserContext.get().getTenantId();
        return ServerResponseEntity.success(orderInvoiceService.isUpload(orderId, null, supplierId));
    }
}
