package com.inkasso.factoring.invoicemanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.factoring.common.constant.ConstantUtil;
import com.inkasso.factoring.common.dict.impl.AmountKindDict;
import com.inkasso.factoring.common.dict.impl.FileModuleDict;
import com.inkasso.factoring.common.dict.impl.SettlementDict;
import com.inkasso.factoring.common.enums.ProjectInitiationStatusEnum;
import com.inkasso.factoring.dict.service.DictionaryService;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import com.inkasso.factoring.file.service.FileService;
import com.inkasso.factoring.invoicemanage.dao.InvoiceApprovalDAO;
import com.inkasso.factoring.invoicemanage.entity.*;
import com.inkasso.factoring.invoicemanage.service.*;
import com.inkasso.factoring.purchManagement.entity.CPurchContractBasicInfo;
import com.inkasso.factoring.purchManagement.entity.CPurchContractManagement;
import com.inkasso.factoring.purchManagement.entity.CPurchContractSignConclusion;
import com.inkasso.factoring.purchManagement.entity.CPurchContractSupplementInfo;
import com.inkasso.factoring.purchManagement.service.ICPurchContractBasicInfoService;
import com.inkasso.factoring.purchManagement.service.ICPurchContractManagementService;
import com.inkasso.factoring.purchManagement.service.ICPurchContractSignConclusionService;
import com.inkasso.factoring.purchManagement.service.ICPurchContractSupplementInfoService;
import com.inkasso.factoring.salesManagement.entity.CSalesContractBasicInfo;
import com.inkasso.factoring.salesManagement.entity.CSalesContractManagement;
import com.inkasso.factoring.salesManagement.entity.CSalesContractSupplementInfo;
import com.inkasso.factoring.salesManagement.service.ICSalesContractBasicInfoService;
import com.inkasso.factoring.salesManagement.service.ICSalesContractManagementService;
import com.inkasso.factoring.salesManagement.service.ICSalesContractSupplementInfoService;
import com.inkasso.factoring.settlement.entity.SettlementBasicInfo;
import com.inkasso.factoring.settlement.service.SettlementBasicInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description : 销售合同审批service实现类
 * @Author : JiaYf
 * @Date: 2021-10-23 14:10
 */
