package com.trade.client.trade.exportrebate.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.trade.client.enterprise.customer.domain.CustomerUser;
import com.trade.client.enterprise.customer.service.CustomerUserService;
import com.trade.client.security.utils.UserUtils;
import com.trade.client.trade.exportrebate.dto.ExportDetailDto;
import com.trade.client.trade.exportrebate.dto.ExportTaxRebateDetailsDto;
import com.trade.client.trade.exportrebate.dto.PurchaseDetailDto;
import com.trade.client.trade.exportrebate.service.ExportTaxRebateService;
import com.trade.common.constant.HttpStatus;
import com.trade.common.core.page.GridPage;
import com.trade.common.exception.ServiceException;
import com.trade.service.DictConstants;
import com.trade.service.enterprise.companyrelated.domain.ImporterEntity;
import com.trade.service.enterprise.companyrelated.service.IImporterEntityService;
import com.trade.service.enterprise.customer.domain.Enterprise;
import com.trade.service.enterprise.customer.service.EnterpriseBaseService;
import com.trade.service.filestorage.dto.FileAbstractDto;
import com.trade.service.filestorage.service.TFileStorageService;
import com.trade.service.thirdparty.xiaotu.service.XiaotuRequestService;
import com.trade.service.trade.exportrebate.domain.TaxRebateExportDetails;
import com.trade.service.trade.exportrebate.dto.ExportTaxRebateStatisticDto;
import com.trade.service.trade.exportrebate.dto.TaxRebatePurchaseAbstractInfo;
import com.trade.service.trade.exportrebate.dto.search.ExportTaxRebateDetailsForCSearchDto;
import com.trade.service.trade.exportrebate.dto.search.TaxRebateSearchDto;
import com.trade.service.trade.exportrebate.service.TaxRebateExportDetailsBaseService;
import com.trade.service.trade.exportrebate.service.TaxRebatePurchaseDetailsBaseService;
import com.trade.service.trade.salesorder.domain.CustomsDeclarationFile;
import com.trade.service.trade.salesorder.service.ICustomsDeclarationFileService;
import com.trade.service.tradingplatform.domain.TradingPlatform;
import com.trade.service.tradingplatform.service.TradingPlatformBaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 出出口退税接口实现类
 *
 * @author hlb
 * @since 2024-10-22 15:46:16
 */
