package com.sunxung.factoring.service.underlying.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.dict.impl.UnderlyingDict;
import com.sunxung.factoring.entity.acceptance.AcceptanceApproval;
import com.sunxung.factoring.entity.invoicemanage.InvoiceApproval;
import com.sunxung.factoring.entity.invoicemanage.InvoiceGoodsInfo;
import com.sunxung.factoring.entity.project.vo.BusinessProcessingTaskVo;
import com.sunxung.factoring.entity.project.vo.SearchBusinessProcessingTask;
import com.sunxung.factoring.entity.settlement.SettlementGoodsInfo;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.underlying.CustomerFileSearch;
import com.sunxung.factoring.entity.underlying.UnderlyingBasicInfo;
import com.sunxung.factoring.entity.underlying.sop.UnderlyingFileVo;
import com.sunxung.factoring.entity.underlying.vo.UnderlyingApprovalVo;
import com.sunxung.factoring.mapper.underlying.UnderlyingBasicInfoMapper;
import com.sunxung.factoring.service.acceptancesheet.AcceptanceSheetLegalFlowService;
import com.sunxung.factoring.service.invoicemanage.InvoiceApprovalService;
import com.sunxung.factoring.service.invoicemanage.InvoiceBasicInfoService;
import com.sunxung.factoring.service.invoicemanage.InvoiceGoodsInfoService;
import com.sunxung.factoring.service.settlement.SettlementGoodsInfoService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import com.sunxung.factoring.service.underlying.UnderlyingApprovalService;
import com.sunxung.factoring.service.underlying.UnderlyingBasicInfoService;
import com.sunxung.factoring.service.underlying.UnderlyingGoodsInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liutao
 * @date 2021.10.11
 */
@Service("underlyingManageService")
public class UnderlyingBasicInfoServiceImpl extends ServiceImpl<UnderlyingBasicInfoMapper, UnderlyingBasicInfo> implements UnderlyingBasicInfoService {

    @Autowired
    private DictionaryService dictService;
    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;
    @Autowired
    private UnderlyingApprovalService underlyingApprovalService;
    @Autowired
    private UnderlyingGoodsInfoService underlyingGoodsInfoService;
    @Autowired
    private AcceptanceSheetLegalFlowService acceptanceSheetLegalFlowService;
    @Autowired
    private InvoiceBasicInfoService invoiceBasicInfoService;
    @Autowired
    private InvoiceApprovalService invoiceApprovalService;
    @Autowired
    private SettlementGoodsInfoService settlementGoodsInfoService;
    @Autowired
    private InvoiceGoodsInfoService invoiceGoodsInfoService;


    @Override
    public UnderlyingBasicInfo get(Long id) {
        return baseMapper.getListInfo(id);
    }

    @Override
    public UnderlyingBasicInfo getDetail(Long id) {
        return baseMapper.getDetail(id);
    }

    @Override
    public List<BusinessProcessingTaskVo> findAllList(SearchBusinessProcessingTask search) {
        List<BusinessProcessingTaskVo> list = baseMapper.findAllList(search);
        list.stream().forEach(processingTaskVo -> autoButtonFlag(processingTaskVo));
        return list;
    }

    @Override
    public List<BusinessProcessingTaskVo> findMyCompletedList(SearchBusinessProcessingTask search) {
        return baseMapper.findMyCompletedList(search);
    }

