/**
 * @filename:SalesCommodityServiceImpl 2024-09-03
 * @project KJT v1.0.0 Copyright(c) 2024 wanglang Co. Ltd. All right reserved.
 */
package com.trade.service.trade.salescontract.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trade.service.enterprise.customer.domain.Enterprise;
import com.trade.service.enterprise.customer.service.EnterpriseBaseService;
import com.trade.service.trade.salescontract.domain.SalesCommodity;
import com.trade.service.trade.salescontract.dto.SalesCommodityDto;
import com.trade.service.trade.salescontract.dto.SalesCommoditySpidDto;
import com.trade.service.trade.salescontract.mapper.SalesCommodityMapper;
import com.trade.service.trade.salescontract.service.SalesCommodityService;
import com.trade.service.trade.salescontract.vo.SalesCommoditySearch;
import com.trade.common.exception.ServiceException;
import com.trade.common.utils.StringUtils;
import com.trade.service.DictConstants;
import com.trade.service.system.service.SuperviseCertificateCodeService;
import com.trade.service.thirdparty.xiaotu.dto.BusinessCommonRequest;
import com.trade.service.thirdparty.xiaotu.dto.CommodityCustomsTariffRespose;
import com.trade.service.thirdparty.xiaotu.dto.CommodityRequest;
import com.trade.service.thirdparty.xiaotu.dto.CommodityResponse;
import com.trade.service.thirdparty.xiaotu.service.XiaotuRequestService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:销售商品服务实现
 * @version: v1.0.0
 * @author: wanglang
 */
@Service
public class SalesCommodityServiceImpl extends ServiceImpl<SalesCommodityMapper, SalesCommodity> implements SalesCommodityService {

    @Resource
    private XiaotuRequestService xiaotuRequestService;
    @Resource
    private EnterpriseBaseService enterpriseBaseService;
    @Resource
    private SuperviseCertificateCodeService superviseCertificateCodeService;

    @Override
    public List<SalesCommodity> queryBySalesContractId(Long salesContractId) {
        return this.baseMapper.selectBySalesContractId(salesContractId);
    }

    @Override
    public PageInfo<SalesCommodity> getContractCommodityList(SalesCommoditySearch search) {
        PageHelper.startPage(search.getPage(), search.getRows());
        QueryWrapper<SalesCommodity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sales_contract_id", search.getSalesContractId());
        if (null != search.getName()) {
            queryWrapper.like("name", search.getName());
        }
        return new PageInfo<>(this.list(queryWrapper));
    }

