package com.sunxung.factoring.service.financing.review.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.component.util.ConstantConversionUtil;
import com.sunxung.factoring.component.util.StringUtil;
import com.sunxung.factoring.entity.financing.review.*;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.mapper.financing.review.ReviewQuotaDisburseHisMapper;
import com.sunxung.factoring.service.financing.review.*;
import com.sunxung.factoring.service.sys.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 额度支用 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2024-01-09
 */
@Service("review_quota_disburseService")
public class ReviewQuotaDisburseHisServiceImpl extends ServiceImpl<ReviewQuotaDisburseHisMapper, ReviewQuotaDisburseHis> implements IReviewQuotaDisburseHisService {

    @Autowired
    private IReviewMasterContractHisService reviewMasterContractHisService;
    @Autowired
    private IReviewMasterContractDebtorHisService reviewMasterContractDebtorHisService;
    @Autowired
    private IReviewFinancingInfoHisService reviewFinancingInfoHisService;
    @Autowired
    private IReviewIncomeExpenditurePlanHisService reviewIncomeExpenditurePlanHisService;
    @Autowired
    private IReviewRltRepayHisService reviewRltRepayHisService;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private IReviewGuaranteeFileHisService reviewGuaranteeFileHisService;
    @Autowired
    private IReviewRltRepayEquityAssetsHistoryService reviewRltRepayEquityAssetsHistoryService;
    @Autowired
    private IReviewRltRepayLandHistoryService reviewRltRepayLandHistoryService;
    @Autowired
    private IReviewRltRepayVehicleHistoryService reviewRltRepayVehicleHistoryService;
    @Autowired
    private IReviewRltRepayEstateHistoryService reviewRltRepayEstateHistoryService;
    @Autowired
    private IReviewRltRepayOtherAssetsHistoryService reviewRltRepayOtherAssetsHistoryService;
    @Autowired
    private IReviewMortgageBasicInfoHisService reviewMortgageBasicInfoHisService;
    @Autowired
    private IReviewMortgagePledgeInfoHisService reviewMortgagePledgeInfoHisService;
    @Autowired
    private IReviewMortgageCollateralInfoHisService reviewMortgageCollateralInfoHisService;
    @Autowired
    private IReviewTransferReceivableHisService reviewTransferReceivableHisService;
    @Autowired
    private IReviewBasicContractHisService reviewBasicContractHisService;
    @Autowired
    private IReviewBasicContractChangeContentHisService reviewBasicContractChangeContentHisService;

    @Override
    public ReviewQuotaDisburseHis getView(Long id) {

        ReviewQuotaDisburseHis reviewQuotaDisburseHis = getById(id);
        if (reviewQuotaDisburseHis == null) {
            throw new BusinessException(CodeUtil.FAIL, "融资申请历史信息不能为空");
        }

        //填充主合同信息历史
        autoMasterContractInfoHis(reviewQuotaDisburseHis);
        //填充融资信息历史
        autoReviewFinancingInfoHis(reviewQuotaDisburseHis);
        //填充收支计划信息
        autoIncomeExpenditurePlanHis(reviewQuotaDisburseHis);
        //新增相关还款责任人
        autoReviewRltRepayHis(reviewQuotaDisburseHis);
        //新增抵质押信息
        autoMortgageInfoHis(reviewQuotaDisburseHis);
        //新增应收账款转让信息
        dealReviewTransferReceivableToEditPage(reviewQuotaDisburseHis);
        //基础交易合同信息
        autoBasicContract(reviewQuotaDisburseHis);

        return reviewQuotaDisburseHis;
    }

    /**
     * 填充主合同信息历史
     *
     * @param reviewQuotaDisburseHis
     */
    private void autoMasterContractInfoHis(ReviewQuotaDisburseHis reviewQuotaDisburseHis) {
        ReviewMasterContractHis reviewMasterContractHis = reviewMasterContractHisService.getOne(new QueryWrapper<ReviewMasterContractHis>()
                .eq("review_quota_disburse_his_id", reviewQuotaDisburseHis.getId()));
        if (reviewMasterContractHis != null) {
            List<ReviewMasterContractDebtorHis> debtorList = reviewMasterContractDebtorHisService.list(new QueryWrapper<ReviewMasterContractDebtorHis>()
                    .eq("review_master_contract_his_id", reviewMasterContractHis.getId()));
            reviewMasterContractHis.setDebtorHisList(debtorList);
            reviewQuotaDisburseHis.setReviewMasterContractHis(reviewMasterContractHis);
        }
    }


