package com.jwipc.finance.logic.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.finance.dto.InvoicedApplyPostApiDTO;
import com.jwipc.finance.entity.InvoicedApply;
import com.jwipc.finance.entity.InvoicedApplyPostResult;
import com.jwipc.finance.logic.InvoicedApplyLogic;
import com.jwipc.finance.logic.InvoicedApplyPostApiLogic;
import com.jwipc.finance.service.IInvoicedApplyPostResultService;
import com.jwipc.finance.service.IInvoicedApplyService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shenyang.ou
 * @date 2024/3/27 9:45
 * @desc
 */
@Service
@RequiredArgsConstructor
public class InvoicedApplyPostApiLogicImpl implements InvoicedApplyPostApiLogic {

    private final IInvoicedApplyPostResultService invoicedApplyPostResultService;
    private final InvoicedApplyLogic invoicedApplyLogic;
    private final IInvoicedApplyService iInvoicedApplyService;
    @Override
    public ApiResult sync(InvoicedApplyPostApiDTO param) {
        List<InvoicedApplyPostApiDTO.Item> items =  param.getItems();
        for (InvoicedApplyPostApiDTO.Item dto : items){
            //对账单号
            String zzjsd = dto.getZZJSD();
            //sap发票凭证
            String belnr = dto.getBELNR();
            //凭证年度
            String gjahr = dto.getGJAHR();
            //凭证状态
            String rbstat = dto.getRBSTAT();
            //付款到期日
            String zfbdt = dto.getZFBDT();
            if (StringUtils.isEmpty(zzjsd)) {
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入对账单号").build();
            }
            if (StringUtils.isEmpty(rbstat)) {
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入过账标识").build();
            }
            int dataStatus;
            if("5".equals(rbstat)) {
                if (StringUtils.isEmpty(belnr)) {
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入发票凭证编号").build();
                }
                if (StringUtils.isEmpty(gjahr)) {
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入凭证年度").build();
                }
                // 已过帐
                dataStatus = 3;
            }else if("X".equals(rbstat) || "2".equals(rbstat)) {
                // 冲销 删除
                dataStatus = 1;
            }else if("3".equals(rbstat)) {
                // 冲销 删除
                dataStatus = 2;
            }else {
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入正确的过账标识").build();
            }
            InvoicedApply invoicedApply = iInvoicedApplyService.getOne(Wrappers.lambdaQuery(InvoicedApply.class).eq(InvoicedApply::getAccountStatementNo,zzjsd).eq(InvoicedApply::getDeleteFlag,0).last(" limit 1"));
            if (ObjectUtil.isNull(invoicedApply)) {
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("对账单号：{}在系统中不存在",zzjsd)).build();
            }

            InvoicedApplyPostResult invoicedApplyPostResult = invoicedApplyPostResultService.getOne(Wrappers.lambdaQuery(InvoicedApplyPostResult.class).eq(InvoicedApplyPostResult::getInvoiceApplyId,invoicedApply.getId()).last(" limit 1"));

            try {
                List<Long> idList = ListUtil.list(false,invoicedApply.getId());
                if (dataStatus == 1) {
                    // 'invoiceVoucher' 'SAP发票凭证号', voucherYear', : '发票年度', invoicePostDate', '过账时间',
                    // paymentExpireDate', '付款到期日',
                    //冲销时清空   SAP冲销发票时，要清空 SAP发票凭证号、发票年度、过账时间、付款到期日 2024-08-21 邓京术 账务需求
                    // 已过帐时
//                    invoicedApplyPostResult.setInvoiceVoucher(StrUtil.isEmpty(belnr)?"":belnr);
//                    invoicedApplyPostResult.setVoucherYear(StrUtil.isEmpty(gjahr)?"":gjahr);
                    invoicedApplyPostResult.setPaymentExpireDate(null);
                    invoicedApplyPostResult.setInvoicePostDate(null);
                    //字符串 传null 不会作更新操作。
                    invoicedApplyPostResult.setInvoiceVoucher("");
                    invoicedApplyPostResult.setVoucherYear("");
                    invoicedApplyPostResultService.updateById(invoicedApplyPostResult);
//                    if ("X".equals(rbstat)){
//                        invoicedApplyLogic.dataDel(JSON.toJSONString(idList),true);
//                    }
                    invoicedApply.setPostStatus(7);
                    iInvoicedApplyService.updateById(invoicedApply);
                }
                if (dataStatus == 2) {
                    // 已过帐时
                    invoicedApply.setPostStatus(3);
                    iInvoicedApplyService.updateById(invoicedApply);
                    invoicedApplyPostResult.setDataStatus(1);
                    invoicedApplyPostResult.setSyncMessage(dto.getREMARK());
                    invoicedApplyPostResultService.updateById(invoicedApplyPostResult);
                }
                if (dataStatus == 3) {
                    invoicedApplyPostResult.setDataStatus(dataStatus);
                    invoicedApplyPostResult.setInvoiceVoucher(belnr);
                    invoicedApplyPostResult.setVoucherYear(gjahr);
                    if (StrUtil.isNotEmpty(zfbdt)){
                        try {
                            invoicedApplyPostResult.setPaymentExpireDate(LocalDateTimeUtil.parse(zfbdt,"yyyyMMdd"));
                        }catch (Exception e){
                            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请输入正确的付款到期日，格式yyyyMMdd").build();
                        }
                    }
                    invoicedApplyPostResult.setDataStatus(dataStatus);
                    invoicedApplyPostResult.setInvoicePostDate(LocalDateTime.now());
                    invoicedApplyPostResultService.updateById(invoicedApplyPostResult);
                    // 已过帐时
                    invoicedApply.setPostStatus(5);
                    iInvoicedApplyService.updateById(invoicedApply);
                }
            }catch (Exception e){
                e.printStackTrace();
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(e.getMessage()).build();
            }

        }
        return ApiResult.builder().code(RestCode.SAP_SUCCESS.getCode()).message("成功").build();
    }
}