    @Override
    public UnderlyingFileVo getAllBusinessFile(CustomerFileSearch customerFileSearch) {
        UnderlyingFileVo underlyingFileVo = new UnderlyingFileVo();
        List<FileStorage> fileStorageList = new ArrayList<>();
        if (customerFileSearch != null) {
            if (CollectionUtil.isNotEmpty(customerFileSearch.getAccountReceivableIdList())) {
                customerFileSearch.getAccountReceivableIdList().forEach(
                        c -> {
                            UnderlyingBasicInfo underlyingBasicInfo = getOne(new QueryWrapper<UnderlyingBasicInfo>()
                                    .eq("sop_accounts_receivable_id", c));
                            if (underlyingBasicInfo != null) {


                                AttachmentDto attachmentDto = AttachmentDto.builder()
                                        .setEntityId(underlyingBasicInfo.getId())
                                        .setChildEnum(FileModuleDict.ChildEnum.UNDERLYING_FILE)
                                        .build();
                                //网价文件
                                fileStorageList.addAll(sysAttachmentRefService.getFiles(attachmentDto));
                                //销售合同文件-采购合同文件-下游验收单文件
                                UnderlyingApprovalVo underlyingApprovalVo = null;
                                fileStorageList.addAll(underlyingApprovalVo.getSalesContractFiles());
                                fileStorageList.addAll(underlyingApprovalVo.getPurchContractFiles());
                                fileStorageList.addAll(underlyingApprovalVo.getAcceptanceFiles());
                                //验收单管理-上游验收单（已签署）
                                List<Long> acceptanceIds = underlyingGoodsInfoService.findAcceptanceIdByBasicId(underlyingBasicInfo.getId());
                                List<Long> settlementBasics = new ArrayList<>();
                                if (CollectionUtil.isNotEmpty(acceptanceIds)) {
                                    List<Long> acceptanceIdList = acceptanceIds.stream().distinct().collect(Collectors.toList());
                                    if (CollectionUtil.isNotEmpty(acceptanceIdList)) {
                                        acceptanceIdList.forEach(
                                                n -> {
                                                    AcceptanceApproval acceptanceApproval = acceptanceSheetLegalFlowService
                                                            .getOne(new QueryWrapper<AcceptanceApproval>()
                                                                    .eq("acceptance_basic_info_id", n)
                                                                    .orderByDesc("gmt_create").last("limit 1"));
                                                    AttachmentDto attachmentDtoAcceptance = AttachmentDto.builder()
                                                            .setEntityId(acceptanceApproval.getAcceptanceBasicInfoId())
                                                            .setChildEnum(FileModuleDict.ChildEnum.ACCEPTANCE_UPSTREAM_FILE_SIGN)
                                                            .build();
                                                    List<FileStorage> acceptanceUpstreamFileSign = sysAttachmentRefService.getFiles(attachmentDtoAcceptance);
                                                    fileStorageList.add(acceptanceUpstreamFileSign.get(0));

                                                    //根据验收单id查询结算货物
                                                    List<SettlementGoodsInfo> settlementGoodsInfos = settlementGoodsInfoService.listByAcceptanceId(n);
                                                    settlementBasics.addAll(settlementGoodsInfos.stream().map(SettlementGoodsInfo::getSettlementBasicInfoId).collect(Collectors.toList()));
                                                }

                                        );
                                    }
                                }
                                //发票管理-采购发票
                                List<Long> invoiceIds = new ArrayList<>();
                                if (CollectionUtil.isNotEmpty(settlementBasics)) {
                                    for (Long m : settlementBasics) {
                                        List<InvoiceGoodsInfo> invoiceGoodsInfos = invoiceGoodsInfoService
                                                .list(new QueryWrapper<InvoiceGoodsInfo>().eq("settlement_basic_info_id", m));
                                        invoiceIds.addAll(invoiceGoodsInfos.stream().map(InvoiceGoodsInfo::getInvoiceBasicInfoId).distinct().collect(Collectors.toList()));

                                    }

                                }
                                List<Long> basicIds = invoiceIds.stream().distinct().collect(Collectors.toList());
                                if (CollectionUtil.isNotEmpty(basicIds)) {
                                    basicIds.forEach(
                                            m -> {
                                                AttachmentDto attachmentDtoInvoice = AttachmentDto.builder()
                                                        .setEntityId(m)
                                                        .setChildEnum(FileModuleDict.ChildEnum.INVOICE_PURCHASE_FILE)
                                                        .build();
                                                List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDtoInvoice);
                                                fileStorageList.addAll(files);
                                                //发票明细
                                                AttachmentDto attachmentDtoInvoice2= AttachmentDto.builder()
                                                    .setEntityId(m)
                                                    .setChildEnum(FileModuleDict.ChildEnum.INVOICE_DETAIL_FILE)
                                                    .build();
                                                List<FileStorage> files2 = sysAttachmentRefService.getFiles(attachmentDtoInvoice2);
                                                fileStorageList.addAll(files2);

                                                //发票管理-审核页面-下游结算单附件/上游结算单附件
                                                InvoiceApproval invoiceApproval = invoiceApprovalService
                                                        .getOne(new QueryWrapper<InvoiceApproval>().eq("invoice_basic_info_id", m)
                                                                .eq("approval_conclusion","pass"));
                                                if (invoiceApproval != null) {
                                                    InvoiceApproval invoiceApprovalData = invoiceApprovalService.getView(invoiceApproval.getId());
                                                    fileStorageList.addAll(invoiceApprovalData.getSettlementFile());
                                                    fileStorageList.addAll(invoiceApprovalData.getSettlementUpstreamSignedFile());
                                                }
                                            }
                                    );
                                }

                            }
                        }
                );
            }
        }
        underlyingFileVo.setFileStorageList(fileStorageList);
        return underlyingFileVo;
    }

    //填充是否展示下载文件按钮
    private void autoButtonFlag(BusinessProcessingTaskVo processingTaskVo) {
        Dictionary approvalDict = dictService.getByCode(UnderlyingDict.ChildEnum.APPROVAL.getCode());
        processingTaskVo.setDownloadFileFlag(false);
        if (approvalDict.getId().equals(processingTaskVo.getStatus().getId())) {
            processingTaskVo.setDownloadFileFlag(true);
        }
    }
}