@Service("sale_invoice_approvalService")
public class InvoiceApprovalServiceImpl extends ServiceImpl<InvoiceApprovalDAO, InvoiceApproval>
        implements InvoiceApprovalService {

    @Autowired
    private InvoiceBasicInfoService invoiceBasicInfoService;


    @Autowired
    private DictionaryService dictService;

    @Autowired
    private ICSalesContractBasicInfoService salesContractBasicInfoService;

    @Autowired
    private ICSalesContractManagementService salesContractService;

    @Autowired
    private ICPurchContractBasicInfoService purchContractBasicInfoService;

    @Autowired
    private ICPurchContractManagementService icPurchContractManagementService;


    @Autowired
    private InvoiceGoodsInfoService invoiceGoodsInfoService;

    @Autowired
    private SettlementBasicInfoService settlementBasicInfoService;

    @Autowired
    private SalesInvoiceInfoService salesInvoiceInfoService;
    @Autowired
    private FileService fileService;

    @Autowired
    private InvoiceSupplierInfoService invoiceSupplierInfoService;

    @Autowired
    private ICSalesContractSupplementInfoService icSalesContractSupplementInfoService;

    @Autowired
    private ICPurchContractSupplementInfoService icPurchContractSupplementInfoService;
    @Autowired
    private ICPurchContractSignConclusionService icPurchContractSignConclusionService;


    @Override
    public InvoiceApproval getFileList(Long businessKey) {
        InvoiceApproval invoiceApproval = new InvoiceApproval();
        InvoiceBasicInfo invoiceBasicInfo = invoiceBasicInfoService.getById(businessKey);
        List<InvoiceGoodsInfo> invoiceGoodsInfoList = invoiceGoodsInfoService.list(new QueryWrapper<InvoiceGoodsInfo>().eq("invoice_basic_info_id", businessKey));
        Set<Long> settlementInfoIds = new HashSet<>();
        if (invoiceGoodsInfoList != null && invoiceGoodsInfoList.size() > 0) {
            for (InvoiceGoodsInfo invoiceGoodsInfo : invoiceGoodsInfoList) {
                settlementInfoIds.add(invoiceGoodsInfo.getSettlementBasicInfoId());
            }
        }
        Set<Long> supplierIds = new HashSet<>();
        List<InvoiceSupplierInfo> invoiceSupplierInfos = invoiceSupplierInfoService.list(new QueryWrapper<InvoiceSupplierInfo>().eq("invoice_basic_info_id", businessKey));
        if (invoiceSupplierInfos != null && invoiceSupplierInfos.size() > 0) {
            for (InvoiceSupplierInfo invoiceSupplierInfo : invoiceSupplierInfos) {
                supplierIds.add(invoiceSupplierInfo.getSupplierId());
            }
        }
        //销售合同
        CSalesContractManagement salesContractManagement = salesContractService.getByBusinessNumber(invoiceBasicInfo.getBusinessNumber());
        CSalesContractBasicInfo salesContractBasicInfo = salesContractBasicInfoService.getOne(new QueryWrapper<CSalesContractBasicInfo>()
                .eq("c_sales_contract_management_id",salesContractManagement.getId()));
        List<FileStorageDO> salesContract = fileService.findByBusinessId(salesContractBasicInfo.getId(), FileTypeEnum.SALES_CONTRACT_FILE.getCode());


        //销售合同补充文件
        List<CSalesContractSupplementInfo> salesContractSupplementInfos = icSalesContractSupplementInfoService
                .list(new QueryWrapper<CSalesContractSupplementInfo>().eq("c_sales_contract_management_id", salesContractManagement.getId()));
        if (CollectionUtil.isNotEmpty(salesContractSupplementInfos)) {
            salesContractSupplementInfos.stream().forEach(s -> {
                if (salesContractManagement.getContractStatus().equals(ProjectInitiationStatusEnum.COMPLETED.getCode()) ) {
                    List<FileStorageDO> salesContractSupplementFiles = fileService.findByBusinessId(s.getId(), FileModuleDict.ChildEnum.SALES_CONTRACT_SUPPLEMENT_FILE.getCode());
                    salesContract.addAll(salesContractSupplementFiles);
                }
            });
        }
        invoiceApproval.setSalesContract(salesContract);

        //下游结算单文件
        List<FileStorageDO> settlementFiles = new ArrayList<>();
        for (Long settlementInfoId : settlementInfoIds) {
            List<FileStorageDO> files = fileService.findByBusinessId(settlementInfoId, FileTypeEnum.SETTLEMENT_FILE.getCode());
            settlementFiles.addAll(files);
        }
        invoiceApproval.setSettlementFile(settlementFiles);
        //采购合同
        List<FileStorageDO> purchFilelist = new ArrayList<>();
        //上游结算单文件
        List<FileStorageDO> settlementUpstreamSignedFile = new ArrayList<>();
        for (Long settlementInfoId : settlementInfoIds) {
            SettlementBasicInfo settlementBasicInfo = settlementBasicInfoService.getById(settlementInfoId);
            if (settlementBasicInfo != null) {
                supplierIds.add(settlementBasicInfo.getSupplierId());
                List<FileStorageDO> files = new ArrayList<>();
                if (ProjectInitiationStatusEnum.PROCESSING.getCode().equals(settlementBasicInfo.getSettlementStatus())) {
                    files  = fileService.findByBusinessId(settlementInfoId, FileTypeEnum.SETTLEMENT_UPSTREAM_UNSIGNED_FILE.getCode());
                } else {
                    files.add(fileService.findOneByBusinessId(settlementInfoId, FileTypeEnum.SETTLEMENT_UPSTREAM_SIGNED_FILE.getCode()));
                }
                settlementUpstreamSignedFile.addAll(files);
            }
        }
        for (Long supplierId : supplierIds) {

            //采购合同
            CPurchContractManagement purchContractManagement = icPurchContractManagementService.getOne(new QueryWrapper<CPurchContractManagement>().eq("business_number", invoiceBasicInfo.getBusinessNumber()).eq("supplier_id", supplierId));

            if (purchContractManagement == null || purchContractManagement.getId() == null) {
                throw new BusinessException(CodeUtil.FAIL, "采购合同管理不能为空");
            }
            CPurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.getLatestBasicInfo(purchContractManagement.getId(),
                    ConstantUtil.PASS);
            if (purchContractBasicInfo == null || purchContractBasicInfo.getId() == null) {
                throw new BusinessException(CodeUtil.FAIL, "采购合同基础信息不能为空");
            }
            purchFilelist.addAll(fileService.findByBusinessId(purchContractBasicInfo.getId(), FileTypeEnum.PURCHASE_CONTRACT_FILE.getCode()));
            //线下签署节点的附件
            CPurchContractSignConclusion purchContractSignConclusion = icPurchContractSignConclusionService
                    .getOne(new QueryWrapper<CPurchContractSignConclusion>().eq("c_purch_contract_basic_info_id", purchContractBasicInfo.getId())
                            .orderByDesc("gmt_create").last("limit 1"));
            if (purchContractSignConclusion != null) {
                purchFilelist.addAll(fileService.findByBusinessId(purchContractSignConclusion.getId(), FileTypeEnum.PURCHASE_CONTRACT_SIGN_UNDERLINE.getCode()));
            }
            //采购合同补充合同
            List<CPurchContractSupplementInfo> contractSupplementInfos = icPurchContractSupplementInfoService
                    .list(new QueryWrapper<CPurchContractSupplementInfo>().eq("purch_contract_management_id", purchContractManagement.getId()));
            //采购合同状态
            Long purchStatus = dictService.getByCode(ProjectInitiationStatusEnum.COMPLETED.getCode()).getId();
            if (dictService.getByCode(ProjectInitiationStatusEnum.COMPLETED.getCode()).getId()
                    .equals(purchContractManagement.getContractStatus())) {
                if (CollectionUtil.isNotEmpty(contractSupplementInfos)) {
                    contractSupplementInfos.stream().forEach(contractSupplementInfo -> {

                        //采购合同变更审核是选择是否签署 TODO
//                        if (contractSupplementInfo.getApproval() == 0) {
//                            //采购合同变更上传的合同文件
//                            AttachmentDto attachmentDto = AttachmentDto.builder().setEntityId(contractSupplementInfo.getId())
//                                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_FILE).build();
//                            purchFilelist.addAll(sysAttachmentRefService.getFiles(attachmentDto));
//                        } else if (contractSupplementInfo.getApproval() == 1 && purchContractManagement.getContractStatus().equals(purchStatus)) {
//                            //采购合同变更已签署文件
//                            AttachmentDto attachmentDto = AttachmentDto.builder().setEntityId(contractSupplementInfo.getId())
//                                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_SIGN_FILE).build();
//                            purchFilelist.addAll(sysAttachmentRefService.getFiles(attachmentDto));
//                        }

                    });
                }
            }
        }
        invoiceApproval.setPurchContract(purchFilelist);
        invoiceApproval.setSettlementUpstreamSignedFile(settlementUpstreamSignedFile);
        //参考待开发票
        invoiceApproval.setPendingInvoice(fileService.findByBusinessId(invoiceBasicInfo.getId() , FileTypeEnum.INVOICE_SALES_FILE.getCode()));
        //金额种类是货款前端显示结算单文件和发票文件
        boolean amountKind = true;
        if (invoiceBasicInfo.getAmountKind().equals(dictService.getByCode(AmountKindDict.ChildEnum.PAYMENT.getCode()).getId())) {
            amountKind = false;
        }
        invoiceApproval.setAmountKind(amountKind);
        //销售发票信息
        QueryWrapper<SalesInvoiceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("invoice_basic_info_id", businessKey);
        SalesInvoiceInfo salesInvoiceInfo = salesInvoiceInfoService.getOne(queryWrapper);
        List<FileStorageDO> fileStorages = fileService.findByBusinessId(salesInvoiceInfo.getId() , FileTypeEnum.INVOICE_SALES_FILE.getCode());
        salesInvoiceInfo.setSalesInvoicFile(CollectionUtil.isNotEmpty(fileStorages)?fileStorages:new ArrayList<>());
        invoiceApproval.setSalesInvoiceInfo(salesInvoiceInfo);
        return invoiceApproval;
    }
}
