package com.jwipc.finance.logic.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.api.dto.SapReposeCostDTO;
import com.jwipc.api.dto.SapResposeBody;
import com.jwipc.exception.DaoException;
import com.jwipc.finance.constant.AccountStatementSapClient;
import com.jwipc.finance.dto.AccountStatementToSapDTO;
import com.jwipc.finance.dto.CostAccountStatementToSapDTO;
import com.jwipc.finance.dto.PaymentToSapDTO;
import com.jwipc.finance.entity.*;
import com.jwipc.finance.logic.CostInvoicedApplyDetailLogic;
import com.jwipc.finance.model.po.StatementItemPO;
import com.jwipc.finance.service.*;
import com.jwipc.security.LoginUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * @author shenyang.ou
 * @date 2025/11/11 15:08
 * @desc
 */
@Service
@RequiredArgsConstructor
public class CostInvoicedApplyDetailLogicImpl implements CostInvoicedApplyDetailLogic {
    private final ICostInvoicedApplyService costInvoicedApplyService;
    private final ICostAccountStatementService costAccountStatementService;
    private final ICostInvoicedApplyPostResultService costInvoicedApplyPostResultService;
    private final AccountStatementSapClient accountStatementSapClient;

    /**
     * 创建预制发票
     *
     * @param iaId            开票申请id
     * @param type            1:预制 2:删除
     * @param invoicePostDate 发票过账日期
     * @param statementType   过账类型
     */
    @Override
    public void createPrefabricateInvoice(Long iaId, Integer type, String invoicePostDate, String statementType) {
        CostInvoicedApply invoicedApply = costInvoicedApplyService.getById(iaId);
        CostAccountStatement costAccountStatement = costAccountStatementService.getById(invoicedApply.getAccountStatementId());
//        if (!Objects.equals(invoicedApply.getFinanceConfirmUserId(), LoginUtil.getUserId())) {
//            throw new DaoException("当前登录人员必须与财务复核人一致，才允许过账");
//        }
        //过账状态 1:暂存 2:待预制 3:预制失败 7:已冲销 2024-08-21 邓京术 财务要求 3和7的也允许过账
        if (ObjectUtil.isNotEmpty(invoicedApply)) {
            if (invoicedApply.getPostStatus() != 1 && invoicedApply.getPostStatus() != 2 && invoicedApply.getPostStatus() != 3 && invoicedApply.getPostStatus() != 7) {
                throw new DaoException(StrUtil.format("开票申请单:{}已过账，不允许再次过账", invoicedApply.getInvoiceApplyNo()));
            }
        }
        CostInvoicedApplyPostResult invoicedApplyPostResult = costInvoicedApplyPostResultService.getOne(Wrappers.lambdaQuery(CostInvoicedApplyPostResult.class).eq(CostInvoicedApplyPostResult::getInvoiceApplyId, invoicedApply.getId()).last(" limit 1"));


        //组装数据传入对账数据到sap接口
        final CostAccountStatementToSapDTO accountStatementToSapDTO = new CostAccountStatementToSapDTO();
        //头
        final CostAccountStatementToSapDTO.ItHead itHead = new CostAccountStatementToSapDTO.ItHead();
        itHead.item = Lists.newArrayList();
        CostAccountStatementToSapDTO.Head head = new CostAccountStatementToSapDTO.Head();
        // SRM费用-开票申请单
        head.setXBLNR(invoicedApply.getInvoiceApplyNo());
        LocalDateTime invoiceDate = LocalDateTimeUtil.parse(invoicePostDate, "yyyy-MM-dd");
        // 凭证中的凭证日期
        head.setBLDAT(invoicePostDate.replaceAll("-", ""));
        // 凭证类型
        head.setBLART("RE");
        // 业务类型
        head.setYWLX("03");
        // 公司代码
        head.setBUKRS(invoicedApply.getCompanyCode());
        // 凭证中的过帐日期
        head.setBUDAT(invoicePostDate.replaceAll("-", ""));
        // 会计期间
        head.setMONAT(LocalDateTimeUtil.format(invoiceDate, "MM"));
        // 凭证抬头文本
        head.setBKTXT(invoicedApply.getAccountStatementNo());
        // 货币码
        head.setWAERS(StrUtil.isNotEmpty(invoicedApply.getCurrencyCode()) ? invoicedApply.getCurrencyCode() : "CNY");
        // 总账科目：供应商
        head.setLIFNR(invoicedApply.getSupplierCode());
//        head.setLIFNR(invoicedApply.getSupplierCode());
        // 总账科目：应交税费-应交增值税-待认证进项-增值税专用发票内
        head.setWRBTR1(costAccountStatement.getDomesticTaxTotalAmount().stripTrailingZeros().toPlainString());
        // 总账科目：材料成本差异-原材料
        head.setWRBTR2(invoicedApply.getDiffAmountSap().stripTrailingZeros().toPlainString());
        // 项目文本
        head.setSGTXT(invoicedApply.getInvoiceNo());
        itHead.item.add(head);
        accountStatementToSapDTO.setIT_HEAD(itHead);
        SapResposeBody sapResposeBody = accountStatementSapClient.syncCostAccountStatement(accountStatementToSapDTO);
        if (sapResposeBody.getES_RET().getCODE().equals(RestCode.SAP_SUCCESS.getCode())) {
            List<SapReposeCostDTO.Item> item = sapResposeBody.getET_RETURN().getItem();
            invoicedApplyPostResult.setInvoiceVoucher(item.get(0).getBELNR());
            invoicedApplyPostResult.setVoucherYear(item.get(0).getGJAHR());
            if (StrUtil.isNotEmpty(item.get(0).getZFBDT())) {
                try {
                    invoicedApplyPostResult.setPaymentExpireDate(LocalDateTimeUtil.parse(item.get(0).getZFBDT(), "yyyyMMdd"));
                } catch (Exception e) {
//                    throw new DaoException("SAP返回的付款到期日不正确，" + item.get(0).getZFBDT());
                }
            }
            invoicedApplyPostResult.setSyncMessage("成功");
            invoicedApplyPostResult.setDataStatus(3);
            invoicedApplyPostResult.setInvoicePostDate(LocalDateTimeUtil.parse(invoicePostDate, "yyyy-MM-dd"));
            //invoicePostDate转成yyyy-MM-20
            // 解析原始字符串为 LocalDate
            LocalDate date = LocalDate.parse(invoicePostDate, DateTimeFormatter.ISO_LOCAL_DATE);
            // 修改为当月20号
            LocalDate fixedDate = date.withDayOfMonth(20);
            invoicedApplyPostResult.setPaymentExpireDate(fixedDate.atStartOfDay());
            invoicedApplyPostResult.setPostUserName(LoginUtil.getName());
            invoicedApplyPostResult.setPostUserId(LoginUtil.getUserId());
            invoicedApplyPostResult.setPostUserCode(LoginUtil.getAccount());
            invoicedApplyPostResult.setInvoicePostDate(LocalDateTime.now());
            costInvoicedApplyPostResultService.updateById(invoicedApplyPostResult);
            // 已过帐时
            invoicedApply.setPostStatus(5);
            costInvoicedApplyService.updateById(invoicedApply);
        } else {
            throw new DaoException("SAP接口报错：" + sapResposeBody.getES_RET().getMSG());
        }
    }
}