    /**
     * 填充融资信息
     */
    private void autoReviewFinancingInfoHis(ReviewQuotaDisburseHis reviewQuotaDisburseHis) {
        if (null != reviewQuotaDisburseHis && null != reviewQuotaDisburseHis.getId()) {
            ReviewFinancingInfoHis financingInfoHis = reviewFinancingInfoHisService.getOne(new QueryWrapper<ReviewFinancingInfoHis>()
                    .eq("review_quota_disburse_his_id", reviewQuotaDisburseHis.getId()));
            if (null != financingInfoHis) {
                autoPercentageForFinancingInfo(financingInfoHis);
                autoTransferNoticeMethodName(financingInfoHis);
                autoServiceScopeName(financingInfoHis);
                reviewQuotaDisburseHis.setReviewFinancingInfoHis(financingInfoHis);
            }
        }
    }

    /**
     * 填充融资信息的比例
     */
    private void autoPercentageForFinancingInfo(ReviewFinancingInfoHis financingInfoHis) {
        if (null != financingInfoHis) {
            // 融资利率(年化)
            financingInfoHis.setFinancingRate(financingInfoHis.getFinancingRate().multiply(new BigDecimal("100")));
            // 融资比例
            financingInfoHis.setFinancingRatio(financingInfoHis.getFinancingRatio().multiply(new BigDecimal("100")));
            // 对外综合报价
            financingInfoHis.setComprehensiveQuotation(financingInfoHis.getComprehensiveQuotation().multiply(new BigDecimal("100")));
            // 管理费率(年化)
            financingInfoHis.setManagementFeeRatio(financingInfoHis.getManagementFeeRatio().multiply(new BigDecimal("100")));
            // 保证金比例
            financingInfoHis.setMarginRatio(financingInfoHis.getMarginRatio().multiply(new BigDecimal("100")));
            // 逾期利率
            financingInfoHis.setOverdueInterestRate(financingInfoHis.getOverdueInterestRate().multiply(new BigDecimal("100")));
            // 坏账担保比例
            financingInfoHis.setBadDebtGuaranteeRate(financingInfoHis.getBadDebtGuaranteeRate().multiply(new BigDecimal("100")));
        }
    }


    /**
     * 填充融资信息：转让通知方式
     */
    private void autoTransferNoticeMethodName(ReviewFinancingInfoHis financingInfoHis) {
        if (null != financingInfoHis && StringUtil.isNotEmpty(financingInfoHis.getTransferNoticeMethod())) {
            List<String> transferNoticeMethodList = StringUtil.separatorCharacter(financingInfoHis.getTransferNoticeMethod());
            financingInfoHis.setTransferNoticeMethodList(transferNoticeMethodList);
        }
    }

    /**
     * 填充融资信息：服务范围
     */
    private void autoServiceScopeName(ReviewFinancingInfoHis financingInfoHis) {
        if (null != financingInfoHis && StringUtil.isNotEmpty(financingInfoHis.getServiceScope())) {
            List<String> serviceScopeList = StringUtil.separatorCharacter(financingInfoHis.getServiceScope());
            financingInfoHis.setServiceScopeList(serviceScopeList);
        }
    }

    /**
     * 填充收支计划信息
     */
    private void autoIncomeExpenditurePlanHis(ReviewQuotaDisburseHis reviewQuotaDisburseHis) {
        if (null != reviewQuotaDisburseHis && null != reviewQuotaDisburseHis.getId()) {
            List<ReviewIncomeExpenditurePlanHis> list = reviewIncomeExpenditurePlanHisService.list(new QueryWrapper<ReviewIncomeExpenditurePlanHis>()
                    .eq("review_quota_disburse_his_id", reviewQuotaDisburseHis.getId()));
            if (null != list && list.size() > 0) {
                reviewQuotaDisburseHis.setIncomeExpenditurePlanHisList(list);
            }
        }
    }

