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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.entity.underlying.UnderlyingApproval;
import com.sunxung.factoring.mapper.underlying.UnderlyingApprovalMapper;
import com.sunxung.factoring.service.underlying.UnderlyingApprovalService;
import org.springframework.stereotype.Service;

/**
 * @author liutao
 * @date 2021.10.11
 */
@Service("underlying_approvalService")
public class UnderlyingApprovalServiceImpl extends ServiceImpl<UnderlyingApprovalMapper, UnderlyingApproval>
        implements UnderlyingApprovalService {
//
//    @Autowired
//    private UnderlyingBasicInfoService underlyingBasicInfoService;
//
//    @Autowired
//    private UnderlyingAccountsReceivableInfoService underlyingAccountsReceivableInfoService;
//
//    @Autowired
//    private DictionaryService dictService;
//
//    @Autowired
//    private FlowableService flowableService;
//
//    @Autowired
//    private RestTemplate restTemplate;
//
//    @Autowired
//    private CustomerService customerService;
//
//    @Autowired
//    private BusinessBasicInfoService businessBasicInfoService;
//
//    @Autowired
//    private ISysAttachmentRefService sysAttachmentRefService;
//
//    @Autowired
//    private AcceptanceBasicInfoService acceptanceBasicInfoService;
//
//    @Autowired
//    private SalesContractService salesContractService;
//
//    @Autowired
//    private ICSalesContractBasicInfoService salesContractBasicInfoService;
//
//    @Autowired
//    private PurchContractService purchContractService;
//
//    @Autowired
//    private PurchContractBasicInfoService purchContractBasicInfoService;
//
//    @Autowired
//    private UnderlyingGoodsInfoService underlyingGoodsInfoService;
//
//    @Value("${config.underlyingAssetsBasic.id.url}")
//    private String underlyingAssetsBasicIdUrl;
//
//    @Value("${config.underlyingAssetsDomestic.add.url}")
//    private String underlyingAssetsDomesticAddUrl;
//
//    @Value("${config.domesticAccountsReceivable.add.url}")
//    private String domesticAccountsReceivableAddUrl;
//
//    @Autowired
//    private InvoiceGoodsInfoService invoiceGoodsInfoService;
//
//
//    @Autowired
//    private ISalesContractSupplementInfoService salesContractSupplementInfoService;
//
//    @Autowired
//    private IPurchContractSupplementInfoService purchContractSupplementInfoService;
//
//    @Autowired
//    private InvoiceBasicInfoService invoiceBasicInfoService;
//
//    @Autowired
//    private IPurchContractSignConclusionService purchContractSignConclusionService;
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void audit(UnderlyingApproval underlyingApproval, String businessKey, String taskId) {
//        //判断审核结果
//        UnderlyingBasicInfo underlyingBasicInfo = underlyingBasicInfoService.getById(businessKey);
//
//        String result;
//        switch (underlyingApproval.getApprovalConclusion()) {
//            case "pass":
//                result = ConstantUtil.APPROVAL;
//                underlyingBasicInfo.setUnderlyingStatus(dictService.getByCode(UnderlyingDict.ChildEnum.APPROVAL.getCode()).getId());
//                //审核通过后，将底层应收账款信息同步到sop的底层管理模块中
//                addUnderlyingInfoToSop(underlyingBasicInfo);
//                break;
//            case "back":
//                result = ConstantUtil.OVERRULE;
//                underlyingBasicInfo.setUnderlyingStatus(dictService.getByCode(UnderlyingDict.ChildEnum.OVERRULE.getCode()).getId());
//                //底层否决  释放本底层的货物
//                //获取对应货物信息
//                List<UnderlyingGoodsInfo> goodsInfoList = underlyingGoodsInfoService
//                        .list(new QueryWrapper<UnderlyingGoodsInfo>().eq("underlying_basic_info_id", underlyingBasicInfo.getId()));
//                if (goodsInfoList != null && goodsInfoList.size() > 0) {
//                    List<Long> acceptanceBasicInfoIds = goodsInfoList.stream().map(UnderlyingGoodsInfo::getAcceptanceBasicInfoId).distinct()
//                            .collect(Collectors.toList());
//                    for (Long acceptanceBasicInfoId : acceptanceBasicInfoIds) {
//                        acceptanceBasicInfoService.update(new UpdateWrapper<AcceptanceBasicInfo>().eq("id", acceptanceBasicInfoId)
//                                .set("is_receivables", false));
//                    }
//                }
//                break;
//            default:
//                result = "";
//
//        }
//        if (StringUtil.isEmpty(result)) {
//            throw new ValidatorException(CodeUtil.FAIL, "结论不能为空");
//        }
//        //修改底层状态
//        underlyingBasicInfoService.updateById(underlyingBasicInfo);
//
//        //保存审核结果
//        underlyingApproval.setAuditorId(ThreadLocalUtil.getUserId());
//        underlyingApproval.setUnderlyingBasicInfoId(underlyingBasicInfo.getId());
//        save(underlyingApproval);
//
//        //完成审核流程流转到下一流程或者完成流程
//        Map<String, Object> msgVariables = new HashMap<>();
//        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "底层编号：" + underlyingBasicInfo.getReceivablesNumber());
//        if (result.equals(ConstantUtil.OVERRULE)) {
//            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
//                    "底层编号为“" + underlyingBasicInfo.getReceivablesNumber() + "”的底层已退回，进入“"
//                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.UNDERLYING_MANAGE) + "—formBusiness”阶段，"
//                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
//        } else if (result.equals(ConstantUtil.APPROVAL)) {
//            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
//                    "底层编号为“" + underlyingBasicInfo.getReceivablesNumber() + "”的底层已通过");
//        }
//        flowableService.completeMyTask(taskId, underlyingBasicInfo, null, result, underlyingApproval.getId(),
//                msgVariables, ConstantUtil.UNDERLYING_MANAGE, null);
//    }
//
//    @Override
//    public UnderlyingApprovalVo getApprovalFileList(Long businessKey) {
//
//        UnderlyingBasicInfo underlyingBasicInfo = underlyingBasicInfoService.getById(businessKey);
//        UnderlyingApprovalVo underlyingApprovalVo = new UnderlyingApprovalVo();
//        if (underlyingBasicInfo != null && underlyingBasicInfo.getBusinessNumber() != null
//                && underlyingBasicInfo.getSupplierId() != null) {
//            //填充所有附件
//            underlyingApprovalVo = autoAllFiles(underlyingBasicInfo);
//
//        }
//        return underlyingApprovalVo;
//    }
//
//    @Override
//    public UnderlyingApprovalVo getView(Long id) {
//        UnderlyingApproval underlyingApproval = baseMapper.selectById(id);
//        if (underlyingApproval != null && underlyingApproval.getUnderlyingBasicInfoId() != null) {
//            UnderlyingApprovalVo underlyingApprovalVo = getApprovalFileList(underlyingApproval.getUnderlyingBasicInfoId());
//            underlyingApprovalVo.setUnderlyingApproval(underlyingApproval);
//            return underlyingApprovalVo;
//        }
//        return null;
//    }
//
//    /**
//     * 同步底层信息到sop
//     *
//     * @param underlyingBasicInfo 贸理通底层信息
//     */
//    private void addUnderlyingInfoToSop(UnderlyingBasicInfo underlyingBasicInfo) {
//        //1.获取供应商的统一社会信用代码，取sop的底层基础信息获取对应的客户信息
//        Customer customer = customerService.getById(underlyingBasicInfo.getSupplierId());
//        if (customer == null || customer.getSocialCreditCode() == null) {
//            throw new ValidatorException(CodeUtil.FAIL, "供应商或供应商的统一社会信用代码不存在");
//        }
//        ResponseEntity<Long> responseEntity = restTemplate.getForEntity(underlyingAssetsBasicIdUrl
//                + "?socialCreditCode=" + customer.getSocialCreditCode() + "&businessType=" + ConstantConversionUtil.DOMESTIC_FACTORING, Long.class);
//
//        if (responseEntity.getBody() == null) {
//            throw new BusinessException(CodeUtil.FAIL, "SOP中供应商不存在、请先前往sop-底层资产管理-国内保理中新增该客户！");
//        }
//
//        Long underlyingAssetsBasicId = responseEntity.getBody();
//
//        //2.包装底层资产基本信息、同步至Sop
//        UnderlyingAssetsDomesticToSop domestic = new UnderlyingAssetsDomesticToSop(underlyingBasicInfo);
//        domestic.setUnderlyingAssetsBasicId(underlyingAssetsBasicId);
//        domestic.setCustomerIdentity("creditor");
//        //这里不能用核心企业、需要去取平台
//        String businessNumber = underlyingBasicInfo.getBusinessNumber();
//        BusinessBasicInfo businessBasicInfo = businessBasicInfoService.getByBusinessNumber(businessNumber);
//        if (businessBasicInfo == null || businessBasicInfo.getPlatform() == null ||
//                businessBasicInfo.getPlatform().getSocialCreditCode() == null) {
//            throw new ValidatorException(CodeUtil.FAIL, "贸易平台或贸易平台的统一社会信用代码不存在");
//        }
//        Customer purchaser = customerService.getById(underlyingBasicInfo.getEnterpriseCustomerInfoId());
//        if (purchaser == null || purchaser.getSocialCreditCode() == null) {
//            throw new ValidatorException(CodeUtil.FAIL, "核心企业或核心企业的统一社会信用代码不存在");
//        }
//        domestic.setThirdPartyCustomerCode(businessBasicInfo.getPlatform().getSocialCreditCode());
//        domestic.setThirdPartyIdentity("debtor");
//        //核心企业名称
//        domestic.setPurchaserName(purchaser.getEnterpriseName());
//        //销售合同编号
////        CSalesContractBasicInfo salesContractBasicInfo = salesContractBasicInfoService.getSalesContractBasicByPurchContractNumber(domestic.getContractNo());
////        if (salesContractBasicInfo != null) {
////            domestic.setSalesContractNumber(salesContractBasicInfo.getContractNumber());
////            domestic.setSalesContractName(salesContractBasicInfo.getContractName());
////        }
//        ResponseEntity<Long> postForEntity = restTemplate.postForEntity(underlyingAssetsDomesticAddUrl, domestic, Long.class);
//
//        if (postForEntity == null || postForEntity.getBody() == null) {
//            throw new BusinessException(CodeUtil.FAIL, "添加底层基础信息失败");
//        }
//        Long assetsDomesticId = postForEntity.getBody();
//        //3.包装应收账款数据、同步至sop
//        List<UnderlyingAccountsReceivableInfo> informationList = underlyingAccountsReceivableInfoService.findByBasicId(underlyingBasicInfo.getId());
//        if (informationList != null && informationList.size() > 0) {
//            DomesticAccountsReceivableToSop accountsReceivableToSop = new DomesticAccountsReceivableToSop(underlyingBasicInfo);
//            accountsReceivableToSop.setUnderlyingAssetsDomesticId(assetsDomesticId);
//            //计算应收账款金额总和
//            BigDecimal accountsReceivableAmount = informationList.stream().filter(accountsReceivable -> accountsReceivable.getAccountsReceivableAmount() != null)
//                    .map(UnderlyingAccountsReceivableInfo::getAccountsReceivableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
//            accountsReceivableToSop.setAccountsReceivableAmount(accountsReceivableAmount);
//            //计算应收账款净额总和
//            BigDecimal netAccountsReceivableAmount = informationList.stream().filter(accountsReceivable -> accountsReceivable.getNetAccountsReceivableAmount() != null)
//                    .map(UnderlyingAccountsReceivableInfo::getNetAccountsReceivableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
//            accountsReceivableToSop.setNetAccountsReceivableAmount(netAccountsReceivableAmount);
//            accountsReceivableToSop.setAccountsReceivableGoodsList(informationList);
//            ResponseEntity<Long> accountsReceivableEntity = restTemplate.postForEntity(domesticAccountsReceivableAddUrl, accountsReceivableToSop, Long.class);
//            if (accountsReceivableEntity == null || accountsReceivableEntity.getBody() == null) {
//                throw new BusinessException(CodeUtil.FAIL, "添加底层应收账款信息失败");
//            }
//            Long sopAccountsReceivableId = accountsReceivableEntity.getBody();
//            underlyingBasicInfo.setSopAccountsReceivableId(sopAccountsReceivableId);
//            underlyingBasicInfoService.updateById(underlyingBasicInfo);
//        }
//    }
//
//    /**
//     * 填充所有附件
//     * @param underlyingBasicInfo
//     * @return
//     */
//    @Override
//    public UnderlyingApprovalVo autoAllFiles(UnderlyingBasicInfo underlyingBasicInfo){
//        UnderlyingApprovalVo underlyingApprovalVo = new UnderlyingApprovalVo();
//        //获取销售合同文件
//        CSalesContract salesContractManagement = salesContractService.getByBusinessNumber(underlyingBasicInfo.getBusinessNumber());
//        if (salesContractManagement == null || salesContractManagement.getId() == null) {
//            throw new BusinessException(CodeUtil.FAIL, "销售合同管理不能为空");
//        }
//        CSalesContractBasicInfo salesContractBasicInfo = salesContractBasicInfoService.getOne(new QueryWrapper<CSalesContractBasicInfo>()
//                .eq("c_sales_contract_management_id",salesContractManagement.getId()));
//        if (salesContractBasicInfo == null || salesContractBasicInfo.getId() == null) {
//            throw new BusinessException(CodeUtil.FAIL, "销售合同基础信息不能为空");
//        }
//
//        AttachmentDto salesContractDto = AttachmentDto.builder()
//                .setEntityId(salesContractBasicInfo.getId())
//                .setChildEnum(FileModuleDict.ChildEnum.SALES_CONTRACT_FILE)
//                .build();
//        List<FileStorage> salesContractFiles = sysAttachmentRefService.getFiles(salesContractDto);
//
//        //销售合同补充合同
//        Long salesStatus = dictService.getByCode(SalesContractStatusDict.ChildEnum.APPROVAL_CHANGE.getCode()).getId();
//
//        //销售合同补充文件
//        List<SalesContractSupplementInfo> salesContractSupplementInfos = salesContractSupplementInfoService
//                .list(new QueryWrapper<SalesContractSupplementInfo>().eq("sales_contract_management_id", salesContractManagement.getId()));
//        if (CollectionUtil.isNotEmpty(salesContractSupplementInfos)) {
//            salesContractSupplementInfos.stream().forEach(s -> {
//                if (s.getApproval() == 1 && salesContractManagement.getContractStatus().equals(salesStatus) || s.getApproval() == 0) {
//                    List<FileStorage> salesContractSupplementFiles = sysAttachmentRefService.getFiles(AttachmentDto.builder()
//                            .setChildEnum(FileModuleDict.ChildEnum.SALES_CONTRACT_SUPPLEMENT_FILE).setEntityId(s.getId()).build());
//                    salesContractFiles.addAll(salesContractSupplementFiles);
//                }
//            });
//        }
//
//        underlyingApprovalVo.setSalesContractFiles(salesContractFiles);
//
//        //采购合同
//        PurchContractManagement purchContractManagement = purchContractService.getOne(
//                new QueryWrapper<PurchContractManagement>()
//                        .eq("business_number", underlyingBasicInfo.getBusinessNumber())
//                        .eq("supplier_id", underlyingBasicInfo.getSupplierId()));
//        if (purchContractManagement == null || purchContractManagement.getId() == null) {
//            throw new BusinessException(CodeUtil.FAIL, "采购合同管理不能为空");
//        }
//        PurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.getLatestBasicInfo(purchContractManagement.getId(),
//                ConstantConversionUtil.APPROVAL_RESULT_PASS);
//        if (purchContractBasicInfo == null || purchContractBasicInfo.getId() == null) {
//            throw new BusinessException(CodeUtil.FAIL, "采购合同基础信息不能为空");
//        }
//        List<FileStorage> purchContractFiles = sysAttachmentRefService.getFiles(AttachmentDto.builder()
//                .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_FILE).setEntityId(purchContractBasicInfo.getId()).build());
//
//        //线下签署节点的附件
//        PurchContractSignConclusion purchContractSignConclusion = purchContractSignConclusionService
//                .getOne(new QueryWrapper<PurchContractSignConclusion>().eq("purch_contract_basic_info_id", purchContractBasicInfo.getId())
//                        .orderByDesc("gmt_create").last("limit 1"));
//        if (purchContractSignConclusion != null) {
//            purchContractFiles.addAll(sysAttachmentRefService.getFiles(AttachmentDto.builder()
//                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SIGN_UNDERLINE).setEntityId(purchContractSignConclusion.getId()).build()));
//        }
//        //采购合同补充合同
//        List<PurchContractSupplementInfo> contractSupplementInfos = purchContractSupplementInfoService
//                .list(new QueryWrapper<PurchContractSupplementInfo>().eq("purch_contract_management_id", purchContractManagement.getId()));
//        //采购合同状态
//        Long purchStatus = dictService.getByCode(PurchContractStatusDict.ChildEnum.CONFIRM_CHANGE.getCode()).getId();
//        if (dictService.getByCode(PurchContractStatusDict.ChildEnum.CONFIRM_CHANGE.getCode()).getId()
//                .equals(purchContractManagement.getContractStatus())) {
//            if (CollectionUtil.isNotEmpty(contractSupplementInfos)) {
//                contractSupplementInfos.stream().forEach(contractSupplementInfo -> {
//                    if (contractSupplementInfo.getApproval() == 0) {
//                        //采购合同变更上传的合同文件
//                        AttachmentDto attachmentDto = AttachmentDto.builder().setEntityId(contractSupplementInfo.getId())
//                                .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_FILE).build();
//                        purchContractFiles.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();
//                        purchContractFiles.addAll(sysAttachmentRefService.getFiles(attachmentDto));
//                    }
//
//                });
//            }
//        }
//        underlyingApprovalVo.setPurchContractFiles(purchContractFiles);
//
//
//        //获取验收单文件
//        List<Long> acceptanceIds = underlyingGoodsInfoService.findAcceptanceIdByBasicId(underlyingBasicInfo.getId());
//        List<FileStorage> acceptanceFiles = new ArrayList<>();
//        if (acceptanceIds != null && acceptanceIds.size() > 0) {
//            for (Long acceptanceId : acceptanceIds) {
//                AttachmentDto acceptanceDto = AttachmentDto.builder()
//                        .setEntityId(acceptanceId)
//                        .setChildEnum(FileModuleDict.ChildEnum.ACCEPTANCE_FILE)
//                        .build();
//                List<FileStorage> files = sysAttachmentRefService.getFiles(acceptanceDto);
//                acceptanceFiles.addAll(files);
//            }
//        }
//        underlyingApprovalVo.setAcceptanceFiles(acceptanceFiles);
//
//        //获取结算单文件
//        List<Long> settlementIds = underlyingGoodsInfoService.findSettlementIdByBasicId(underlyingBasicInfo.getId());
//        List<FileStorage> settlementFiles = new ArrayList<>();
//        if (settlementIds != null && settlementIds.size() > 0) {
//            for (Long settlementId : settlementIds) {
//                AttachmentDto settlementDto = AttachmentDto.builder()
//                        .setEntityId(settlementId)
//                        .setChildEnum(FileModuleDict.ChildEnum.SETTLEMENT_FILE)
//                        .build();
//                List<FileStorage> files = sysAttachmentRefService.getFiles(settlementDto);
//                settlementFiles.addAll(files);
//            }
//        }
//        underlyingApprovalVo.setSettlementFiles(settlementFiles);
//        //获取销售发票、采购发票文件
//        List<UnderlyingGoodsInfo> underlyingGoodsInfos = underlyingGoodsInfoService
//                .list(new QueryWrapper<UnderlyingGoodsInfo>().eq("underlying_basic_info_id", underlyingBasicInfo.getId()));
//        HashSet<Long> settlementBasicIds = new HashSet<>();
//        for (UnderlyingGoodsInfo underlyingGoodsInfo : underlyingGoodsInfos) {
//            settlementBasicIds.add(underlyingGoodsInfo.getSettlementBasicInfoId());
//        }
//        List<InvoiceGoodsInfo> invoiceGoodsInfos = invoiceGoodsInfoService
//                .list(new QueryWrapper<InvoiceGoodsInfo>().in("settlement_basic_info_id", settlementBasicIds));
//        HashSet<Long> invoiceBasicIds = new HashSet<>();
//        for (InvoiceGoodsInfo invoiceGoodsInfo : invoiceGoodsInfos) {
//            InvoiceBasicInfo invoiceBasicInfo = invoiceBasicInfoService.getById(invoiceGoodsInfo.getInvoiceBasicInfoId());
//            if (invoiceBasicInfo.getInvoiceStatus().equals(dictService.getByCode(InvoiceDict.ChildEnum.PASS.getCode()).getId())) {
//                invoiceBasicIds.add(invoiceGoodsInfo.getInvoiceBasicInfoId());
//            }
//        }
//        List<FileStorage> salesInvoiceFiles = new ArrayList<>();
//        List<FileStorage> purchInvoiceFiles = new ArrayList<>();
//        if (invoiceBasicIds != null && invoiceBasicIds.size() > 0) {
//            for (Long invoiceBasicId : invoiceBasicIds) {
//                AttachmentDto settlementDto = AttachmentDto.builder()
//                        .setEntityId(invoiceBasicId)
//                        .setChildEnum(FileModuleDict.ChildEnum.INVOICE_SALES_FILE)
//                        .build();
//                List<FileStorage> files = sysAttachmentRefService.getFiles(settlementDto);
//                salesInvoiceFiles.addAll(files);
//                AttachmentDto settlementDtoPurch = AttachmentDto.builder()
//                        .setEntityId(invoiceBasicId)
//                        .setChildEnum(FileModuleDict.ChildEnum.INVOICE_PURCHASE_FILE)
//                        .build();
//                List<FileStorage> purchFiles = sysAttachmentRefService.getFiles(settlementDtoPurch);
//                purchInvoiceFiles.addAll(purchFiles);
//            }
//        }
//        underlyingApprovalVo.setPurchInvoiceFiles(purchInvoiceFiles);
//        underlyingApprovalVo.setSalesInvoiceFiles(salesInvoiceFiles);
//
//        return underlyingApprovalVo;
//    }

}
