package com.trade.client.accounts.payableaccounts.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.trade.client.accounts.payableaccounts.dto.PaymentConfirmDto;
import com.trade.client.accounts.payableaccounts.service.BPayableAccountsService;
import com.trade.client.accounts.payableaccounts.vo.PayableAccountsDetail;
import com.trade.client.enterprise.customer.domain.CustomerUser;
import com.trade.client.enterprise.customer.service.CustomerUserService;
import com.trade.common.constant.HttpStatus;
import com.trade.common.core.page.GridPage;
import com.trade.common.exception.ServiceException;
import com.trade.common.utils.ConstantUtil;
import com.trade.service.business.payableaccounts.domain.PayableAccounts;
import com.trade.service.business.payableaccounts.dto.PayableAccountsSearchDto;
import com.trade.service.business.payableaccounts.service.PayableAccountsService;
import com.trade.service.filestorage.entity.BusinessRelateFile;
import com.trade.service.filestorage.entity.TFileStorage;
import com.trade.service.filestorage.enums.FileTypeEnum;
import com.trade.service.filestorage.service.BusinessRelateFileBaseService;
import com.trade.service.filestorage.service.TFileStorageService;
import com.trade.service.finance.constant.BillingConstant;
import com.trade.service.finance.paymentcollection.service.BillingIncomeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * @description:
 * @Author: wanglang
 * @Date: 2024/11/5
 * @Version: 1.0
 */
@Service
public class BPayableAccountsServiceImpl implements BPayableAccountsService {

    @Resource
    private PayableAccountsService payableAccountsService;
    @Resource
    private CustomerUserService customerUserService;
    @Resource
    private TFileStorageService fileStorageService;
    @Resource
    private BusinessRelateFileBaseService businessRelateFileBaseService;
    @Resource
    private BillingIncomeService billingIncomeService;

    @Override
    public GridPage<PayableAccounts> queryListByPage(PayableAccountsSearchDto searchDto) {
        CustomerUser customerUser = customerUserService.getCustomerUser();
        searchDto.setCustomerUserId(customerUser.getId());
        Page<PayableAccounts> page = PageHelper.startPage(searchDto.getPage(), searchDto.getRows());
        List<PayableAccounts> voList = payableAccountsService.queryByPage(searchDto);
        for (PayableAccounts payableAccounts : voList) {
            if (BillingConstant.PAYMENT_STATUS_WAIT.equals(payableAccounts.getStatus())
                    && LocalDateTime.now().isAfter(payableAccounts.getPaymentDeadline())) {
                payableAccounts.setStatus(BillingConstant.PAYMENT_STATUS_UNPAID);
                payableAccountsService.updateById(payableAccounts);
            }
        }
        return new GridPage<>(searchDto.getPage(), searchDto.getRows(), page.getTotal(), voList);
    }

    @Override
    public Boolean submitPaymentConfirm(PaymentConfirmDto paymentConfirmDto) {
        PayableAccounts payableAccounts = payableAccountsService.getById(paymentConfirmDto.getId());
        if (payableAccounts == null) {
            throw new ServiceException("该应付账款记录不存在");
        }
        if (!BillingConstant.PAYMENT_STATUS_WAIT.equals(payableAccounts.getStatus())) {
            throw new ServiceException("仅待支付状态的记录可以付款");
        }
        payableAccounts.setPaymentTime(paymentConfirmDto.getPaymentTime());
        payableAccounts.setVoucherNo(paymentConfirmDto.getVoucherNo());
        payableAccounts.setStatus(BillingConstant.PAYMENT_STATUS_PAID);
        // 附件信息
        TFileStorage fileStorage = fileStorageService.getFileStorageById(paymentConfirmDto.getFileId());
        if (fileStorage == null) {
            throw new ServiceException("文件不存在（文件id：" + paymentConfirmDto.getFileId() + "）", HttpStatus.BAD_REQUEST);
        }
        BusinessRelateFile businessRelateFile = new BusinessRelateFile();
        businessRelateFile.setFileId(paymentConfirmDto.getFileId());
        businessRelateFile.setBelongId(payableAccounts.getId());
        businessRelateFile.setBelongType(BillingConstant.PAYMENT_VOUCHER);
        businessRelateFile.setFileType(FileTypeEnum.PAYABLE_ACCOUNTS.getCode());
        businessRelateFileBaseService.addBusinessRelateFiles(Collections.singletonList(businessRelateFile));
        // 生成入账信息
        Long billingIncomeId = billingIncomeService.savePayableAccountsIncome(payableAccounts);
        payableAccounts.setBillingIncomeId(billingIncomeId);
        payableAccountsService.updateById(payableAccounts);
        return true;
    }

    @Override
    public PayableAccountsDetail queryDetail(Long id) {
        PayableAccounts payableAccounts = payableAccountsService.getById(id);
        if (payableAccounts == null) {
            throw new ServiceException("该应付账款记录不存在");
        }
        PayableAccountsDetail payableAccountsDetail = new PayableAccountsDetail();
        businessRelateFileBaseService.fillBizObjFiles(payableAccountsDetail, payableAccounts.getId(),
                BillingConstant.PAYMENT_VOUCHER, FileTypeEnum.PAYABLE_ACCOUNTS.getCode());
        payableAccountsDetail.setPayableAccountInfo(payableAccounts);
        return payableAccountsDetail;
    }
}