    /**
     * 填充相关还款责任人信息
     *
     * @param quotaDisburseHis
     */
    private void autoReviewRltRepayHis(ReviewQuotaDisburseHis quotaDisburseHis) {
        if (null != quotaDisburseHis && null != quotaDisburseHis.getId()) {
            List<ReviewRltRepayHis> list = reviewRltRepayHisService.list(new QueryWrapper<ReviewRltRepayHis>()
                    .eq("review_quota_disburse_his_id", quotaDisburseHis.getId()));
            if (null != list && list.size() > 0) {
                list.stream().forEach(reviewRltRepayHis -> {
                    //填充证件照
                    if (reviewRltRepayHis.getGuaranteeCardFrontFileStorageId() != null) {
                        FileStorage fileStorage = fileStorageService.get(reviewRltRepayHis.getGuaranteeCardFrontFileStorageId());
                        reviewRltRepayHis.setGuaranteeCardFrontFileStorage(fileStorage);
                    }
                    if (reviewRltRepayHis.getGuaranteeCardReverseFileStorageId() != null) {
                        FileStorage fileStorage = fileStorageService.get(reviewRltRepayHis.getGuaranteeCardReverseFileStorageId());
                        reviewRltRepayHis.setGuaranteeCardReverseFileStorage(fileStorage);
                    }
                    if (reviewRltRepayHis.getSpouseCardFrontFileStorageId() != null) {
                        FileStorage fileStorage = fileStorageService.get(reviewRltRepayHis.getSpouseCardFrontFileStorageId());
                        reviewRltRepayHis.setSpouseCardFrontFileStorage(fileStorage);
                    }
                    if (reviewRltRepayHis.getSpouseCardReverseFileStorageId() != null) {
                        FileStorage fileStorage = fileStorageService.get(reviewRltRepayHis.getSpouseCardReverseFileStorageId());
                        reviewRltRepayHis.setSpouseCardReverseFileStorage(fileStorage);
                    }
                    //填充附件
                    List<ReviewGuaranteeFileHis> reviewGuaranteeFileHisList = reviewGuaranteeFileHisService.lambdaQuery().eq(ReviewGuaranteeFileHis::getGuaranteeId, reviewRltRepayHis.getId())
                            .eq(ReviewGuaranteeFileHis::getGuaranteeFileType, ConstantConversionUtil.GUARANTEEINFO_FILE).list();
                    if (CollectionUtil.isNotEmpty(reviewGuaranteeFileHisList)) {
                        List<FileStorage> fileStorages = reviewGuaranteeFileHisList.stream().map(reviewGuaranteeSecondFile -> fileStorageService.get(reviewGuaranteeSecondFile.getFileId())).collect(Collectors.toList());
                        reviewRltRepayHis.setFileStorages(fileStorages);
                    }
                    //填充房产信息
                    List<ReviewRltRepayEstateHistory> rltRepayEstateHistoryList = reviewRltRepayEstateHistoryService.lambdaQuery().eq(ReviewRltRepayEstateHistory::getReviewRltRepayId, reviewRltRepayHis.getId()).list();
                    reviewRltRepayHis.setReviewRltRepayEstatesHistory(rltRepayEstateHistoryList);
                    //填充土地信息
                    List<ReviewRltRepayLandHistory> reviewRltRepayLandHistoryList = reviewRltRepayLandHistoryService.lambdaQuery().eq(ReviewRltRepayLandHistory::getReviewRltRepayId, reviewRltRepayHis.getId()).list();
                    reviewRltRepayHis.setReviewRltRepayLandsHistory(reviewRltRepayLandHistoryList);
                    //填充车辆信息
                    List<ReviewRltRepayVehicleHistory> reviewRltRepayVehicleHistoryList = reviewRltRepayVehicleHistoryService.lambdaQuery().eq(ReviewRltRepayVehicleHistory::getReviewRltRepayId, reviewRltRepayHis.getId()).list();
                    reviewRltRepayHis.setReviewRltRepayVehiclesHistory(reviewRltRepayVehicleHistoryList);
                    //填充股权资产信息
                    List<ReviewRltRepayEquityAssetsHistory> reviewRltRepayEquityAssetsHistoryList = reviewRltRepayEquityAssetsHistoryService.lambdaQuery().eq(ReviewRltRepayEquityAssetsHistory::getReviewRltRepayId, reviewRltRepayHis.getId()).list();
                    if (CollectionUtil.isNotEmpty(reviewRltRepayEquityAssetsHistoryList)) {
                        reviewRltRepayEquityAssetsHistoryList.stream().forEach(equityAssets -> equityAssets.setRatio(equityAssets.getRatio().multiply(new BigDecimal("100"))));
                    }
                    reviewRltRepayHis.setReviewRltRepayEquityAssetsHistory(reviewRltRepayEquityAssetsHistoryList);
                    //填充其他资产信息
                    List<ReviewRltRepayOtherAssetsHistory> reviewRltRepayOtherAssetsHistoryList = reviewRltRepayOtherAssetsHistoryService.lambdaQuery().eq(ReviewRltRepayOtherAssetsHistory::getReviewRltRepayId, reviewRltRepayHis.getId()).list();
                    reviewRltRepayHis.setReviewRltRepayOtherAssetsHistory(reviewRltRepayOtherAssetsHistoryList);
                });
                quotaDisburseHis.setRltRepayHisList(list);
            }
        }
    }

