package com.trade.service.salesorder.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
import com.trade.service.TransStruct;
import com.trade.service.companyrelated.domain.ImporterEntity;
import com.trade.service.companyrelated.service.IImporterEntityService;
import com.trade.service.sales.domain.ContractTerms;
import com.trade.service.sales.dto.SalesContractDto;
import com.trade.service.sales.service.ContractTermsService;
import com.trade.service.sales.service.SalesContractService;
import com.trade.service.salesorder.constant.SaleOrderConstant;
import com.trade.service.salesorder.domain.*;
import com.trade.service.salesorder.mapper.SalesOrderMapper;
import com.trade.service.salesorder.service.*;
import com.trade.service.salesorder.vo.SalesOrderDtlVO;
import com.trade.service.salesorder.vo.SalesOrderGoodsVO;
import com.trade.service.salesorder.vo.SalesOrderSearch;
import com.trade.service.salesorder.vo.SalesOrderVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 销售订单表 服务实现类
 * </p>
 *
 * @author zhangchenm
 * @since 2024-09-06
 */
@Service
public class SalesOrderServiceImpl extends ServiceImpl<SalesOrderMapper, SalesOrder> implements ISalesOrderService {

    private final ISalesOrderGoodsService salesOrderGoodsService;
    private final ISalesOrderInvoiceService salesOrderInvoiceService;
    private final ISalesOrderLogisticsService salesOrderLogisticsService;
    private final ISalesOrderContainerService salesOrderContainerService;
    @Resource
    private TransStruct transStruct;
    @Resource
    private SalesContractService salesContractService;
    @Resource
    private ContractTermsService contractTermsService;
    @Resource
    private IImporterEntityService importerEntityService;

    public SalesOrderServiceImpl(ISalesOrderGoodsService salesOrderGoodsService,
            ISalesOrderInvoiceService salesOrderInvoiceService, ISalesOrderLogisticsService salesOrderLogisticsService,
            ISalesOrderContainerService salesOrderContainerService){
        this.salesOrderGoodsService = salesOrderGoodsService;
        this.salesOrderInvoiceService = salesOrderInvoiceService;
        this.salesOrderLogisticsService = salesOrderLogisticsService;
        this.salesOrderContainerService = salesOrderContainerService;
    }

    @Override
    public PageInfo<SalesOrderVO> queryListBySearch(SalesOrderSearch search) {
        PageHelper.startPage(search.getPage(), search.getRows());
        List<SalesOrderVO> list = this.baseMapper.queryListBySearch(search);
        return new PageInfo<>(list);
    }

    @Override
    public SalesOrderDtlVO getDetail(Long id, boolean is4Update) {
        Optional<SalesOrder> salesOrderOpt = Optional.ofNullable(this.getById(id));
        salesOrderOpt.orElseThrow(() -> new ServiceException("订单不存在", HttpStatus.BAD_REQUEST));
        SalesOrderDtlVO salesOrderDtlVO = new SalesOrderDtlVO();
        SalesOrder salesOrder = salesOrderOpt.get();
        SalesOrderVO salesOrderVO = transStruct.transSalesOrder2SalesOrderVO(salesOrder);
        SalesContractDto salesContract = salesContractService.getSalesContractById(salesOrder.getSaleContractId());
        salesOrderVO.setAgencyEnterpriseName(salesContract.getAgencyEnterpriseName());
        salesOrderVO.setSalesContractName(salesContract.getContractName());
        salesOrderVO.setSalesContractNo(salesContract.getContractNo());
        Optional<ImporterEntity> importerEntity = Optional
                .ofNullable(importerEntityService.getByEntityId(salesOrder.getImporterId()));
        salesOrderDtlVO.setSalesOrderVO(salesOrderVO);
        importerEntity.ifPresent(e -> salesOrderVO.setImporterName(e.getEntityName()));
        List<SalesOrderGoodsVO> salesOrderGoodsList = salesOrderGoodsService.listByOrderId(id);
        salesOrderDtlVO.setSalesOrderGoodsList(salesOrderGoodsList);
        if (is4Update) {
            return salesOrderDtlVO;
        }
        Optional<SalesOrderLogistics> orderLogisticsOptional = Optional
                .ofNullable(salesOrderLogisticsService.getByOrderId(salesOrder.getId()));
        if (orderLogisticsOptional.isPresent()) {
            SalesOrderLogistics orderLogistics = orderLogisticsOptional.get();
            salesOrderDtlVO.setSalesOrderLogistics(orderLogistics);
            List<SalesOrderContainer> containers = salesOrderContainerService.listByLogisticsId(orderLogistics.getId());
            salesOrderDtlVO.setSalesOrderContainerList(containers);
        }
        Optional<SalesOrderInvoice> orderInvoiceOptional = Optional
                .ofNullable(salesOrderInvoiceService.getByOrderId(salesOrder.getId()));
        orderInvoiceOptional.ifPresent(salesOrderDtlVO::setSalesOrderInvoice);
        Optional<ContractTerms> contractTermsOpt = Optional.ofNullable(contractTermsService.lambdaQuery()
                .eq(ContractTerms::getContractNo, salesContract.getContractNo()).one());
        contractTermsOpt.ifPresent(e -> {
            salesOrderDtlVO.setSalesOrderPayInfoVO(transStruct.transContractTerms2SalesOrderPayInfoVO(e));
            salesOrderVO.setPaymentWay(e.getPaymentWay());
            salesOrderVO.setSettlementCycle(e.getSettlementCycle());
        });
        return salesOrderDtlVO;
    }

    @Override
    public Long saveSalesOrder(SalesOrder salesOrder) {
        this.save(salesOrder);
        return salesOrder.getId();
    }

    @Override
    public boolean existSalesOrderByImporterId(Long importerId) {
        return this.count(new QueryWrapper<SalesOrder>().eq("importer_id", importerId)) > 0;
    }
}
