package com.ruoyi.database.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUserByPhone;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.database.domain.BaseInvoiceInfo;
import com.ruoyi.database.domain.dto.BaseInvoiceInfoDto;
import com.ruoyi.database.service.BaseInvoiceInfoService;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * 发票信息表(BaseInvoiceInfo)Controller
 *
 * @author hanrenchun
 * @since 2026-04-08 09:26:38
 */
@RequestMapping("/BaseInvoiceInfo")
@Api(tags = "发票信息")
@RestController
@RequiredArgsConstructor
public class BaseInvoiceInfoController extends BaseController {

    private final BaseInvoiceInfoService baseInvoiceInfoService;
    private final TokenService tokenService;

    @GetMapping
    @ApiOperation("查询当前已开发票信息(详情)")
    public AjaxResult list(@RequestParam String inUnid, HttpServletRequest request) {
        LoginUserByPhone loginUserByPhone = tokenService.getLoginUserByPhone(request);
        BaseInvoiceInfo one = baseInvoiceInfoService.lambdaQuery()
                .eq(BaseInvoiceInfo::getInUnid, inUnid)
                .eq(BaseInvoiceInfo::getUserPhone,loginUserByPhone.getPhone())
                .last("LIMIT 1")
                .one();
        if (one != null) {
            return AjaxResult.success(one);
        }else {
            return AjaxResult.error("未找到对应订单");
        }
    }



    @PostMapping
    @ApiOperation("新增发票开票任务")
    @Transactional
    public AjaxResult insert(@RequestBody BaseInvoiceInfoDto baseInvoiceInfo, HttpServletRequest request) {
        try {
            LoginUserByPhone loginUserByPhone = tokenService.getLoginUserByPhone(request);
            List<String> inUnid = baseInvoiceInfo.getInUnid();
            String uuid = UUID.randomUUID().toString();
            for (String s : inUnid) {
                BaseInvoiceInfo invoiceInfo = new BaseInvoiceInfo();
                BeanUtils.copyProperties(baseInvoiceInfo,invoiceInfo);
                invoiceInfo.setInUnid(s);
                invoiceInfo.setInvoiceTypeCode(0);
                invoiceInfo.setPriceTaxMark(1);
                invoiceInfo.setUserPhone(loginUserByPhone.getPhone());
                invoiceInfo.setPlId(uuid);
                baseInvoiceInfoService.save(invoiceInfo);
            }
            return AjaxResult.success("操作成功，等待开票");
        } catch (BeansException e) {
            return AjaxResult.error("操作失败");
        }
    }

}