    /**
     * 填充抵质押信息
     *
     * @param reviewQuotaDisburseHis
     */
    private void autoMortgageInfoHis(ReviewQuotaDisburseHis reviewQuotaDisburseHis) {
        if (null != reviewQuotaDisburseHis && null != reviewQuotaDisburseHis.getId()) {
            List<ReviewMortgageBasicInfoHis> list = reviewMortgageBasicInfoHisService.findHistoryByQuotaDisburseId(reviewQuotaDisburseHis.getId());
            if (null != list && list.size() > 0) {
                list.forEach(reviewMortgageBasicInfoHis -> {
                    //附件
                    List<ReviewGuaranteeFileHis> reviewGuaranteeFiles = reviewGuaranteeFileHisService.lambdaQuery().eq(ReviewGuaranteeFileHis::getGuaranteeId, reviewMortgageBasicInfoHis.getId())
                            .eq(ReviewGuaranteeFileHis::getGuaranteeFileType, ConstantConversionUtil.MORTGAGEINFORMATION_FILE).list();
                    if (CollectionUtil.isNotEmpty(reviewGuaranteeFiles)) {
                        List<FileStorage> fileStorages = reviewGuaranteeFiles.stream().map(r -> fileStorageService.get(r.getFileId())).collect(Collectors.toList());
                        reviewMortgageBasicInfoHis.setFileStorageList(fileStorages);
                    }
                    //证件文件
                    if (reviewMortgageBasicInfoHis.getCardFrontFileStorageId() != null) {
                        FileStorage fileStorage = fileStorageService.get(reviewMortgageBasicInfoHis.getCardFrontFileStorageId());
                        reviewMortgageBasicInfoHis.setCardFrontFileStorage(fileStorage);
                    }
                    if (reviewMortgageBasicInfoHis.getCardReverseFileStorageId() != null) {
                        FileStorage fileStorage = fileStorageService.get(reviewMortgageBasicInfoHis.getCardReverseFileStorageId());
                        reviewMortgageBasicInfoHis.setCardReverseFileStorage(fileStorage);
                    }
                    //抵押信息填充
                    List<ReviewMortgageCollateralInfoHis> reviewMortgageCollateralInfoHisList = reviewMortgageCollateralInfoHisService.list(new QueryWrapper<ReviewMortgageCollateralInfoHis>()
                            .eq("review_mortgage_basic_his_id", reviewMortgageBasicInfoHis.getId()));
                    if (CollectionUtil.isNotEmpty(reviewMortgageCollateralInfoHisList)) {
                        reviewMortgageCollateralInfoHisList.forEach(reviewMortgageCollateralInfoHis -> {
                            //行政区划
                            if (reviewMortgageCollateralInfoHis.getCollDistrict() != null) {
                                reviewMortgageCollateralInfoHis.setCollDistrictStr(StringUtil.separatorCharacter(reviewMortgageCollateralInfoHis.getCollDistrict()));
                            }
                            //附件
                            List<ReviewGuaranteeFileHis> chattelMortgageFiles = reviewGuaranteeFileHisService.lambdaQuery()
                                    .eq(ReviewGuaranteeFileHis::getGuaranteeId, reviewMortgageCollateralInfoHis.getId())
                                    .eq(ReviewGuaranteeFileHis::getGuaranteeFileType, ConstantConversionUtil.CHATTELMORTGAGE_FILE).list();
                            if (CollectionUtil.isNotEmpty(chattelMortgageFiles)) {
                                List<FileStorage> chattelMortgageFileStorages = chattelMortgageFiles.stream().map(r -> fileStorageService.get(r.getFileId())).collect(Collectors.toList());
                                reviewMortgageCollateralInfoHis.setFileStorageList(chattelMortgageFileStorages);
                            }
                        });
                    }
                    reviewMortgageBasicInfoHis.setMortgageCollateralInfoList(reviewMortgageCollateralInfoHisList);
                    //质押物信息填充
                    List<ReviewMortgagePledgeInfoHis> reviewMortgagePledgeInfoHisList = reviewMortgagePledgeInfoHisService.list(new QueryWrapper<ReviewMortgagePledgeInfoHis>()
                            .eq("review_mortgage_basic_his_id", reviewMortgageBasicInfoHis.getId()));
                    if (CollectionUtil.isNotEmpty(reviewMortgagePledgeInfoHisList)) {
                        reviewMortgagePledgeInfoHisList.forEach(reviewMortgagePledgeInfo -> {
                            reviewMortgagePledgeInfo.setEquityRatio(reviewMortgagePledgeInfo.getEquityRatio().multiply(new BigDecimal("100")));
                            //附件
                            List<ReviewGuaranteeFileHis> pledgeInformationFiles = reviewGuaranteeFileHisService.lambdaQuery()
                                    .eq(ReviewGuaranteeFileHis::getGuaranteeId, reviewMortgagePledgeInfo.getId())
                                    .eq(ReviewGuaranteeFileHis::getGuaranteeFileType, ConstantConversionUtil.PLEDGEINFORMATION_FILE).list();
                            if (CollectionUtil.isNotEmpty(pledgeInformationFiles)) {
                                List<FileStorage> pledgeInformationFilesStorages = pledgeInformationFiles.stream().map(r -> fileStorageService.get(r.getFileId())).collect(Collectors.toList());
                                reviewMortgagePledgeInfo.setFileStorageList(pledgeInformationFilesStorages);
                            }
                        });
                    }
                    reviewMortgageBasicInfoHis.setMortgagePledgeInfoList(reviewMortgagePledgeInfoHisList);
                });
                reviewQuotaDisburseHis.setMortgageBasicInfoHisList(list);
            }
        }
    }

