package com.heyu.api.controller.financial;


import com.heyu.api.baidu.handle.financial.BVatInvoiceVerificationHandle;
import com.heyu.api.baidu.request.financial.BVatInvoiceVerificationRequest;
import com.heyu.api.baidu.response.financial.BCommonVatInvoiceVerificationResp;
import com.heyu.api.baidu.response.financial.BVatInvoiceVerificationResp;
import com.heyu.api.controller.BaseController;
import com.heyu.api.data.annotation.CacheResult;
import com.heyu.api.data.annotation.NotIntercept;
import com.heyu.api.data.utils.ApiR;
import com.heyu.api.data.utils.R;
import com.heyu.api.request.financial.CommonVatInvoiceVerificationRequest;
import com.heyu.api.resp.financial.CommonVatInvoiceVerificationResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/***
 *https://console.bce.baidu.com/support/?_=1740494347073&timestamp=1740500368284#/api?product=AI&project=%E6%96%87%E5%AD%97%E8%AF%86%E5%88%AB&parent=%E8%B4%A2%E5%8A%A1%E7%A5%A8%E6%8D%AEOCR&api=rest%2F2.0%2Focr%2Fv1%2Fvat_invoice_verification&method=post
 *
 *
 * 增值税发票验真
 *
 *
 *
 * 支持 14 种增值税发票的信息核验，包括增值税专票、电子专票、普票、电子普票、卷票、区块链发票（深圳地区）、全电发票（新版全国统一电子发票，专票/普票）、通行费增值税电子普通发票、货物运输业增值税专用发票、
 * 机动车销售发票、二手车销售发票、航空运输电子客票行程单（电子发票）、铁路电子客票（电子发票）等，支持返回票面的全部信息。同时可直接与同平台的发票识别能力对接，完成发票识别的同时进行自动化验真。
 *
 *
 * 视频教程请参见 智能财务票据识别+增值税发票验真使用教程
 *
 *
 */
@Slf4j
@RestController
@RequestMapping("/common/vat/Invoice")
@NotIntercept
public class CommonVatInvoiceVerificationController extends BaseController {


    @Autowired
    private BVatInvoiceVerificationHandle bVatInvoiceVerificationHandle;