    @Override
    public List<SalesCommodityDto> getXiaoTuCommodityList(String name, String xtUid, Long customerId,
            boolean isImport) {
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(customerId);
        CommodityRequest commodityRequest = new CommodityRequest();
        if (!isImport) {
            commodityRequest.setCksptssplxDm(CommodityRequest.OTHER);
        }
        commodityRequest.setCkspdm(name);
        BusinessCommonRequest businessCommonRequest = new BusinessCommonRequest();
        businessCommonRequest.setXtUid(xtUid);
        businessCommonRequest.setCustomerId(customerId);
        businessCommonRequest.setXtEid(enterprise.getXtEid());
        List<CommodityResponse> commodityResponses;
        try {
            commodityResponses = xiaotuRequestService.taxRefundRateInquiry(commodityRequest, businessCommonRequest)
                    .stream().filter(c -> "Y".equals(c.getJbspbz())).collect(Collectors.toList());
        } catch (Exception e) {
            if (isImport) {
                return null;
            } else {
                throw new ServiceException("未检索到商品信息");
            }
        }
        if (commodityResponses == null || CollectionUtil.isEmpty(commodityResponses)) {
            if (isImport) {
                return null;
            } else {
                throw new ServiceException("未检索到商品信息");
            }
        }
        List<SalesCommodityDto> salesCommodityDtos = new ArrayList<>();
        for (CommodityResponse commodityResponse : commodityResponses) {
            if (commodityResponse == null || StringUtils.isEmpty(commodityResponse.getSpid())) {
                continue;
            }
            List<CommodityCustomsTariffRespose> commodityCustomsTariffResposes = xiaotuRequestService
                    .commodityCustomsTariffInquiry(commodityResponse.getSpid(), businessCommonRequest);
            for (CommodityCustomsTariffRespose commodityCustomsTariffRespose : commodityCustomsTariffResposes) {
                for (CommodityCustomsTariffRespose.Spmhgszinfo spmhgszinfo : commodityCustomsTariffRespose
                        .getSPMHGSZINFO()) {
                    SalesCommodityDto salesCommodityDto = new SalesCommodityDto();
                    salesCommodityDto.setHsCode(spmhgszinfo.getHSCODE());
                    salesCommodityDto.setName(spmhgszinfo.getHSNAME());
                    salesCommodityDto.setMeasurementUnit(commodityCustomsTariffRespose.getHGJLDWMC());
                    if (StringUtils.isNotEmpty(commodityCustomsTariffRespose.getTSL())) {
                        salesCommodityDto.setExportTaxRebateRate(new BigDecimal(commodityCustomsTariffRespose.getTSL())
                                .divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP).toString());
                    }
                    String zssljh = commodityCustomsTariffRespose.getZSSLJH();
                    if (zssljh.contains(",")) {
                        zssljh = zssljh.split(",")[0];
                    }
                    salesCommodityDto.setAddedTaxRate(
                            new BigDecimal(zssljh).divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP).toString());
                    if (isImport) {
                        if (commodityRequest.PROHIBITION_EXPORT
                                .equals(commodityCustomsTariffRespose.getCKSPTSSPLX_DM())) {
                            salesCommodityDto.setErrorsValidator("该商品禁止出口");
                        }
                        if (commodityRequest.TAX_FREE.equals(commodityCustomsTariffRespose.getCKSPTSSPLX_DM())) {
                            salesCommodityDto.setErrorsValidator("该商品为免税商品");
                        }
                    }
                    if (DictConstants.EXPORT_TYPE_PROXY.equals(enterprise.getExportType())) {
                        Long count = superviseCertificateCodeService.countByCode(spmhgszinfo.getHSHGJGTJ());
                        if (count != null && count > 0) {
                            salesCommodityDto.setErrorsValidator("该商品为监管商品");
                        }
                    }
                    if (!isImport && StringUtils.isEmpty(salesCommodityDto.getErrors())) {
                        salesCommodityDtos.add(salesCommodityDto);
                    } else {
                        salesCommodityDtos.add(salesCommodityDto);
                    }
                }
            }
        }
        return salesCommodityDtos;
    }

    @Override
    public List<SalesCommodityDto> getXiaoTuCommodityList(String spid, String xtUid, Long customerId) {
        List<SalesCommodityDto> salesCommodityDtos = new ArrayList<>();
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(customerId);
        BusinessCommonRequest businessCommonRequest = new BusinessCommonRequest();
        businessCommonRequest.setXtUid(xtUid);
        businessCommonRequest.setCustomerId(customerId);
        businessCommonRequest.setXtEid(enterprise.getXtEid());
        List<CommodityCustomsTariffRespose> commodityCustomsTariffResposes = xiaotuRequestService
                .commodityCustomsTariffInquiry(spid, businessCommonRequest);
        for (CommodityCustomsTariffRespose commodityCustomsTariffRespose : commodityCustomsTariffResposes) {
            for (CommodityCustomsTariffRespose.Spmhgszinfo spmhgszinfo : commodityCustomsTariffRespose
                    .getSPMHGSZINFO()) {
                SalesCommodityDto salesCommodityDto = new SalesCommodityDto();
                salesCommodityDto.setHsCode(spmhgszinfo.getHSCODE());
                salesCommodityDto.setName(spmhgszinfo.getHSNAME());
                salesCommodityDto.setMeasurementUnit(commodityCustomsTariffRespose.getHGJLDWMC());
                if (StringUtils.isNotEmpty(commodityCustomsTariffRespose.getTSL())) {
                    salesCommodityDto.setExportTaxRebateRate(new BigDecimal(commodityCustomsTariffRespose.getTSL())
                            .divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP).toString());
                }
                String zssljh = commodityCustomsTariffRespose.getZSSLJH();
                if (zssljh.contains(",")) {
                    zssljh = zssljh.split(",")[0];
                }
                salesCommodityDto.setAddedTaxRate(
                        new BigDecimal(zssljh).divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP).toString());
                if (DictConstants.EXPORT_TYPE_PROXY.equals(enterprise.getExportType())) {
                    Long count = superviseCertificateCodeService.countByCode(spmhgszinfo.getHSHGJGTJ());
                    if (count != null && count > 0) {
                        salesCommodityDto.setErrorsValidator("该商品为监管商品，请重新选择");
                    }
                }
                if (StringUtils.isEmpty(salesCommodityDto.getErrors())) {
                    salesCommodityDtos.add(salesCommodityDto);
                }
            }
        }
        return salesCommodityDtos;
    }

    @Override
    public List<SalesCommoditySpidDto> getXiaoTuCommoditySpidList(String name, String xtUid, Long customerId) {
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(customerId);
        CommodityRequest commodityRequest = new CommodityRequest();
        commodityRequest.setCksptssplxDm(CommodityRequest.OTHER);
        commodityRequest.setCkspdm(name);
        BusinessCommonRequest businessCommonRequest = new BusinessCommonRequest();
        businessCommonRequest.setXtUid(xtUid);
        businessCommonRequest.setCustomerId(customerId);
        businessCommonRequest.setXtEid(enterprise.getXtEid());
        List<SalesCommoditySpidDto> salesCommoditySpidDtos = new ArrayList<>();
        try {
            List<CommodityResponse> commodityResponses = xiaotuRequestService
                    .taxRefundRateInquiry(commodityRequest, businessCommonRequest).stream()
                    .filter(c -> "Y".equals(c.getJbspbz())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(commodityResponses)) {
                for (CommodityResponse commodityRespons : commodityResponses) {
                    SalesCommoditySpidDto salesCommoditySpidDto = new SalesCommoditySpidDto();
                    salesCommoditySpidDto.setName(commodityRespons.getCkspmc());
                    salesCommoditySpidDto.setSpid(commodityRespons.getSpid());
                    salesCommoditySpidDtos.add(salesCommoditySpidDto);
                }
                return salesCommoditySpidDtos;
            } else {
                throw new ServiceException("未检索到商品信息");
            }
        } catch (Exception e) {
            throw new ServiceException("未检索到商品信息");
        }
    }

    @Override
    public SalesCommodity findByDeclarationName(String declarationName) {
        return this.baseMapper.selectByDeclarationName(declarationName);
    }
}
