package com.ecep.contract.ds.company.service;

import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.IEntityService;
import com.ecep.contract.MessageHolder;
import com.ecep.contract.QueryService;
import com.ecep.contract.ds.company.repository.CompanyBankAccountRepository;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.CompanyBankAccount;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "company-bank-account")
public class CompanyBankAccountService implements IEntityService<CompanyBankAccount>, QueryService<CompanyBankAccount> {
    private static final Logger logger = LoggerFactory.getLogger(CompanyBankAccountService.class);
    @Lazy
    @Autowired
    private CompanyBankAccountRepository repository;

    public CompanyBankAccount findByAccount(Company company, String account) {
        return repository.findByCompanyAndAccount(company, account).orElse(null);
    }

    public void updateBankAccount(Company company, String bank, String bankAccount, MessageHolder holder) {
        boolean modified = false;
        if (!StringUtils.hasText(bankAccount)) {
            // 空账户不用存储
            return;
        }

        CompanyBankAccount account = findByAccount(company, bankAccount);
        if (account == null) {
            account = new CompanyBankAccount();
            account.setCompany(company);
            account.setAccount(bankAccount);
            holder.info("新增银行账户" + bankAccount);
            modified = true;
        }

        if (StringUtils.hasText(bank)) {
            // 更新开户行
            if (!Objects.equals(account.getOpeningBank(), bank)) {
                account.setOpeningBank(bank);
                holder.info("更新开户行" + bank);
                modified = true;
            }
        }

        if (modified) {
            save(account);
        }
    }

    public CompanyBankAccount save(CompanyBankAccount account) {
        return repository.save(account);
    }

    public List<CompanyBankAccount> findAll(Specification<CompanyBankAccount> spec, Sort sort) {
        return repository.findAll(spec, sort);
    }

    @Override
    public CompanyBankAccount findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public Specification<CompanyBankAccount> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            return builder.or(
                    builder.and(
                            builder.isNotNull(root.get("bank")),
                            builder.or(
                                    builder.like(root.get("bank").get("name"), "%" + searchText + "%"),
                                    builder.like(root.get("bank").get("code"), "%" + searchText + "%"))),
                    builder.like(root.get("openingBank"), "%" + searchText + "%"),
                    builder.like(root.get("account"), "%" + searchText + "%"));
        };
    }

    @Override
    public Page<CompanyBankAccount> findAll(Specification<CompanyBankAccount> spec, Pageable pageable) {
        return repository.findAll(spec, pageable);
    }

    public void delete(CompanyBankAccount entity) {
        repository.delete(entity);
    }

    public List<CompanyBankAccount> searchByCompany(Company company, String searchText) {
        Specification<CompanyBankAccount> spec = getSpecification(searchText);
        if (company != null) {
            spec = SpecificationUtils.and(spec, (root, query, builder) -> {
                return builder.equal(root.get("company"), company);
            });
        }
        return repository.findAll(spec, Pageable.ofSize(10)).getContent();
    }

    @Override
    public Page<CompanyBankAccount> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<CompanyBankAccount> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "company");
        return findAll(spec, pageable);
    }
}
