package com.sunxung.factoring.service.purchcontractmanagement.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.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.purchcontractmanagement.*;
import com.sunxung.factoring.entity.purchcontractmanagement.vo.PurchContractApprovalVo;
import com.sunxung.factoring.entity.purchcontractmanagement.vo.PurchContractVo;
import com.sunxung.factoring.entity.salescontractmanagement.vo.SalesContractBasicVo;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.mapper.purchcontractmanagement.PurchContractBasicInfoMapper;
import com.sunxung.factoring.service.businessmanagement.BusinessBasicInfoService;
import com.sunxung.factoring.service.customerinformation.CustomerService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.purchcontractmanagement.*;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractGoodsInfoService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description : 采购合同基础信息service实现类
 * @Author : JiaYf
 * @Date: 2021-09-15 9:46
 */
@Service("purch_contract_createService")
public class PurchContractBasicInfoServiceImpl extends ServiceImpl<PurchContractBasicInfoMapper, PurchContractBasicInfo>
        implements PurchContractBasicInfoService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private PurchContractService purchContractService;

    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;

    @Autowired
    private BusinessBasicInfoService businessBasicInfoService;

    @Autowired
    private PurchContractPaymentConditionService purchContractPaymentConditionService;

    @Autowired
    private PurchContractSettleCycleService purchContractSettleCycleService;

    @Autowired
    private PurchContractRetentionInfoService purchContractRetentionInfoService;

    @Autowired
    private PurchContractPriceRuleService purchContractPriceRuleService;

    @Autowired
    private PurchContractGoodsInfoService purchContractGoodsInfoService;

    @Autowired
    private SalesContractGoodsInfoService salesContractGoodsInfoService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private PurchContractReplenishInfoService purchContractReplenishInfoService;

    @Autowired
    private PurchContractQualityAcceptService purchContractQualityAcceptService;

    @Autowired
    private PurchContractSettlePaymentService purchContractSettlePaymentService;

    @Autowired
    private PurchContractDeliverClauseService purchContractDeliverClauseService;

    @Autowired
    private PurchContractSellerBlameService purchContractSellerBlameService;

    @Autowired
    private PurchContractPunishClauseService purchContractPunishClauseService;

    @Autowired
    private PurchContractOtherClauseService purchContractOtherClauseService;

    @Autowired
    private PurchContractApprovalService purchContractApprovalService;

    @Autowired
    private IPurchContractBuyerSellerService purchContractBuyerSellerService;

    @Autowired
    private IPurchContractBasicInfoHistoryService purchContractBasicInfoHistoryService;

    @Autowired
    private IPurchContractPaymentConditionHistoryService purchContractPaymentConditionHistoryService;

    @Autowired
    private IPurchContractRetentionInfoHistoryService purchContractRetentionInfoHistoryService;

    @Autowired
    private IPurchContractPriceRuleHistoryService purchContractPriceRuleHistoryService;

    @Autowired
    private IPurchContractGoodsInfoHistoryService purchContractGoodsInfoHistoryService;

    @Autowired
    private IPurchContractSettlePaymentHistoryService purchContractSettlePaymentHistoryService;

    @Autowired
    private IPurchContractBuyerSellerHistoryService purchContractBuyerSellerHistoryService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private PlatformService platformService;

    @Override
    public PurchContractBasicInfo getLatestBasicInfo(Long purchContractManageId, String conclusion) {
        return baseMapper.getLatestBasicInfo(purchContractManageId, conclusion);
    }

    @Override
    public PurchContractApprovalVo getDetail(Long id) {
        PurchContractApprovalVo purchContractApprovalVo = new PurchContractApprovalVo();
        PurchContractBasicInfo purchContractBasicInfo = baseMapper.getDetail(id);
        PurchContractApproval purchContractApproval = null;
        PurchContractManagement purchContractManagement = purchContractService.getById(purchContractBasicInfo.getPurchContractManagementId());
        purchContractApproval = purchContractApprovalService.getLatestPurchContractApproval(purchContractBasicInfo.getId(), 1);
        purchContractApprovalVo.setPurchContractBasicInfo(purchContractBasicInfo);
        //如果业务第二次提交，查询之前合同信息录入的最新审核信息
        if (purchContractApproval == null) {
            List<PurchContractBasicInfo> purchBasicList = purchContractBasicInfoService.list(new QueryWrapper<PurchContractBasicInfo>().eq("purch_contract_management_id", purchContractManagement.getId()));
            if (purchBasicList.size() > 1) {
                //取第二个最新合同基本信息，查询最新它对应的最新审核信息
                purchContractApproval = purchContractApprovalService.getLatestPurchContractApproval(purchBasicList.get(1).getId(), 1);
            }
        }

        //根据采购合同审核表ID,获取合同其他信息
        if (purchContractApproval != null && purchContractApproval.getId() != null) {
            //获取合同补充信息
            PurchContractReplenishInfo replenishInfo = purchContractReplenishInfoService.findByPurchContBasicId(purchContractBasicInfo.getId());
            //获取增值税要求
//            PurchContractVatInfo vatInfo = purchContractVatInfoService.findByPurchContApprId(purchContractBasicInfo.getId());
            //获取质量与验收
            PurchContractQualityAccept qualityAccept = purchContractQualityAcceptService
                    .lambdaQuery().eq(PurchContractQualityAccept::getPurchContractApprovalId, purchContractApproval.getId()).one();
            //获取结算与付款
//            PurchContractSettlePayment settlePayment = purchContractSettlePaymentService.findByPurchContApprId(purchContractBasicInfo.getId());
            //获取交货规定
            PurchContractDeliverClause deliverClause = purchContractDeliverClauseService
                    .lambdaQuery().eq(PurchContractDeliverClause::getPurchContractApprovalId, purchContractBasicInfo.getId()).one();
            //获取供货商责任
            PurchContractSellerBlame sellerBlame = purchContractSellerBlameService.findByPurchContApprId(purchContractBasicInfo.getId());
            //获取其他条款
            List<PurchContractOtherClause> otherClauseList = purchContractOtherClauseService.findByPurchContApprId(purchContractBasicInfo.getId());

            purchContractApprovalVo.setPurchContractReplenishInfo(replenishInfo);
            purchContractApprovalVo.setPurchContractQualityAccept(qualityAccept);
            purchContractApprovalVo.setPurchContractDeliverClause(deliverClause);
//            purchContractApprovalVo.set(punishClause);
            purchContractApprovalVo.setPurchContractOtherClause(otherClauseList);

        }

        return purchContractApprovalVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFileByPurchContractId(Long purchContractId) {
        List<Long> fileIdList = baseMapper.findFileIdByPurchContractId(purchContractId);
        baseMapper.deleteFileRef(purchContractId, null);
        if (null != fileIdList && fileIdList.size() > 0) {
            for (Long fileId : fileIdList) {
                // 循环删除附件表中的数据
                fileStorageService.delete(fileId);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addFileRef(Long purchContractId, Long fileId) {
        baseMapper.addFileRef(purchContractId, fileId);
    }

    @Override
    public PurchContractVo getView(Long id) {
        PurchContractVo purchContractVo = new PurchContractVo();
        PurchContractBasicInfoHistory purchContractBasicInfoHistory = purchContractBasicInfoHistoryService.getById(id);
        if (purchContractBasicInfoHistory != null && purchContractBasicInfoHistory.getId() != null) {

            PurchContractManagement purchContractManagement = purchContractService.getById(purchContractBasicInfoHistory.getPurchContractManagementId());
            if (purchContractManagement != null && purchContractManagement.getId() != null) {


                PurchContractBasicInfo purchContractBasicInfo = new PurchContractBasicInfo();
                BeanUtils.copyProperties(purchContractBasicInfoHistory, purchContractBasicInfo);

                SalesContractBasicVo basicVo = new SalesContractBasicVo();
                basicVo.setBusinessNumber(purchContractManagement.getBusinessNumber());
                basicVo.setProjectName(purchContractBasicInfo.getProjectName());
                basicVo.setMainEnterprise(purchContractBasicInfo.getSupplierName());
                basicVo.setEnterprise(purchContractBasicInfo.getBuyerName());
                Platform platform = platformService.getById(purchContractBasicInfo.getTradingPlatformId());
                if (platform != null) {
                    basicVo.setPlatformName(platform.getPlatformName());
                }
                purchContractVo.setBasicInfo(basicVo);

                if (purchContractBasicInfo.getRepurchMethod() != null) {
                    purchContractBasicInfo.setRepurchMethodDic(dictionaryService.getByCode(purchContractBasicInfo.getRepurchMethod()));
                }
                purchContractVo.setPurchContractBasicInfo(purchContractBasicInfo);

                //根据采购合同获取其他信息
                //获取质保金
                PurchContractRetentionInfoHistory purchContractRetentionInfoHistory = purchContractRetentionInfoHistoryService.getOne(
                        new QueryWrapper<PurchContractRetentionInfoHistory>().eq("purch_contract_basic_info_history_id", id)
                );
                if (purchContractRetentionInfoHistory != null) {
                    PurchContractRetentionInfo purchContractRetentionInfo = new PurchContractRetentionInfo();
                    BeanUtils.copyProperties(purchContractRetentionInfoHistory, purchContractRetentionInfo);
                    purchContractVo.setPurchContractRetentionInfo(purchContractRetentionInfo);
                }
                //结算与付款
                PurchContractSettlePaymentHistory purchContractSettlePaymentHistory = purchContractSettlePaymentHistoryService
                        .lambdaQuery().eq(PurchContractSettlePaymentHistory::getPurchContractBasicInfoHisId, id).one();
                if (purchContractSettlePaymentHistory != null) {
                    PurchContractSettlePayment purchContractSettlePayment = new PurchContractSettlePayment();
                    BeanUtils.copyProperties(purchContractSettlePaymentHistory, purchContractSettlePayment);
                    purchContractVo.setPurchContractSettlePayment(purchContractSettlePayment);
                }
                //获取价格规则
                PurchContractPriceRuleHistory purchContractPriceRuleHistory = purchContractPriceRuleHistoryService.getOne(
                        new QueryWrapper<PurchContractPriceRuleHistory>().eq("purch_contract_basic_info_history_id", id)
                );
                if (purchContractPriceRuleHistory != null) {
                    PurchContractPriceRule purchContractPriceRule = new PurchContractPriceRule();
                    BeanUtils.copyProperties(purchContractPriceRuleHistory, purchContractPriceRule);
                    purchContractVo.setPurchContractPriceRule(purchContractPriceRule);
                }
                //获取货物信息
                List<PurchContractGoodsInfoHistory> purchContractGoodsInfoHistoryList = purchContractGoodsInfoHistoryService.list(
                        new QueryWrapper<PurchContractGoodsInfoHistory>().eq("purch_contract_basic_info_history_id", id)
                );
                List<PurchContractGoodsInfo> purchContractGoodsInfoList = new ArrayList<>();
                if (purchContractGoodsInfoHistoryList != null && purchContractGoodsInfoHistoryList.size() > 0) {
                    for (PurchContractGoodsInfoHistory purchContractGoodsInfoHistory : purchContractGoodsInfoHistoryList) {
                        PurchContractGoodsInfo purchContractGoodsInfo = new PurchContractGoodsInfo();
                        BeanUtils.copyProperties(purchContractGoodsInfoHistory, purchContractGoodsInfo);
                        purchContractGoodsInfoList.add(purchContractGoodsInfo);
                    }
                }
                purchContractVo.setPurchContractGoodsInfoList(purchContractGoodsInfoList);


                //获取发货人
                List<PurchContractBuyerSellerHistory> purchContractSellerHistoryList = purchContractBuyerSellerHistoryService.list(
                        new QueryWrapper<PurchContractBuyerSellerHistory>().eq("purch_contract_basic_info_history_id", id));
                List<PurchContractBuyerSeller> purchContractBuyerSellerList = new ArrayList<>();
                if (purchContractSellerHistoryList != null && purchContractSellerHistoryList.size() > 0) {
                    for (PurchContractBuyerSellerHistory purchContractBuyerSellerHistory : purchContractSellerHistoryList) {
                        PurchContractBuyerSeller purchContractBuyerSeller = new PurchContractBuyerSeller();
                        BeanUtils.copyProperties(purchContractBuyerSellerHistory, purchContractBuyerSeller);
                        purchContractBuyerSellerList.add(purchContractBuyerSeller);
                    }
                    purchContractVo.setPurchContractBuyerSellerList(purchContractBuyerSellerList);
                }
            }
        }
        return purchContractVo;
    }

    @Override
    public PurchContractBasicInfo findByBusinessNumberAndSupplierId(String businessNumber, Long supplierId) {
        ProjectInformation projectInformation = projectInformationService.getOne(new QueryWrapper<ProjectInformation>()
                .eq("business_number", businessNumber));
        PurchContractManagement purchContractManagement = purchContractService.getOne(
                new QueryWrapper<PurchContractManagement>()
                        .eq("business_number", businessNumber)
                        .eq("supplier_id", supplierId));
        if (purchContractManagement == null || purchContractManagement.getId() == null) {
            throw new BusinessException(CodeUtil.FAIL, "采购合同管理不能为空");
        }
        PurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService
                .lambdaQuery().eq(PurchContractBasicInfo::getPurchContractManagementId, purchContractManagement.getId()).one();

        if (purchContractBasicInfo == null || purchContractBasicInfo.getId() == null) {
            throw new BusinessException(CodeUtil.FAIL, "采购合同基础信息不能为空");
        }
        purchContractBasicInfo.setProjectInformation(projectInformation);
        return purchContractBasicInfo;
    }

}