    @RequestMapping("/verification")
    @CacheResult
    public R verification(CommonVatInvoiceVerificationRequest req) {

        BVatInvoiceVerificationRequest bVatInvoiceVerificationRequest = new BVatInvoiceVerificationRequest();
        bVatInvoiceVerificationRequest.setInvoiceCode(req.getInvoiceCode());
        bVatInvoiceVerificationRequest.setInvoiceNum(req.getInvoiceNum());
        bVatInvoiceVerificationRequest.setInvoiceDate(req.getInvoiceDate());
        bVatInvoiceVerificationRequest.setInvoiceType(req.getInvoiceType());
        bVatInvoiceVerificationRequest.setCheckCode(req.getCheckCode());
        bVatInvoiceVerificationRequest.setTotalAmount(req.getTotalAmount());


        CommonVatInvoiceVerificationResp resp = new CommonVatInvoiceVerificationResp();


        ApiR<BVatInvoiceVerificationResp> bR = bVatInvoiceVerificationHandle.handle(bVatInvoiceVerificationRequest, BCommonVatInvoiceVerificationResp.class);
        if (bR.isSuccess()) {
            BCommonVatInvoiceVerificationResp bCommonVatInvoiceVerificationResp = (BCommonVatInvoiceVerificationResp) bR.getData();
            BCommonVatInvoiceVerificationResp.WordsResultDTO wordsResultDTO = bCommonVatInvoiceVerificationResp.getWordsResult();

            String verifyFrequency = wordsResultDTO.getVerifyFrequency();    // 查验次数。为历史查验次数
            String verifyMessage = wordsResultDTO.getVerifyMessage();      //查验结果信息。查验成功且发票为真返回“查验成功发票一致“，查验失败返回对应错误原因，详见末尾表格
            String invalidSign= wordsResultDTO.getInvalidSign();         // 是否作废（冲红）。Y：已作废；H：已冲红；N：未作废
            String invoiceType = wordsResultDTO.getInvoiceType();     //发票种类。即增值税专用发票、增值税电子专用发票、增值税普通发票、增值税普通发票（电子）、增值税普通发票（卷式）、通行费增值税电子普通发票、区块链电子发票、全电发票（专用发票）、全电发票（普通发票）、机动车销售发票、二手车销售发票、货物运输业增值税专用发票、航空运输电子客票行程单（电子发票）、铁路电子客票（电子发票）
            String machineCode = wordsResultDTO.getMachineCode();                 //机器编号
            String checkCode = wordsResultDTO.getCheckCode();           //校验码
            String invoiceCode = wordsResultDTO.getInvoiceCode();             //发票代码
            String invoiceDate = wordsResultDTO.getInvoiceDate();             //	开票日期
            String verifyResult = wordsResultDTO.getVerifyResult();            //查验结果。查验成功返回“0001”，查验失败返回对应查验结果错误码，详见末尾表格
            String invoiceNum = wordsResultDTO.getInvoiceNum();              //发票号码
            String taxControlNum = wordsResultDTO.getTaxControlNum();                   //税控盘号。货运专票返回信息，其他类型发票可忽略
            resp.setVerifyFrequency(verifyFrequency);
            resp.setVerifyMessage(verifyMessage);
            resp.setInvalidSign(invalidSign);
            resp.setInvoiceType(invoiceType);
            resp.setMachineCode(machineCode);
            resp.setCheckCode(checkCode);
            resp.setInvoiceCode(invoiceCode);
            resp.setInvoiceDate(invoiceDate);
            resp.setVerifyResult(verifyResult);
            resp.setInvoiceNum(invoiceNum);
            resp.setTaxControlNum(taxControlNum);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityEndDate = new ArrayList<>();            // 	通行日期止。通行费增值税电子普通发票返回信息，其他类型发票可忽略wordsResultDTO
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityEndDate())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityEndDateDTO commodityEndDateDTO : wordsResultDTO.getCommodityEndDate()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityEndDateDTO.getRow());
                    commodityDTO.setWord(commodityEndDateDTO.getWord());
                    commodityEndDate.add(commodityDTO);
                }
            }
            resp.setCommodityEndDate(commodityEndDate);

            resp.setVehicleTonnage(wordsResultDTO.getVehicleTonnage());                  //车船吨位。货运专票返回信息，其他类型发票可忽略
            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityVehicleType = new ArrayList<>();        //类型。通行费增值税电子普通发票返回信息，其他类型发票可忽略
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityVehicleType())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityVehicleTypeDTO commodityVehicleTypeDTO : wordsResultDTO.getCommodityVehicleType()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityVehicleTypeDTO.getRow());
                    commodityVehicleType.add(commodityDTO);
                }
            }
            resp.setCommodityVehicleType(commodityVehicleType);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityStartDate  = new ArrayList<>();      //通行日期起。通行费增值税电子普通发票返回信息，其他类型发票可忽略
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityStartDate())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityStartDateDTO commodityStartDateDTO : wordsResultDTO.getCommodityStartDate()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityStartDateDTO.getRow());
                    commodityDTO.setWord(commodityStartDateDTO.getWord());
                    commodityStartDate.add(commodityDTO);
                    commodityStartDate.add(commodityDTO);
                }
            }
            resp.setCommodityStartDate(commodityStartDate);

            resp.setSellerAddress(wordsResultDTO.getSellerAddress());                   //	销售方地址及电话

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityPrice = new ArrayList<>();      //单价
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityPrice())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityPriceDTO commodityPriceDTO : wordsResultDTO.getCommodityPrice()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityPriceDTO.getRow());
                    commodityDTO.setWord(commodityPriceDTO.getWord());
                    commodityPrice.add(commodityDTO);
                    commodityPrice.add(commodityDTO);
                }
            }
            resp.setCommodityPrice(commodityPrice);

            resp.setTransportCargoInformation(wordsResultDTO.getTransportCargoInformation());           //运输货物信息。货运专票返回信息，其他类型发票可忽略
            resp.setNoteDrawer(wordsResultDTO.getNoteDrawer());          //开票人（因税局不返回此字段，故字段为空，暂做保留使用）
            resp.setSellerRegisterNum(wordsResultDTO.getSellerRegisterNum());           //销售方纳税人识别号
            resp.setSellerBank(wordsResultDTO.getSellerBank());                      //销售方开户行及账号
            resp.setRemarks(wordsResultDTO.getRemarks());                     //	备注
            resp.setTotalTax(wordsResultDTO.getTotalTax());                //合计税额
            resp.setZeroTaxRateIndicator(wordsResultDTO.getZeroTaxRateIndicator());        //零税率标识。空：非零税率,1：税率栏位显示“免税”，2：税率栏位显示“不征税”，3：零税率。通行费增值税电子普通发票返回信息，其他类型发票可忽略
            resp.setCarrier(wordsResultDTO.getCarrier());                         //承运人名称。货运专票返回信息，其他类型发票可忽略
            resp.setSenderCode(wordsResultDTO.getSenderCode());                              //	发货人识别号。货运专票返回信息，其他类型发票可忽略
            resp.setPurchaserRegisterNum(wordsResultDTO.getPurchaserRegisterNum());                    //	购方纳税人识别号
            resp.setReceiverCode(wordsResultDTO.getReceiverCode());                            //收货人识别号。货运专票返回信息，其他类型发票可忽略
            resp.setAmountInFiguers(wordsResultDTO.getAmountInFiguers());                     //价税合计（小写）
            resp.setPurchaserBank(wordsResultDTO.getPurchaserBank());                           //	购方开户行及账号
            resp.setChecker(wordsResultDTO.getChecker());                     //复核（因税局不返回此字段，故字段为空，暂做保留使用）
            resp.setTollSign(wordsResultDTO.getTollSign());                //通行费标志。Y-可抵扣通行费，N-不可抵扣通行费。通行费增值税电子普通发票返回信息，其他类型发票可忽略
            resp.setVehicleTypeNum(wordsResultDTO.getVehicleTypeNum());
            resp.setDepartureViaArrival(wordsResultDTO.getDepartureViaArrival());                                 //	起运地、经由、到达地。货运专票返回信息，其他类型发票可忽略
            resp.setReceiver(wordsResultDTO.getReceiver());                    //	收货人名称。货运专票返回信息，其他类型发票可忽略
            resp.setRecipient(wordsResultDTO.getRecipient());                   //	受票方名称。货运专票返回信息，其他类型发票可忽略
            resp.setTotalAmount(wordsResultDTO.getTotalAmount());         //	合计金额
            resp.setPurchaserName(wordsResultDTO.getPurchaserName());           //购方名称
            resp.setSender(wordsResultDTO.getSender());                          //	发货人名称。货运专票返回信息，其他类型发票可忽略
            resp.setPurchaserAddress(wordsResultDTO.getPurchaserAddress());                //	买方单位/个人住址
            resp.setCarrierCode(wordsResultDTO.getCarrierCode());         //承运人识别号。货运专票返回信息，其他类型发票可忽略
            resp.setPayee(wordsResultDTO.getPayee());                   //收款人（因税局不返回此字段，故字段为空，暂做保留使用）
            resp.setRecipientCode(wordsResultDTO.getRecipientCode());           //受票方识别号。货运专票返回信息，其他类型发票可忽略
            resp.setSellerName(wordsResultDTO.getSellerName());                      //销售方名称




            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityTaxRate = new ArrayList<>();    //税率
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityTaxRate())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityTaxRateDTO commodityTaxRateDTO : wordsResultDTO.getCommodityTaxRate()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityTaxRateDTO.getRow());
                    commodityDTO.setWord(commodityTaxRateDTO.getWord());
                    commodityTaxRate.add(commodityDTO);
                }
            }
            resp.setCommodityTaxRate(commodityTaxRate);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityExpenseItem = new ArrayList<>();                //费用项目。货运专票返回信息，其他类型发票可忽略
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityExpenseItem())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityExpenseItemDTO commodityExpenseItemDTO : wordsResultDTO.getCommodityExpenseItem()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityExpenseItemDTO.getRow());
                    commodityDTO.setWord(commodityExpenseItemDTO.getWord());
                    commodityExpenseItem.add(commodityDTO);
                }
            }
            resp.setCommodityExpenseItem(commodityExpenseItem);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityNum  = new ArrayList<>();    //数量
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityNum())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityNumDTO commodityNumDTO : wordsResultDTO.getCommodityNum()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityNumDTO.getRow());
                    commodityDTO.setWord(commodityNumDTO.getWord());
                    commodityNum.add(commodityDTO);
                }
            }
            resp.setCommodityNum(commodityNum);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityAmount= new ArrayList<>();     //金额

            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityAmount())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityAmountDTO commodityAmountDTO : wordsResultDTO.getCommodityAmount()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityAmountDTO.getRow());
                    commodityDTO.setWord(commodityAmountDTO.getWord());
                    commodityAmount.add(commodityDTO);
                }
            }
            resp.setCommodityAmount(commodityAmount);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityType = new ArrayList<>();           //规格型号
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityType())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityTypeDTO commodityTypeDTO : wordsResultDTO.getCommodityType()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityTypeDTO.getRow());
                    commodityDTO.setWord(commodityTypeDTO.getWord());
                    commodityType.add(commodityDTO);
                }
            }
            resp.setCommodityType(commodityType);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityTax = new ArrayList<>();        //税额
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityTax())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityTaxDTO tax : wordsResultDTO.getCommodityTax()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(tax.getRow());
                    commodityDTO.setWord(tax.getWord());
                    commodityTax.add(commodityDTO);
                }
            }
            resp.setCommodityTax(commodityTax);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityPlateNum= new ArrayList<>();           //车牌号。通行费增值税电子普通发票返回信息，其他类型发票可忽略
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityPlateNum())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityPlateNumDTO commodityPlateNumDTO : wordsResultDTO.getCommodityPlateNum()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityPlateNumDTO.getRow());
                    commodityDTO.setWord(commodityPlateNumDTO.getWord());
                    commodityPlateNum.add(commodityDTO);
                }
            }
            resp.setCommodityPlateNum(commodityPlateNum);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityUnit = new ArrayList<>();       //	单位
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityUnit())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityUnitDTO commodityUnitDTO : wordsResultDTO.getCommodityUnit()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityUnitDTO.getRow());
                    commodityDTO.setWord(commodityUnitDTO.getWord());
                    commodityUnit.add(commodityDTO);

                }
            }
            resp.setCommodityUnit(commodityUnit);

            List<CommonVatInvoiceVerificationResp.CommodityDTO> commodityName = new ArrayList<>();           //	货物名称/项目名称
            if(CollectionUtils.isNotEmpty(wordsResultDTO.getCommodityName())){
                for (BCommonVatInvoiceVerificationResp.WordsResultDTO.CommodityNameDTO commodityNameDTO : wordsResultDTO.getCommodityName()) {
                    CommonVatInvoiceVerificationResp.CommodityDTO commodityDTO = new CommonVatInvoiceVerificationResp.CommodityDTO();
                    commodityDTO.setRow(commodityNameDTO.getRow());
                    commodityDTO.setWord(commodityNameDTO.getWord());
                    commodityName.add(commodityDTO);


                }
            }
            resp.setCommodityName(commodityName);
        }


        return R.ok();
    }


}
