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.cache.annotation.Cacheable;
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.SpringApp;
import com.ecep.contract.ds.company.repository.CompanyBankAccountRepository;
import com.ecep.contract.ds.other.service.BankService;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.ds.company.model.CompanyBankAccount;
import com.ecep.contract.service.ServiceException;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.CompanyBankAccountVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "company-bank-account")
public class CompanyBankAccountService implements IEntityService<CompanyBankAccount>, QueryService<CompanyBankAccountVo>,
        VoableService<CompanyBankAccount, CompanyBankAccountVo> {
    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);
    }

    @Cacheable(key = "#p0")
    @Override
    public CompanyBankAccountVo findById(Integer id) {
        return repository.findById(id).map(CompanyBankAccount::toVo).orElse(null);
    }
    
    @Override
    public CompanyBankAccount getById(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<CompanyBankAccountVo> 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).map(CompanyBankAccount::toVo);
    }

    @Override
    public void updateByVo(CompanyBankAccount model, CompanyBankAccountVo vo) {
        if (model == null) {
            throw new ServiceException("CompanyBankAccount cannot be null");
        }
        if (vo == null) {
            throw new ServiceException("CompanyBankAccountVo cannot be null");
        }
        
        // 基本属性映射
        model.setAccount(vo.getAccount());
        model.setOpeningBank(vo.getOpeningBank());
        model.setDescription(vo.getDescription());
        
        // 处理关联关系 - 公司
        if (vo.getCompanyId() != null) {
            model.setCompany(SpringApp.getBean(CompanyService.class).getById(vo.getCompanyId()));
        } else {
            model.setCompany(null);
        }
        
        // 处理关联关系 - 银行
        if (vo.getBankId() != null) {
            model.setBank(SpringApp.getBean(BankService.class).getById(vo.getBankId()));
        } else {
            model.setBank(null);
        }
        
        // 注意：CompanyBankAccount实体类中没有active字段，所以不需要设置
    }
}
