/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2019 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.axelor.apps.supplychain.service;

import static com.axelor.apps.base.service.administration.AbstractBatch.FETCH_LIMIT;

import com.axelor.apps.account.db.Account;
import com.axelor.apps.account.db.AccountConfig;
import com.axelor.apps.account.db.AccountManagement;
import com.axelor.apps.account.db.AnalyticDistributionTemplate;
import com.axelor.apps.account.db.AnalyticMoveLine;
import com.axelor.apps.account.db.Journal;
import com.axelor.apps.account.db.Move;
import com.axelor.apps.account.db.MoveLine;
import com.axelor.apps.account.db.Tax;
import com.axelor.apps.account.db.TaxLine;
import com.axelor.apps.account.db.repo.AccountManagementRepository;
import com.axelor.apps.account.db.repo.AccountRepository;
import com.axelor.apps.account.db.repo.AnalyticMoveLineRepository;
import com.axelor.apps.account.db.repo.JournalRepository;
import com.axelor.apps.account.db.repo.MoveRepository;
import com.axelor.apps.account.exception.IExceptionMessage;
import com.axelor.apps.account.service.AccountManagementAccountService;
import com.axelor.apps.account.service.AnalyticMoveLineService;
import com.axelor.apps.account.service.ReconcileService;
import com.axelor.apps.account.service.TaxAccountService;
import com.axelor.apps.account.service.app.AppAccountService;
import com.axelor.apps.account.service.invoice.generator.line.InvoiceLineManagement;
import com.axelor.apps.account.service.move.MoveCreateService;
import com.axelor.apps.account.service.move.MoveLineService;
import com.axelor.apps.account.service.move.MoveToolService;
import com.axelor.apps.account.service.move.MoveValidateService;
import com.axelor.apps.base.db.Batch;
import com.axelor.apps.base.db.Company;
import com.axelor.apps.base.db.Currency;
import com.axelor.apps.base.db.Partner;
import com.axelor.apps.base.db.Product;
import com.axelor.apps.base.db.repo.AppAccountRepository;
import com.axelor.apps.base.service.UnitConversionService;
import com.axelor.apps.purchase.db.PurchaseOrder;
import com.axelor.apps.purchase.db.PurchaseOrderLine;
import com.axelor.apps.purchase.db.repo.PurchaseOrderRepository;
import com.axelor.apps.sale.db.SaleOrder;
import com.axelor.apps.sale.db.SaleOrderLine;
import com.axelor.apps.sale.db.repo.SaleOrderRepository;
import com.axelor.apps.stock.db.InventoryLine;
import com.axelor.apps.stock.db.StockMove;
import com.axelor.apps.stock.db.StockMoveLine;
import com.axelor.apps.stock.db.repo.InventoryLineRepository;
import com.axelor.apps.stock.db.repo.StockLocationRepository;
import com.axelor.apps.stock.db.repo.StockMoveLineRepository;
import com.axelor.apps.stock.db.repo.StockMoveRepository;
import com.axelor.apps.supplychain.db.repo.SupplychainBatchRepository;
import com.axelor.apps.supplychain.service.config.AccountConfigSupplychainService;
import com.axelor.db.JPA;
import com.axelor.db.Query;
import com.axelor.exception.AxelorException;
import com.axelor.exception.db.repo.TraceBackRepository;
import com.axelor.i18n.I18n;
import com.axelor.inject.Beans;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class AccountingCutOffServiceImpl implements AccountingCutOffService {

  protected StockMoveRepository stockMoverepository;
  protected StockMoveLineRepository stockMoveLineRepository;
  protected MoveCreateService moveCreateService;
  protected MoveLineService moveLineService;
  protected AccountConfigSupplychainService accountConfigSupplychainService;
  protected SaleOrderRepository saleOrderRepository;
  protected PurchaseOrderRepository purchaseOrderRepository;
  protected MoveToolService moveToolService;
  protected AccountManagementAccountService accountManagementAccountService;
  protected TaxAccountService taxAccountService;
  protected AppAccountService appAccountService;
  protected AnalyticMoveLineService analyticMoveLineService;
  protected MoveRepository moveRepository;
  protected MoveValidateService moveValidateService;
  protected UnitConversionService unitConversionService;
  protected AnalyticMoveLineRepository analyticMoveLineRepository;
  protected ReconcileService reconcileService;
  protected int counter = 0;

  @Inject
  public AccountingCutOffServiceImpl(
      StockMoveRepository stockMoverepository,
      StockMoveLineRepository stockMoveLineRepository,
      MoveCreateService moveCreateService,
      MoveLineService moveLineService,
      AccountConfigSupplychainService accountConfigSupplychainService,
      SaleOrderRepository saleOrderRepository,
      PurchaseOrderRepository purchaseOrderRepository,
      MoveToolService moveToolService,
      AccountManagementAccountService accountManagementAccountService,
      TaxAccountService taxAccountService,
      AppAccountService appAccountService,
      AnalyticMoveLineService analyticMoveLineService,
      MoveRepository moveRepository,
      MoveValidateService moveValidateService,
      UnitConversionService unitConversionService,
      AnalyticMoveLineRepository analyticMoveLineRepository,
      ReconcileService reconcileService) {

    this.stockMoverepository = stockMoverepository;
    this.stockMoveLineRepository = stockMoveLineRepository;
    this.moveCreateService = moveCreateService;
    this.moveLineService = moveLineService;
    this.accountConfigSupplychainService = accountConfigSupplychainService;
    this.saleOrderRepository = saleOrderRepository;
    this.purchaseOrderRepository = purchaseOrderRepository;
    this.moveToolService = moveToolService;
    this.accountManagementAccountService = accountManagementAccountService;
    this.taxAccountService = taxAccountService;
    this.appAccountService = appAccountService;
    this.analyticMoveLineService = analyticMoveLineService;
    this.moveRepository = moveRepository;
    this.moveValidateService = moveValidateService;
    this.unitConversionService = unitConversionService;
    this.analyticMoveLineRepository = analyticMoveLineRepository;
    this.reconcileService = reconcileService;
  }

  public List<StockMove> getStockMoves(
      Company company,
      int accountingCutOffTypeSelect,
      LocalDate moveDate,
      Integer limit,
      Integer offset) {

    int stockMoveTypeSelect = 0;

    if (accountingCutOffTypeSelect
        == SupplychainBatchRepository.ACCOUNTING_CUT_OFF_TYPE_SUPPLIER_INVOICES) {
      stockMoveTypeSelect = StockMoveRepository.TYPE_INCOMING;
    } else if (accountingCutOffTypeSelect
        == SupplychainBatchRepository.ACCOUNTING_CUT_OFF_TYPE_CUSTOMER_INVOICES) {
      stockMoveTypeSelect = StockMoveRepository.TYPE_OUTGOING;
    }

    String queryStr =
        " self.statusSelect = :stockMoveStatusRealized and self.realDate <= :moveDate "
            + "AND self.typeSelect = :stockMoveType ";

    if (company != null) {
      queryStr += "AND self.company.id = :companyId";
    }

    Query<StockMove> query =
        stockMoverepository
            .all()
            .filter(queryStr)
            .bind("stockMoveStatusRealized", StockMoveRepository.STATUS_REALIZED)
            .bind("stockMoveType", stockMoveTypeSelect)
            .bind("moveDate", moveDate);

    if (company != null) {
      query.bind("companyId", company.getId());
    }

    if (limit != null && offset != null) {
      return query.order("id").fetch(limit, offset);
    }

    return query.order("id").fetch();
  }

  @Transactional(rollbackOn = {Exception.class})
  public List<Move> generateCutOffMoves(
      StockMove stockMove,
      LocalDate moveDate,
      LocalDate reverseMoveDate,
      int accountingCutOffTypeSelect,
      boolean recoveredTax,
      boolean ati,
      String moveDescription,
      boolean includeNotStockManagedProduct)
      throws AxelorException {

    List<Move> moveList = new ArrayList<>();

    List<StockMoveLine> stockMoveLineSortedList = stockMove.getStockMoveLineList();
    Collections.sort(stockMoveLineSortedList, Comparator.comparing(StockMoveLine::getSequence));

    Move move =
        generateCutOffMove(
            stockMove,
            stockMoveLineSortedList,
            moveDate,
            moveDate,
            accountingCutOffTypeSelect
                == SupplychainBatchRepository.ACCOUNTING_CUT_OFF_TYPE_SUPPLIER_INVOICES,
            recoveredTax,
            ati,
            moveDescription,
            includeNotStockManagedProduct,
            false);

    if (move == null) {
      return null;
    }
    moveList.add(move);

    Move reverseMove =
        generateCutOffMove(
            stockMove,
            stockMoveLineSortedList,
            reverseMoveDate,
            moveDate,
            accountingCutOffTypeSelect
                == SupplychainBatchRepository.ACCOUNTING_CUT_OFF_TYPE_SUPPLIER_INVOICES,
            recoveredTax,
            ati,
            moveDescription,
            includeNotStockManagedProduct,
            true);

    if (reverseMove == null) {
      return null;
    }
    moveList.add(reverseMove);

    reconcile(move, reverseMove);

    return moveList;
  }

  public Move generateCutOffMove(
      StockMove stockMove,
      List<StockMoveLine> sortedStockMoveLine,
      LocalDate moveDate,
      LocalDate originDate,
      boolean isPurchase,
      boolean recoveredTax,
      boolean ati,
      String moveDescription,
      boolean includeNotStockManagedProduct,
      boolean isReverse)
      throws AxelorException {

    if (moveDate == null
        || stockMove.getOriginTypeSelect() == null
        || stockMove.getOriginId() == null) {
      return null;
    }

    Company company = stockMove.getCompany();

    AccountConfig accountConfig = accountConfigSupplychainService.getAccountConfig(company);

    Partner partner = stockMove.getPartner();
    Account partnerAccount = null;

    Currency currency = null;
    if (StockMoveRepository.ORIGIN_SALE_ORDER.equals(stockMove.getOriginTypeSelect())
        && stockMove.getOriginId() != null) {
      SaleOrder saleOrder = saleOrderRepository.find(stockMove.getOriginId());
      currency = saleOrder.getCurrency();
      if (partner == null) {
        partner = saleOrder.getClientPartner();
      }
      partnerAccount = accountConfigSupplychainService.getForecastedInvCustAccount(accountConfig);
    }
    if (StockMoveRepository.ORIGIN_PURCHASE_ORDER.equals(stockMove.getOriginTypeSelect())
        && stockMove.getOriginId() != null) {
      PurchaseOrder purchaseOrder = purchaseOrderRepository.find(stockMove.getOriginId());
      currency = purchaseOrder.getCurrency();
      if (partner == null) {
        partner = purchaseOrder.getSupplierPartner();
      }
      partnerAccount = accountConfigSupplychainService.getForecastedInvSuppAccount(accountConfig);
    }

    String origin = stockMove.getStockMoveSeq();

    Move move =
        moveCreateService.createMove(
            accountConfigSupplychainService.getAutoMiscOpeJournal(accountConfig),
            company,
            currency,
            partner,
            moveDate,
            null,
            MoveRepository.TECHNICAL_ORIGIN_AUTOMATIC);

    counter = 0;

    this.generateMoveLines(
        move,
        stockMove.getStockMoveLineList(),
        origin,
        isPurchase,
        recoveredTax,
        ati,
        moveDescription,
        isReverse,
        originDate,
        includeNotStockManagedProduct);

    this.generatePartnerMoveLine(move, origin, partnerAccount, moveDescription, originDate);

    if (move.getMoveLineList() != null && !move.getMoveLineList().isEmpty()) {
      move.setStockMove(stockMove);
      moveValidateService.validate(move);
    } else {
      moveRepository.remove(move);
      return null;
    }

    return move;
  }

  protected List<MoveLine> generateMoveLines(
      Move move,
      List<StockMoveLine> stockMoveLineList,
      String origin,
      boolean isPurchase,
      boolean recoveredTax,
      boolean ati,
      String moveDescription,
      boolean isReverse,
      LocalDate originDate,
      boolean includeNotStockManagedProduct)
      throws AxelorException {

    if (stockMoveLineList != null) {

      for (StockMoveLine stockMoveLine : stockMoveLineList) {

        Product product = stockMoveLine.getProduct();

        if (checkStockMoveLine(stockMoveLine, product, includeNotStockManagedProduct)) {
          continue;
        }

        generateProductMoveLine(
            move,
            stockMoveLine,
            origin,
            isPurchase,
            recoveredTax,
            ati,
            moveDescription,
            isReverse,
            originDate);
      }
    }

    return move.getMoveLineList();
  }

  protected boolean checkStockMoveLine(
      StockMoveLine stockMoveLine, Product product, boolean includeNotStockManagedProduct) {
    return (stockMoveLine.getRealQty().compareTo(BigDecimal.ZERO) == 0
            || product == null
            || (!includeNotStockManagedProduct && !product.getStockManaged()))
        || (stockMoveLine.getRealQty().compareTo(stockMoveLine.getQtyInvoiced()) == 0);
  }

  protected MoveLine generateProductMoveLine(
      Move move,
      StockMoveLine stockMoveLine,
      String origin,
      boolean isPurchase,
      boolean recoveredTax,
      boolean ati,
      String moveDescription,
      boolean isReverse,
      LocalDate originDate)
      throws AxelorException {

    SaleOrderLine saleOrderLine = stockMoveLine.getSaleOrderLine();
    PurchaseOrderLine purchaseOrderLine = stockMoveLine.getPurchaseOrderLine();
    Company company = move.getCompany();
    LocalDate moveDate = move.getDate();
    Partner partner = move.getPartner();

    boolean isFixedAssets = false;
    BigDecimal amountInCurrency = null;
    BigDecimal totalQty = null;
    BigDecimal notInvoicedQty = null;

    if (isPurchase && purchaseOrderLine != null) {
      totalQty = purchaseOrderLine.getQty();

      notInvoicedQty =
          unitConversionService.convert(
              stockMoveLine.getUnit(),
              purchaseOrderLine.getUnit(),
              stockMoveLine.getRealQty().subtract(stockMoveLine.getQtyInvoiced()),
              stockMoveLine.getRealQty().scale(),
              purchaseOrderLine.getProduct());

      isFixedAssets = purchaseOrderLine.getFixedAssets();
      if (ati && !recoveredTax) {
        amountInCurrency = purchaseOrderLine.getInTaxTotal();
      } else {
        amountInCurrency = purchaseOrderLine.getExTaxTotal();
      }
    }
    if (!isPurchase && saleOrderLine != null) {
      totalQty = saleOrderLine.getQty();

      notInvoicedQty =
          unitConversionService.convert(
              stockMoveLine.getUnit(),
              saleOrderLine.getUnit(),
              stockMoveLine.getRealQty().subtract(stockMoveLine.getQtyInvoiced()),
              stockMoveLine.getRealQty().scale(),
              saleOrderLine.getProduct());
      if (ati) {
        amountInCurrency = saleOrderLine.getInTaxTotal();
      } else {
        amountInCurrency = saleOrderLine.getExTaxTotal();
      }
    }
    if (totalQty == null || BigDecimal.ZERO.compareTo(totalQty) == 0) {
      return null;
    }

    BigDecimal qtyRate = notInvoicedQty.divide(totalQty, 10, RoundingMode.HALF_EVEN);
    amountInCurrency = amountInCurrency.multiply(qtyRate).setScale(2, RoundingMode.HALF_EVEN);

    if (amountInCurrency == null || amountInCurrency.compareTo(BigDecimal.ZERO) == 0) {
      return null;
    }

    Product product = stockMoveLine.getProduct();

    Account account =
        accountManagementAccountService.getProductAccount(
            product, company, partner.getFiscalPosition(), isPurchase, isFixedAssets);

    boolean isDebit = false;
    if ((isPurchase && amountInCurrency.compareTo(BigDecimal.ZERO) == 1)
        || !isPurchase && amountInCurrency.compareTo(BigDecimal.ZERO) == -1) {
      isDebit = true;
    }
    if (isReverse) {
      isDebit = !isDebit;
    }

    MoveLine moveLine =
        moveLineService.createMoveLine(
            move,
            partner,
            account,
            amountInCurrency,
            isDebit,
            originDate,
            ++counter,
            origin,
            moveDescription);
    moveLine.setDate(moveDate);
    moveLine.setDueDate(moveDate);

    getAndComputeAnalyticDistribution(product, move, moveLine);

    move.addMoveLineListItem(moveLine);

    if (recoveredTax) {
      TaxLine taxLine =
          accountManagementAccountService.getTaxLine(
              originDate, product, company, partner.getFiscalPosition(), isPurchase);
      if (taxLine != null) {
        moveLine.setTaxLine(taxLine);
        moveLine.setTaxRate(taxLine.getValue());
        moveLine.setTaxCode(taxLine.getTax().getCode());

        if (taxLine.getValue().compareTo(BigDecimal.ZERO) != 0) {
          generateTaxMoveLine(move, moveLine, origin, isPurchase, isFixedAssets, moveDescription);
        }
      }
    }

    return moveLine;
  }

  protected void generateTaxMoveLine(
      Move move,
      MoveLine productMoveLine,
      String origin,
      boolean isPurchase,
      boolean isFixedAssets,
      String moveDescription)
      throws AxelorException {

    TaxLine taxLine = productMoveLine.getTaxLine();

    Tax tax = taxLine.getTax();

    Account taxAccount =
        taxAccountService.getAccount(tax, move.getCompany(), isPurchase, isFixedAssets);

    BigDecimal currencyTaxAmount =
        InvoiceLineManagement.computeAmount(
            productMoveLine.getCurrencyAmount(), taxLine.getValue());

    MoveLine taxMoveLine =
        moveLineService.createMoveLine(
            move,
            move.getPartner(),
            taxAccount,
            currencyTaxAmount,
            productMoveLine.getDebit().compareTo(BigDecimal.ZERO) == 1,
            productMoveLine.getOriginDate(),
            ++counter,
            origin,
            moveDescription);
    taxMoveLine.setDate(move.getDate());
    taxMoveLine.setDueDate(move.getDate());

    move.addMoveLineListItem(taxMoveLine);
  }

  protected MoveLine generatePartnerMoveLine(
      Move move, String origin, Account account, String moveDescription, LocalDate originDate)
      throws AxelorException {
    LocalDate moveDate = move.getDate();

    BigDecimal currencyBalance = moveToolService.getBalanceCurrencyAmount(move.getMoveLineList());
    BigDecimal balance = moveToolService.getBalanceAmount(move.getMoveLineList());

    if (balance.compareTo(BigDecimal.ZERO) == 0) {
      return null;
    }

    MoveLine moveLine =
        moveLineService.createMoveLine(
            move,
            move.getPartner(),
            account,
            currencyBalance.abs(),
            balance.abs(),
            null,
            balance.compareTo(BigDecimal.ZERO) == -1,
            moveDate,
            moveDate,
            originDate,
            ++counter,
            origin,
            moveDescription);

    move.addMoveLineListItem(moveLine);

    return moveLine;
  }

  protected void getAndComputeAnalyticDistribution(Product product, Move move, MoveLine moveLine) {

    if (appAccountService.getAppAccount().getAnalyticDistributionTypeSelect()
        == AppAccountRepository.DISTRIBUTION_TYPE_FREE) {
      return;
    }

    AnalyticDistributionTemplate analyticDistributionTemplate =
        analyticMoveLineService.getAnalyticDistributionTemplate(
            move.getPartner(), product, move.getCompany());

    moveLine.setAnalyticDistributionTemplate(analyticDistributionTemplate);

    List<AnalyticMoveLine> analyticMoveLineList =
        moveLineService.createAnalyticDistributionWithTemplate(moveLine).getAnalyticMoveLineList();
    for (AnalyticMoveLine analyticMoveLine : analyticMoveLineList) {
      analyticMoveLine.setMoveLine(moveLine);
    }
    analyticMoveLineList.stream().forEach(analyticMoveLineRepository::save);
  }

  protected void reconcile(Move move, Move reverseMove) throws AxelorException {

    List<MoveLine> moveLineSortedList = move.getMoveLineList();
    Collections.sort(moveLineSortedList, Comparator.comparing(MoveLine::getCounter));

    List<MoveLine> reverseMoveLineSortedList = reverseMove.getMoveLineList();
    Collections.sort(reverseMoveLineSortedList, Comparator.comparing(MoveLine::getCounter));

    Iterator<MoveLine> reverseMoveLinesIt = reverseMoveLineSortedList.iterator();

    for (MoveLine moveLine : moveLineSortedList) {

      MoveLine reverseMoveLine = reverseMoveLinesIt.next();

      reconcileService.reconcile(moveLine, reverseMoveLine, false, false);
    }
  }

  public List<Long> getStockMoveLines(Batch batch) {
    int offset = 0;
    Boolean includeNotStockManagedProduct =
        batch.getSupplychainBatch().getIncludeNotStockManagedProduct();

    List<StockMoveLine> stockMoveLineList;
    List<Long> stockMoveLineIdList = new ArrayList<>();

    Query<StockMove> stockMoveQuery =
        stockMoverepository.all().filter(":batch MEMBER OF self.batchSet").bind("batch", batch);
    List<Long> stockMoveIdList =
        stockMoveQuery
            .select("id")
            .fetch(0, 0)
            .stream()
            .map(m -> (Long) m.get("id"))
            .collect(Collectors.toList());

    if (stockMoveIdList.isEmpty()) {
      stockMoveLineIdList.add(0L);
    } else {
      Query<StockMoveLine> stockMoveLineQuery =
          stockMoveLineRepository
              .all()
              .filter("self.stockMove.id IN :stockMoveIdList")
              .bind("stockMoveIdList", stockMoveIdList)
              .order("id");

      while (!(stockMoveLineList = stockMoveLineQuery.fetch(FETCH_LIMIT, offset)).isEmpty()) {
        offset += stockMoveLineList.size();

        for (StockMoveLine stockMoveLine : stockMoveLineList) {
          Product product = stockMoveLine.getProduct();
          if (!checkStockMoveLine(stockMoveLine, product, includeNotStockManagedProduct)) {
            stockMoveLineIdList.add(stockMoveLine.getId());
          }
        }

        JPA.clear();
      }
    }
    return stockMoveLineIdList;
  }

  @Transactional(rollbackOn = {Exception.class})
  public Move generateStockAccountMove(StockMove stockMove) throws AxelorException {
    List<StockMoveLine> stockMoveLines = stockMove.getStockMoveLineList();
    Map<StockMoveLine, Map<String, Account>> stockAccounts = new HashMap<>();
    Company company = stockMove.getCompany();
    Currency currency = stockMove.getCompany().getCurrency();
    Partner partner = stockMove.getPartner();
    LocalDate moveDate = stockMove.getEstimatedDate();
    Journal journal = this.setJournal(stockMove);
    for (StockMoveLine line : stockMoveLines) {
      Map<String, Account> accountMap = new HashMap<String, Account>();
      AccountManagement accountManagement =
          Beans.get(AccountManagementRepository.class)
              .all()
              .filter("self.product = ?1 and self.company = ?2", line.getProduct(), company)
              .fetchOne();
      if (stockMove.getToStockLocation().getTypeSelect() == StockLocationRepository.TYPE_EXTERNAL) {
        Account stockAccount = null;
        if (line.getProduct().getFamilleProduit().getId() == 67L
            || line.getProduct().getFamilleProduit().getId() == 68L) {
          stockAccount = Beans.get(AccountRepository.class).find(595L);

        } else if (line.getProduct().getFamilleProduit().getId() == 59L) {
          stockAccount = Beans.get(AccountRepository.class).find(3518L);
        } else {
          stockAccount = Beans.get(AccountRepository.class).find(4113L);
        }
        accountMap.put("stockAccount", stockAccount);
      } else {
        accountMap.put("stockAccount", accountManagement.getStockAccount());
      }

      accountMap.put("purchaseAccount", accountManagement.getPurchaseAccount());
      accountMap.put("consumptionAccount", accountManagement.getConsumptionAccount());
      stockAccounts.put(line, accountMap);
    }

    Move move =
        moveCreateService.createMove(
            journal,
            company,
            currency,
            partner,
            moveDate,
            null,
            MoveRepository.TECHNICAL_ORIGIN_AUTOMATIC);

    int counter = 0;
    for (StockMoveLine line : stockMoveLines) {

      Account acc = stockAccounts.get(line).get("purchaseAccount");
      Account acc2 = stockAccounts.get(line).get("stockAccount");

      if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_INCOMING
          && stockMove.getPartner() == stockMove.getCompany().getPartner()) {
        acc = stockAccounts.get(line).get("consumptionAccount");
        acc2 = stockAccounts.get(line).get("stockAccount");
      } else if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_INCOMING
          && stockMove.getPartner() != stockMove.getCompany().getPartner()) {
        acc2 = stockAccounts.get(line).get("stockAccount");
        acc = stockAccounts.get(line).get("purchaseAccount");
      } else if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_OUTGOING
          && stockMove.getPartner() == stockMove.getCompany().getPartner()) {
        acc = stockAccounts.get(line).get("consumptionAccount");
        acc2 = stockAccounts.get(line).get("stockAccount");
      }

      BigDecimal amountInCurrency = line.getUnitPriceUntaxed().multiply(line.getRealQty());
      String description = stockMove.getStockMoveSeq() + "-" + line.getProduct().getCode();
      if (line.getTrackingNumber() != null) {
        description += "-" + line.getTrackingNumber().getTrackingNumberSeq();
      }

      if (line.getRealQty().compareTo(BigDecimal.ZERO) > 0) {

        MoveLine moveLine =
            moveLineService.createMoveLine(
                move,
                partner,
                acc,
                amountInCurrency,
                isDebit(stockMove),
                moveDate,
                ++counter,
                stockMove.getStockMoveSeq(),
                description);
        moveLine.setDate(moveDate);
        moveLine.setDueDate(moveDate);
        moveLine.setAccountId(acc.getId());
        moveLine.setAccountCode(acc.getCode());

        MoveLine moveLine2 =
            moveLineService.createMoveLine(
                move,
                partner,
                acc2,
                amountInCurrency,
                !isDebit(stockMove),
                moveDate,
                ++counter,
                stockMove.getStockMoveSeq(),
                description);
        moveLine2.setDate(moveDate);
        moveLine2.setDueDate(moveDate);
        moveLine2.setAccountId(acc2.getId());
        moveLine2.setAccountCode(acc2.getCode());

        move.addMoveLineListItem(moveLine);
        move.addMoveLineListItem(moveLine2);
      }
    }
    stockMove.setIsVentilated(true);
    move.setIgnoreInAccountingOk(false);
    move.setStatusSelect(MoveRepository.STATUS_DAYBOOK);
    move.setStockMove(stockMove);
    return move;
  }

  public List<Long> massGenerationMove(List<Long> ids) throws AxelorException {

    List<Long> movesId = new ArrayList<>();

    for (Long id : ids) {
      StockMove stockMove = Beans.get(StockMoveRepository.class).find(id);
      Move move = this.generateStockAccountMove(stockMove);
      movesId.add(move.getId());
    }
    ;
    return movesId;
  }

  public boolean isDebit(StockMove stockMove) throws AxelorException {
    boolean isDebit;
    // stockMove.getToStockLocation().getTypeSelect() == StockLocationRepository.TYPE_VIRTUAL
    if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_INCOMING) {
      isDebit = false;
    } else if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_OUTGOING) {
      isDebit = true;
    } else
      throw new AxelorException(
          stockMove,
          TraceBackRepository.CATEGORY_MISSING_FIELD,
          I18n.get(IExceptionMessage.MOVE_1),
          stockMove.getId());
    return isDebit;
  }

  public Journal setJournal(StockMove stockMove) throws AxelorException {
    Journal journal;
    // stockMove.getToStockLocation().getTypeSelect() == StockLocationRepository.TYPE_VIRTUAL
    if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_INCOMING) {
      journal = Beans.get(JournalRepository.class).find(10L);
    } else if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_OUTGOING) {
      journal = Beans.get(JournalRepository.class).find(30L);
    } else
      throw new AxelorException(
          stockMove,
          TraceBackRepository.CATEGORY_MISSING_FIELD,
          I18n.get(IExceptionMessage.MOVE_1),
          stockMove.getId());
    return journal;
  }

  public boolean isDebitInventoryLine(InventoryLine inventoryLine) throws AxelorException {
    boolean isDebit;
    // stockMove.getToStockLocation().getTypeSelect() == StockLocationRepository.TYPE_VIRTUAL
    if (inventoryLine.getGap().compareTo(BigDecimal.ZERO) < 0) {
      isDebit = false;
    } else if (inventoryLine.getGap().compareTo(BigDecimal.ZERO) > 0) {
      isDebit = true;
    } else
      throw new AxelorException(
          inventoryLine,
          TraceBackRepository.CATEGORY_MISSING_FIELD,
          "Ecart = 0",
          inventoryLine.getId());
    return isDebit;
  }

  public Boolean isGapPositive(InventoryLine line) {
    if (line.getGap().compareTo(BigDecimal.ZERO) > 0) {
      return true;
    } else {
      return false;
    }
  }

  @Transactional(rollbackOn = {Exception.class})
  public Move generateInventoryLineMove(InventoryLine inventoryLine) throws AxelorException {

    Map<InventoryLine, Map<String, Account>> stockAccounts = new HashMap<>();
    Company company = inventoryLine.getInventory().getCompany();
    Currency currency = inventoryLine.getInventory().getCompany().getCurrency();
    Partner partner = inventoryLine.getInventory().getCompany().getPartner();
    LocalDate moveDate = inventoryLine.getInventory().getPlannedEndDateT().toLocalDate();
    Journal journal = Beans.get(JournalRepository.class).find(10L);

    Map<String, Account> accountMap = new HashMap<String, Account>();
    AccountManagement accountManagement =
        Beans.get(AccountManagementRepository.class)
            .all()
            .filter("self.product = ?1 and self.company = ?2", inventoryLine.getProduct(), company)
            .fetchOne();

    if (accountManagement.getStockAccount() == null
        || accountManagement.getConsumptionAccount() == null) {
      throw new AxelorException(
          inventoryLine,
          TraceBackRepository.CATEGORY_MISSING_FIELD,
          I18n.get(IExceptionMessage.VENTILATE_STATE_6),
          inventoryLine.getProduct().getFullName());
    }

    accountMap.put("stockAccount", accountManagement.getStockAccount());
    accountMap.put("consumptionAccount", accountManagement.getConsumptionAccount());

    stockAccounts.put(inventoryLine, accountMap);

    Move move =
        moveCreateService.createMove(
            journal,
            company,
            currency,
            partner,
            moveDate,
            null,
            MoveRepository.TECHNICAL_ORIGIN_AUTOMATIC);

    int counter = 0;

    Account acc = stockAccounts.get(inventoryLine).get("consumptionAccount");
    Account acc2 = stockAccounts.get(inventoryLine).get("stockAccount");

    if (inventoryLine.getJustifiedGap()) {
      if (isGapPositive(inventoryLine)) {
        acc = stockAccounts.get(inventoryLine).get("consumptionAccount");
        acc2 = stockAccounts.get(inventoryLine).get("stockAccount");
      } else if (!isGapPositive(inventoryLine)) {
        acc = stockAccounts.get(inventoryLine).get("stockAccount");
        acc2 = stockAccounts.get(inventoryLine).get("consumptionAccount");
      }
    } else {
      if (isGapPositive(inventoryLine)) {
        acc = Beans.get(AccountRepository.class).find(1360L);
        acc2 = stockAccounts.get(inventoryLine).get("stockAccount");
      } else if (!isGapPositive(inventoryLine)) {
        acc = stockAccounts.get(inventoryLine).get("stockAccount");
        acc2 = Beans.get(AccountRepository.class).find(1400L);
      }
    }

    BigDecimal amountInCurrency = inventoryLine.getGapValue().multiply(inventoryLine.getGap());
    String description =
        inventoryLine.getInventory().getInventorySeq() + "-" + inventoryLine.getProduct().getCode();
    if (inventoryLine.getTrackingNumber() != null) {
      description += "-" + inventoryLine.getTrackingNumber().getTrackingNumberSeq();
    }

    MoveLine moveLine =
        moveLineService.createMoveLine(
            move,
            partner,
            acc,
            amountInCurrency,
            isDebitInventoryLine(inventoryLine),
            moveDate,
            ++counter,
            inventoryLine.getInventory().getInventorySeq(),
            description);
    moveLine.setDescription(description);
    moveLine.setDate(moveDate);
    moveLine.setDueDate(moveDate);
    moveLine.setAccountId(acc.getId());
    moveLine.setAccountCode(acc.getCode());
    moveLine.setAccountName(acc.getName());

    MoveLine moveLine2 =
        moveLineService.createMoveLine(
            move,
            partner,
            acc2,
            amountInCurrency,
            !isDebitInventoryLine(inventoryLine),
            moveDate,
            ++counter,
            inventoryLine.getInventory().getInventorySeq(),
            description);
    moveLine2.setDescription(description);
    moveLine2.setDate(moveDate);
    moveLine2.setDueDate(moveDate);
    moveLine2.setAccountId(acc2.getId());
    moveLine2.setAccountCode(acc2.getCode());
    moveLine2.setAccountName(acc2.getName());

    move.addMoveLineListItem(moveLine);
    move.addMoveLineListItem(moveLine2);
    move.setInventoryLine(inventoryLine);
    inventoryLine.setIsVentilated(true);

    move.setIgnoreInAccountingOk(false);
    move.setStatusSelect(MoveRepository.STATUS_DAYBOOK);
    return move;
  }

  public List<Long> massGenerationInventoryLineMove(List<Long> ids) throws AxelorException {

    List<Long> movesId = new ArrayList<>();

    for (Long id : ids) {
      InventoryLine line = Beans.get(InventoryLineRepository.class).find(id);
      Move move = this.generateInventoryLineMove(line);
      movesId.add(move.getId());
    }
    return movesId;
  }

  // public boolean isPurchase(StockMove stockMove){
  //   boolean isPurchase;
  //   Partner partner = stockMove.getPartner() ;
  //   if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_INCOMING &&  stockMove.getPartner()
  // == stockMove.getCompany().getPartner()) {
  //     isPurchase = false;
  //   }
  //   else if(stockMove.getTypeSelect() == StockMoveRepository.TYPE_INCOMING  &&
  // stockMove.getPartner() != stockMove.getCompany().getPartner()){
  //     isPurchase = true;
  //   }else if(stockMove.getTypeSelect() == StockMoveRepository.TYPE_OUTGOING  &&
  // stockMove.getPartner() == stockMove.getCompany().getPartner()){

  //    }

  // }

}