@Service("exportTaxRebateService")
public class ExportTaxRebateServiceImpl implements ExportTaxRebateService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExportTaxRebateServiceImpl.class);
    @Resource
    private TaxRebateExportDetailsBaseService taxRebateExportDetailsBaseService;
    @Resource
    private EnterpriseBaseService enterpriseBaseService;
    @Resource
    private XiaotuRequestService xiaotuRequestService;
    @Autowired
    private CustomerUserService customerUserService;
    @Autowired
    private TradingPlatformBaseService tradingPlatformBaseService;
    @Autowired
    private IImporterEntityService importerEntityService;
    @Autowired
    private ICustomsDeclarationFileService customsDeclarationFileService;
    @Resource
    private TFileStorageService tFileStorageService;
    @Resource
    private TaxRebatePurchaseDetailsBaseService taxRebatePurchaseDetailsBaseService;

    @Override
    public GridPage<ExportTaxRebateStatisticDto> getPagesBySearch(TaxRebateSearchDto search) {
        Long customerUserId = UserUtils.getCustomerUserId();
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(customerUserId);
        if (enterprise == null) {
            throw new ServiceException("用户没有企业认证", HttpStatus.BAD_REQUEST);
        }
        // “生产型”自营出口客户，无“申报批次”；“所属期”即“申报年月”；无“退税额”，有“免抵退税额”
        if (DictConstants.EXPORT_TYPE_SELF.equals(enterprise.getExportType())
                && (DictConstants.ENTERPRISE_TYPE_PRODUCE.equals(enterprise.getEnterpriseType())
                        || DictConstants.ENTERPRISE_TYPE_PRODUCE_EXTERNAL.equals(enterprise.getEnterpriseType()))) {
            search.setHasDeclarationBatch(false);
        }
        search.setCustomerUserId(customerUserId);
        return taxRebateExportDetailsBaseService.getPagesBySearch(search);
    }

    @Override
    public ExportTaxRebateDetailsDto getDetails(ExportTaxRebateDetailsForCSearchDto search) {
        Long customerUserId = UserUtils.getCustomerUserId();
        search.setCustomerUserId(customerUserId);
        if (StrUtil.isEmpty(search.getSalesOrderNo())) {
            throw new ServiceException("销售订单ID不能为空", HttpStatus.BAD_REQUEST);
        }
        if (StrUtil.isEmpty(search.getDeclarationMonthYear())) {
            throw new ServiceException("申报年月（所属期）不能为空", HttpStatus.BAD_REQUEST);
        }
        if (StrUtil.isEmpty(search.getDeclarationBatch())) {
            throw new ServiceException("申报批次不能为空", HttpStatus.BAD_REQUEST);
        }
        if (StrUtil.isEmpty(search.getCustomsDeclarationNo())) {
            throw new ServiceException("海关报关单号不能为空", HttpStatus.BAD_REQUEST);
        }
        if (StrUtil.isEmpty(search.getProformaInvoiceNo())) {
            throw new ServiceException("出口发票号不能为空", HttpStatus.BAD_REQUEST);
        }
        if (null == search.getExportDate()) {
            throw new ServiceException("出口日期不能为空", HttpStatus.BAD_REQUEST);
        }
        if (StrUtil.isEmpty(search.getStatus())) {
            throw new ServiceException("退税状态不能为空", HttpStatus.BAD_REQUEST);
        }
        List<TaxRebateExportDetails> taxRebateExportDetailsList = taxRebateExportDetailsBaseService
                .getDetailsByCSearch(search);
        if (CollUtil.isEmpty(taxRebateExportDetailsList)) {
            throw new ServiceException("未查询到相关退税详情信息", HttpStatus.BAD_REQUEST);
        }
        ExportTaxRebateDetailsDto exportTaxRebateDetailsDto = new ExportTaxRebateDetailsDto(taxRebateExportDetailsList);
        // 补充贸易平台名称
        if (StrUtil.isNotEmpty(exportTaxRebateDetailsDto.getAgencyCertNo())) {
            TradingPlatform tradingPlatform = tradingPlatformBaseService
                    .findByCertNo(exportTaxRebateDetailsDto.getAgencyCertNo());
            exportTaxRebateDetailsDto.setAgencyName(tradingPlatform == null ? "" : tradingPlatform.getPlatformName());
        }
        // 补充进口商名称
        if (StrUtil.isNotEmpty(exportTaxRebateDetailsDto.getImporterCertNo())) {
            ImporterEntity importerEntity = importerEntityService
                    .getByCertNo(exportTaxRebateDetailsDto.getImporterCertNo());
            exportTaxRebateDetailsDto.setImporterName(importerEntity == null ? "" : importerEntity.getEntityName());
        }
        // 补充报关单文件信息
        if (StrUtil.isNotEmpty(exportTaxRebateDetailsDto.getCustomsDeclarationNo())) {
            CustomsDeclarationFile customsDeclarationFile = customsDeclarationFileService
                    .getByCustomsNo(exportTaxRebateDetailsDto.getCustomsDeclarationNo());
            exportTaxRebateDetailsDto.setCustomsDeclarationFile(customsDeclarationFile == null ? null
                    : new FileAbstractDto(
                            tFileStorageService.getFileStorageById(customsDeclarationFile.getCustomsFileId())));
        }
        // 出口退税详情
        List<ExportDetailDto> exportDetailList = taxRebateExportDetailsList.stream().map(ExportDetailDto::new)
                .collect(Collectors.toList());
        exportTaxRebateDetailsDto.setExportDetailList(exportDetailList);
        List<Long> exportDetailIds = taxRebateExportDetailsList.stream().map(TaxRebateExportDetails::getId).distinct()
                .collect(Collectors.toList());
        List<TaxRebatePurchaseAbstractInfo> purchaseDetailsList = taxRebatePurchaseDetailsBaseService
                .getByExportDetailIds(exportDetailIds);
        if (CollUtil.isEmpty(purchaseDetailsList)) {
            return exportTaxRebateDetailsDto;
        }
        // 进货明细
        List<PurchaseDetailDto> purchaseDetailList = purchaseDetailsList.stream().map(PurchaseDetailDto::new)
                .collect(Collectors.toList());
        exportTaxRebateDetailsDto.setPurchaseDetailList(purchaseDetailList);
        long purchaseInvoiceCount = purchaseDetailsList.stream()
                .map(TaxRebatePurchaseAbstractInfo::getPurchaseVoucherNo).filter(StrUtil::isNotEmpty).distinct()
                .count();
        exportTaxRebateDetailsDto.setPurchaseInvoiceCount(purchaseInvoiceCount);
        return exportTaxRebateDetailsDto;
    }

    @Override
    public String getTaxRebateUrl() {
        CustomerUser customerUser = UserUtils.getLoginUser().getCustomerUser();
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(customerUser.getId());
        if (enterprise == null) {
            throw new ServiceException("用户没有企业认证", HttpStatus.BAD_REQUEST);
        }
        if (!DictConstants.CONTRACT_STATUS_DONE.equals(enterprise.getTaxRebateAgreementSignStatus())
                || !DictConstants.EXPORT_TYPE_SELF.equals(enterprise.getExportType())) {
            throw new ServiceException("无退税操作权限", HttpStatus.BAD_REQUEST);
        }
        return getXiaotuUrl("/02/0202/020204");
    }

    @Override
    public String getDownloadCustomsDeclarationUrl() {
        return getXiaotuUrl("/02/0202/020201");
    }

    @Override
    public String getDownloadPurchaseInvoiceUrl() {
        return getXiaotuUrl("/02/0202/020203");
    }

    private String getXiaotuUrl(String jumpUrl) {
        CustomerUser customerUser = UserUtils.getLoginUser().getCustomerUser();
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(customerUser.getId());
        if (enterprise == null) {
            throw new ServiceException("用户没有企业认证", HttpStatus.BAD_REQUEST);
        }
        if (StrUtil.isEmpty(enterprise.getXtEid()) || StrUtil.isEmpty(customerUser.getXtUid())) {
            throw new ServiceException("用户没有退税认证", HttpStatus.BAD_REQUEST);
        }
        return xiaotuRequestService.getExportRebateUrl(customerUser.getXtUid(), enterprise.getXtEid(), jumpUrl);
    }
}
