/**
 * @filename:SalesContractServiceImpl 2024-09-03
 * @project KJT v1.0.0 Copyright(c) 2024 wanglang Co. Ltd. All right reserved.
 */
package com.trade.service.sales.service.impl;

import com.trade.common.constant.HttpStatus;
import com.trade.common.enums.ContractStatus;
import com.trade.common.enums.SubmitStatus;
import com.trade.common.exception.ValidatorException;
import com.trade.service.enterprise.domain.Enterprise;
import com.trade.service.enterprise.service.EnterpriseBaseService;
import com.trade.common.utils.ConstantUtil;
import com.trade.service.filestorage.entity.TFileStorage;
import com.trade.service.filestorage.service.LocalFileService;
import com.trade.service.sales.domain.*;
import com.trade.service.sales.dto.ContractFileDto;
import com.trade.service.sales.dto.ContractSearchDto;
import com.trade.service.sales.dto.ContractTermsDto;
import com.trade.service.sales.dto.SalesContractDto;
import com.trade.service.sales.mapper.SalesContractMapper;
import com.trade.service.sales.service.*;
import com.trade.service.sales.vo.SalesContractInfoVo;
import com.trade.service.sales.vo.SalesContractVo;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:销售合同基础信息服务实现
 * @version: v1.0.0
 * @author: wanglang
 */
@Service
public class SalesContractServiceImpl extends ServiceImpl<SalesContractMapper, SalesContract> implements SalesContractService {

    @Resource
    private SalesDataConverter salesDataConverter;
    @Resource
    private SalesCommodityService salesCommodityService;
    @Resource
    private ContractFileService contractFileService;
    @Resource
    private LocalFileService localFileService;
    @Resource
    private ContractTermsService contractTermsService;
    @Resource
    private ContractTermsExtendService contractTermsExtendService;
    @Resource
    private EnterpriseBaseService enterpriseBaseService;

    @Override
    public SalesContractInfoVo getSalesContractDetails(Long contractId) {
        SalesContract salesContract = this.baseMapper.selectById(contractId);
        if (salesContract == null) {
            throw new ValidatorException(HttpStatus.ERROR, "销售合同不存在！");
        }
        SalesContractInfoVo salesContractInfoVo = new SalesContractInfoVo();
        SalesContractDto salesContractDto = salesDataConverter.convertSalesContractDto(salesContract);
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(salesContract.getCustomerUserId());
        salesContractDto.setExportType(enterprise.getExportType());
        List<SalesCommodity> salesCommodities = salesCommodityService.queryBySalesContractId(salesContractDto.getId());
        BigDecimal amount = salesCommodities.stream().map(SalesCommodity::getAmount).reduce(BigDecimal::add)
                .orElse(BigDecimal.ZERO);
        salesContractDto.setContractAmount(amount);
        salesContractInfoVo.setSalesContract(salesContractDto);
        salesContractInfoVo.setSalesCommoditys(salesDataConverter.convertCommodityDto(salesCommodities));
        ContractFile contractFile = contractFileService.lambdaQuery()
                .eq(ContractFile::getContractNo, salesContractDto.getContractNo()).eq(ContractFile::getDeleted, 0)
                .one();
        ContractFileDto contractFileDto = new ContractFileDto();
        TFileStorage fileStorage;
        if (ContractStatus.TAKE_EFFECT.getCode().equals(salesContractDto.getContractStatus())
                || ContractStatus.COMPLETED.getCode().equals(salesContractDto.getContractStatus())) {
            fileStorage = localFileService.getFileById(contractFile.getSignedFileStorageId());
            contractFileDto.setFileId(contractFile.getSignedFileStorageId());
        } else {
            contractFileDto.setFileId(contractFile.getUnsignFileStorageId());
            fileStorage = localFileService.getFileById(contractFile.getUnsignFileStorageId());
            contractFileDto.setFileId(contractFile.getSignedFileStorageId());
        }
        contractFileDto.setPath(fileStorage.getOriginalName());
        salesContractInfoVo.setContractFile(contractFileDto);
        ContractTermsDto contractTermsDto = contractTermsService.getDetailByContractIdAndType(contractId,
                ConstantUtil.SALES_CONTRACT_NO_PREFIX);
        salesContractInfoVo.setContractTermsDto(contractTermsDto);
        return salesContractInfoVo;
    }

    @Override
    public List<SalesContractVo> getSalesContractInfo(ContractSearchDto contractSearch) {
        List<SalesContractVo> salesContractVos = this.baseMapper.selectByCondition(contractSearch);
        salesContractVos.forEach(salesContractVo -> {
            List<SalesCommodity> salesCommodities = salesCommodityService
                    .queryBySalesContractId(salesContractVo.getId());
            BigDecimal amount = salesCommodities.stream().map(SalesCommodity::getAmount).reduce(BigDecimal::add)
                    .orElse(BigDecimal.ZERO);
            salesContractVo.setContractAmount(amount);
        });
        return salesContractVos;
    }

    @Override
    public Boolean deleteSalesContract(Long contractId) {
        SalesContract salesContract = this.baseMapper.selectById(contractId);
        if (!SubmitStatus.DRAFT.getCode().equals(salesContract.getSubmitStatus())) {
            throw new ValidatorException(HttpStatus.ERROR, "非草稿状态销售合同不允许删除！");
        }
        salesContract.setDeleted(1);
        List<SalesCommodity> salesCommodities = salesCommodityService.lambdaQuery()
                .eq(SalesCommodity::getSalesContractId, salesContract.getId()).list();
        salesCommodities.forEach(salesCommodity -> {
            salesCommodity.setDeleted(1);
        });
        ContractFile contractFile = contractFileService.lambdaQuery()
                .eq(ContractFile::getContractNo, salesContract.getContractNo()).eq(ContractFile::getDeleted, 0).one();
        contractFile.setDeleted(1);
        ContractTerms contractTerms = contractTermsService.getByContractNo(salesContract.getContractNo());
        contractTerms.setDeleted(1);
        List<ContractTermsExtend> contractTermsExtends = contractTermsExtendService.lambdaQuery()
                .eq(ContractTermsExtend::getContractTermsId, contractTerms.getId()).list();
        contractTermsExtends.forEach(contractTermsExtend -> {
            contractTermsExtend.setDeleted(1);
        });
        this.baseMapper.updateById(salesContract);
        salesCommodityService.updateBatchById(salesCommodities);
        contractFileService.updateById(contractFile);
        contractTermsService.updateById(contractTerms);
        contractTermsExtendService.updateBatchById(contractTermsExtends);
        return true;
    }

    @Override
    public SalesContractDto getSalesContractById(Long contractId) {
        SalesContract salesContract = this.baseMapper.selectById(contractId);
        if (salesContract == null) {
            throw new ValidatorException(HttpStatus.ERROR, "销售合同不存在！");
        }
        return salesDataConverter.convertSalesContractDto(salesContract);
    }

    @Override
    public List<SalesContractVo> querySalesContractByCustomerUserId(Long customerUserId) {
        ContractSearchDto contractSearch = new ContractSearchDto();
        contractSearch.setCustomerUserId(customerUserId);
        return this.baseMapper.selectByCondition(contractSearch).stream()
                .filter(e -> ContractStatus.COMPLETED.getCode().equals(e.getContractStatus()))
                .collect(Collectors.toList());
    }
}