    /**
     * 应收转让信息：更新受让方到额度支用处理页面
     */
    private void dealReviewTransferReceivableToEditPage(ReviewQuotaDisburseHis quota) {
        if (null != quota && null != quota.getId()) {
            ReviewTransferReceivableHis transferReceivableHis = reviewTransferReceivableHisService
                    .getOne(new QueryWrapper<ReviewTransferReceivableHis>().eq("review_quota_disburse_his_id", quota.getId()));
            if (null == transferReceivableHis) {
                transferReceivableHis = new ReviewTransferReceivableHis();
            }
            transferReceivableHis.setTransferee("长安银科商业保理有限公司");
            if (transferReceivableHis.getConfirmMethod() != null) {
                transferReceivableHis.setConfirmMethodList(StringUtil.separatorCharacter(transferReceivableHis.getConfirmMethod()));
            }
            quota.setReviewTransferReceivableHis(transferReceivableHis);
        }
    }

    /**
     * 填充基础交易合同信息
     */
    private void autoBasicContract(ReviewQuotaDisburseHis quota) {
        if (null != quota && null != quota.getId()) {
            List<ReviewBasicContractHis> list = reviewBasicContractHisService
                    .list(new QueryWrapper<ReviewBasicContractHis>().eq("review_quota_disburse_his_id", quota.getId()));
            if (null != list && list.size() > 0) {
                list.stream().forEach(reviewBasicContractHis -> {
                    List<ReviewBasicContractChangeContentHis> changeContentList = reviewBasicContractChangeContentHisService.list(new QueryWrapper<ReviewBasicContractChangeContentHis>()
                            .eq("review_basic_contract_his_id", reviewBasicContractHis.getId()));
                    reviewBasicContractHis.setContractContentList(changeContentList);
                });

                quota.setReviewBasicContractHisList(list);
            }
        }
    }
}
