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.dto.PaymentPostApiDTO;
import com.jwipc.finance.entity.*;
import com.jwipc.finance.logic.*;
import com.jwipc.finance.service.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

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

    private final PaymentMatchingLogic paymentMatchingLogic;
    private final IPaymentMatchingService PaymentMatchingService;
    private final CostMatchingLogic costMatchingLogic;
    private final ICostMatchingService costMatchingService;
    private final ICostInvoicedApplyService costInvoicedApplyService;
    private final ICostInvoicedApplyPostResultService costInvoicedApplyPostResultService;
    private final CostInvoicedApplyLogic costInvoicedApplyLogic;
    @Override
    public ApiResult sync(PaymentPostApiDTO param) {
        List<PaymentPostApiDTO.Item> items =  param.getItems();
        for (PaymentPostApiDTO.Item dto : items){
            //业务类型 01-货款、02-费用
            String ywlx = dto.getYWLX();
            //对账单号
            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();
            }


            try {
                if (ywlx.equals("01")){
                    PaymentMatching paymentMatching = PaymentMatchingService.getOne(Wrappers.lambdaQuery(PaymentMatching.class).eq(PaymentMatching::getCode,zzjsd).eq(PaymentMatching::getDeleteFlag,0).last(" limit 1"));
                    if (ObjectUtil.isNull(paymentMatching)) {
                        return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("货款匹配单号：{}在系统中不存在",zzjsd)).build();
                    }

                    List<Long> idList = ListUtil.list(false,paymentMatching.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);
                        paymentMatching.setPaymentExpireDate(null);
                        paymentMatching.setInvoicePostDate(null);
                        //字符串 传null 不会作更新操作。
                        paymentMatching.setInvoiceVoucher("");
                        paymentMatching.setVoucherYear("");
                        paymentMatchingLogic.dataDel(JSON.toJSONString(idList),true);
                        paymentMatching.setPostStatus(7);
                        PaymentMatchingService.updateById(paymentMatching);
                    }
                    if (dataStatus == 2) {
                        // 已过帐时
                        paymentMatching.setPostStatus(3);
                        paymentMatching.setPostMsg(dto.getREMARK());
                        PaymentMatchingService.updateById(paymentMatching);
                    }
                    if (dataStatus == 3) {
                        paymentMatching.setInvoiceVoucher(belnr);
                        paymentMatching.setVoucherYear(gjahr);
                        if (StrUtil.isNotEmpty(zfbdt)){
                            try {
                                paymentMatching.setPaymentExpireDate(LocalDateTimeUtil.parse(zfbdt,"yyyyMMdd"));
                            }catch (Exception e){
                                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请输入正确的付款到期日，格式yyyyMMdd").build();
                            }
                        }else {
                            LocalDate date = LocalDate.now();
                            LocalDate fixedDate = date.withDayOfMonth(20);
                            paymentMatching.setPaymentExpireDate(fixedDate.atStartOfDay());
                        }
                        paymentMatching.setInvoicePostDate(LocalDateTime.now());
                        // 已过帐时
                        paymentMatching.setPostStatus(5);
                        PaymentMatchingService.updateById(paymentMatching);
                    }
                }else if (ywlx.equals("02")){
                    CostMatching costMatching = costMatchingService.getOne(Wrappers.lambdaQuery(CostMatching.class).eq(CostMatching::getCode,zzjsd).eq(CostMatching::getDeleteFlag,0).last(" limit 1"));
                    if (ObjectUtil.isNull(costMatching)) {
                        return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("费用匹配单号：{}在系统中不存在",zzjsd)).build();
                    }

                    List<Long> idList = ListUtil.list(false,costMatching.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);
                        costMatching.setPaymentExpireDate(null);
                        costMatching.setInvoicePostDate(null);
                        //字符串 传null 不会作更新操作。
                        costMatching.setInvoiceVoucher("");
                        costMatching.setVoucherYear("");
//                        costMatchingLogic.dataDel(JSON.toJSONString(idList),true);
                        costMatching.setPostStatus(7);
                        costMatchingService.updateById(costMatching);
                    }
                    if (dataStatus == 2) {
                        // 已过帐时
                        costMatching.setPostStatus(3);
                        costMatching.setPostMsg(dto.getREMARK());
                        costMatchingService.updateById(costMatching);
                    }
                    if (dataStatus == 3) {
                        costMatching.setInvoiceVoucher(belnr);
                        costMatching.setVoucherYear(gjahr);
                        if (StrUtil.isNotEmpty(zfbdt)){
                            try {
                                costMatching.setPaymentExpireDate(LocalDateTimeUtil.parse(zfbdt,"yyyyMMdd"));
                            }catch (Exception e){
                                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请输入正确的付款到期日，格式yyyyMMdd").build();
                            }
                        }
                        costMatching.setInvoicePostDate(LocalDateTime.now());
                        // 已过帐时
                        costMatching.setPostStatus(5);
                        costMatchingService.updateById(costMatching);
                    }
                }else {
                    CostInvoicedApply invoicedApply = costInvoicedApplyService.getOne(Wrappers.lambdaQuery(CostInvoicedApply.class).eq(CostInvoicedApply::getInvoiceApplyNo,zzjsd).eq(CostInvoicedApply::getDeleteFlag,0).last(" limit 1"));
                    if (ObjectUtil.isNull(invoicedApply)) {
                        return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("费用开票申请单号：{}在系统中不存在",zzjsd)).build();
                    }

                    CostInvoicedApplyPostResult invoicedApplyPostResult = costInvoicedApplyPostResultService.getOne(Wrappers.lambdaQuery(CostInvoicedApplyPostResult.class).eq(CostInvoicedApplyPostResult::getInvoiceApplyId,invoicedApply.getId()).last(" limit 1"));
                    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("");
                        costInvoicedApplyPostResultService.updateById(invoicedApplyPostResult);
                        costInvoicedApplyLogic.dataDel(JSON.toJSONString(idList),true);
                        invoicedApply.setPostStatus(7);
                        costInvoicedApplyService.updateById(invoicedApply);
                    }
                    if (dataStatus == 2) {
                        // 已过帐时
                        invoicedApply.setPostStatus(3);
                        costInvoicedApplyService.updateById(invoicedApply);
                        invoicedApplyPostResult.setDataStatus(1);
                        invoicedApplyPostResult.setSyncMessage(dto.getREMARK());
                        costInvoicedApplyPostResultService.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();
                            }
                        }else {

                            LocalDate date = LocalDate.now();
                            LocalDate fixedDate = date.withDayOfMonth(20);
                            invoicedApplyPostResult.setPaymentExpireDate(fixedDate.atStartOfDay());
                        }
                        invoicedApplyPostResult.setDataStatus(dataStatus);
                        invoicedApplyPostResult.setInvoicePostDate(LocalDateTime.now());
                        costInvoicedApplyPostResultService.updateById(invoicedApplyPostResult);
                        // 已过帐时
                        invoicedApply.setPostStatus(5);
                        costInvoicedApplyService.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();
    }
}
