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

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import org.hibernate.Hibernate;
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.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.CustomerFileType;
import com.ecep.contract.IEntityService;
import com.ecep.contract.MessageHolder;
import com.ecep.contract.QueryService;
import com.ecep.contract.SpringApp;
import com.ecep.contract.constant.CompanyCustomerConstant;
import com.ecep.contract.ds.company.service.CompanyBasicService;
import com.ecep.contract.ds.company.service.CompanyContactService;
import com.ecep.contract.ds.company.service.CompanyService;
import com.ecep.contract.ds.customer.repository.CompanyCustomerRepository;
import com.ecep.contract.ds.other.service.SysConfService;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.model.CompanyBasicFile;
import com.ecep.contract.ds.customer.model.CompanyCustomer;
import com.ecep.contract.ds.customer.model.CompanyCustomerEntity;
import com.ecep.contract.ds.customer.model.CompanyCustomerEvaluationFormFile;
import com.ecep.contract.ds.customer.model.CompanyCustomerFile;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.CompanyUtils;
import com.ecep.contract.util.FileUtils;
import com.ecep.contract.util.MyStringUtils;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.CompanyCustomerVo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import jakarta.persistence.criteria.Path;

@Lazy
@Service
@CacheConfig(cacheNames = "company-customer")
public class CompanyCustomerService extends CompanyBasicService
        implements IEntityService<CompanyCustomer>, QueryService<CompanyCustomerVo>,
        VoableService<CompanyCustomer, CompanyCustomerVo> {
    private static final Logger logger = LoggerFactory.getLogger(CompanyCustomerService.class);

    @Lazy
    @Autowired
    private CompanyCustomerRepository repository;
    @Lazy
    @Autowired
    private CompanyCustomerFileService companyCustomerFileService;
    @Lazy
    @Autowired
    private SysConfService confService;
    @Lazy
    @Autowired
    private CompanyCustomerEntityService companyCustomerEntityService;

    public CompanyCustomer findByCompany(Company company) {
        return repository.findByCompany(company).orElse(null);
    }

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

    @Cacheable(key = "#p0")
    public CompanyCustomerVo findById(Integer id) {
        return repository.findById(id).map(CompanyCustomer::toVo).orElse(null);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id")
    })
    public CompanyCustomer save(CompanyCustomer companyCustomer) {
        return repository.save(companyCustomer);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0")
    })
    @Override
    public void delete(CompanyCustomer entity) {
        repository.delete(entity);
    }

    @Override
    public Specification<CompanyCustomer> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }

        Specification<CompanyCustomer> nameSpec = (root, query, builder) -> {
            Path<Company> company = root.get("company");
            return companyService.buildSearchPredicate(searchText, company, query, builder);
        };
        // 判断是否全是数字
        if (MyStringUtils.isAllDigit(searchText)) {
            // 全数字就按 Id 查询
            try {
                int id = Integer.parseInt(searchText);
                Specification<CompanyCustomer> idSpec = (root, query, builder) -> {
                    return builder.equal(root.get("id"), id);
                };
                nameSpec = nameSpec.or(idSpec);
            } catch (Exception ignored) {
            }
        }
        List<CompanyCustomerEntity> searched = companyCustomerEntityService.search(searchText);
        if (!searched.isEmpty()) {
            nameSpec = SpecificationUtils.or(nameSpec, (root, query, builder) -> {
                return builder.in(root.get("id")).value(searched.stream()
                        .map(CompanyCustomerEntity::getCustomer)
                        .filter(Objects::nonNull)
                        .map(CompanyCustomer::getId)
                        .collect(Collectors.toSet()));
            });
        }
        return nameSpec;
    }

    @Override
    public List<CompanyCustomer> search(String searchText) {
        Specification<CompanyCustomer> spec = getSpecification(searchText);
        return repository.findAll(spec, Pageable.ofSize(10)).getContent();
    }

    @Override
    public <T, F extends CompanyBasicFile<T>, ID> void deleteFile(F file) {
        CompanyCustomerFile customerFile = (CompanyCustomerFile) file;
        companyCustomerFileService.delete(customerFile);
    }

    public File getBasePath() {
        return new File(confService.getString(CompanyCustomerConstant.KEY_BASE_PATH));
    }

    /**
     * 重置 客户文件
     *
     * @param companyCustomer 客户对象
     * @param holder          消息持有者
     */
    public boolean reBuildingFiles(CompanyCustomer companyCustomer, MessageHolder holder) {
        List<CompanyCustomerFile> dbFiles = companyCustomerFileService.findAllByCustomer(companyCustomer);
        Map<String, CompanyCustomerFile> map = new HashMap<>();

        boolean modified = fetchDbFiles(dbFiles, map, holder::info);

        // 客户目录下
        List<CompanyCustomerFile> retrieveFiles = new ArrayList<>();
        List<File> needMoveToCompanyPath = new ArrayList<>();

        // TODO 客户有曾用名，可能存在多个目录
        fetchFiles(companyCustomer.getPath(), needMoveToCompanyPath, retrieveFiles, map, holder::info);

        // 移动文件到公司目录下 to company path
        moveFileToCompany(companyCustomer.getCompany(), needMoveToCompanyPath);

        holder.info("导入 " + retrieveFiles.size() + " 个文件");

        if (!retrieveFiles.isEmpty()) {
            // update db
            retrieveFiles.forEach(v -> v.setCustomer(companyCustomer));
            companyCustomerFileService.saveAll(retrieveFiles);
            modified = true;
        }

        return modified;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected <T, F extends CompanyBasicFile<T>> boolean fillFileAsDefaultType(F dbFile, File file,
            Consumer<String> status) {
        dbFile.setType((T) CustomerFileType.General);
        fillFile(dbFile, file, null, status);
        companyCustomerFileService.save((CompanyCustomerFile) dbFile);
        return true;
    }

    @Override
    protected <T, F extends CompanyBasicFile<T>> boolean fillFileAsEvaluationFile(F customerFile, File file,
            List<File> fileList, Consumer<String> status) {
        boolean modified = super.fillFileAsEvaluationFile(customerFile, file, fileList, status);

        if (fileList != null) {
            File jsonFile = null;
            // 文件名
            String fileName = file.getName();
            // 文件名，不含后缀
            String name = StringUtils.stripFilenameExtension(fileName);

            String jsonFileName = name + FileUtils.JSON;
            for (File f : fileList) {
                // 查找存档文件
                if (f.getName().equals(jsonFileName)) {
                    jsonFile = f;
                    break;
                }
            }
            if (jsonFile != null) {
                if (fileList.remove(jsonFile)) {
                    try {
                        updateEvaluationFileByJsonFile(customerFile, jsonFile, status);
                    } catch (IOException e) {
                        if (logger.isErrorEnabled()) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
            }
        }
        return modified;
    }

    private <T, F extends CompanyBasicFile<T>> void updateEvaluationFileByJsonFile(F customerFile, File jsonFile,
            Consumer<String> status) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode root = objectMapper.readTree(jsonFile);
        if (!root.isObject()) {
            return;
        }
        ObjectNode data = (ObjectNode) root;
        data.remove("file");
        data.remove("signDate");
        data.remove("valid");
        JsonNode type = data.remove("type");

        CompanyCustomerEvaluationFormFile formFile = companyCustomerFileService
                .findCustomerEvaluationFormFileByCustomerFile((CompanyCustomerFile) customerFile);
        objectMapper.updateValue(formFile, data);
        logger.info("load json data from {}", jsonFile.getName());
        formFile.setCatalog(type.asText());
        SpringApp.getBean(CompanyCustomerEvaluationFormFileService.class).save(formFile);
        if (jsonFile.delete()) {
            logger.info("delete json file {}", jsonFile.getName());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected <T, F extends CompanyBasicFile<T>> F fillFileType(File file, List<File> fileList,
            Consumer<String> status) {
        CompanyCustomerFile customerFile = new CompanyCustomerFile();
        customerFile.setType(CustomerFileType.General);
        if (fillFile(customerFile, file, fileList, status)) {
            return (F) customerFile;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected <T, F extends CompanyBasicFile<T>> boolean setFileTypeAsEvaluationForm(F file) {
        T type = file.getType();
        if (type != CustomerFileType.EvaluationForm) {
            file.setType((T) CustomerFileType.EvaluationForm);
            return true;
        }
        return false;
    }

    protected boolean isEvaluationFile(String fileName) {
        return (fileName.contains(CompanyCustomerConstant.EVALUATION_FORM_NAME1)
                || fileName.contains(CompanyCustomerConstant.EVALUATION_FORM_NAME2))
                && (FileUtils.withExtensions(fileName, FileUtils.JPG, FileUtils.JPEG,
                        FileUtils.PDF));
    }

    public boolean makePathAbsent(CompanyCustomer companyCustomer) {
        String path = companyCustomer.getPath();
        if (StringUtils.hasText(path)) {
            File file = new File(path);
            if (file.exists()) {
                return false;
            }
        }

        File dir = makePath(companyCustomer);
        if (dir == null) {
            return false;
        }
        if (!dir.exists()) {
            return false;
        }
        companyCustomer.setPath(dir.getAbsolutePath());
        return true;
    }

    private File makePath(CompanyCustomer companyCustomer) {
        File basePath = getBasePath();
        Company company = companyCustomer.getCompany();
        if (!Hibernate.isInitialized(company)) {
            company = companyService.getById(company.getId());
        }

        String companyName = company.getName();
        String fileName = CompanyUtils.formatCompanyVendorId(companyCustomer.getId()) + "-"
                + FileUtils.escapeFileName(companyName);

        File dir = new File(basePath, fileName);
        if (!dir.exists()) {
            if (!dir.mkdir()) {
                return null;
            }
        }
        return dir;
    }

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

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

    /**
     * 将一个公司的客户信息转移到另一个公司，并保存在数据库中
     *
     * @param from 要转移的客户信息所属的公司
     * @param to   要转移到的公司
     */
    public void resetTo(Company from, Company to) {
        // 这里使用Optional对象来处理可能为空的情况
        Optional<CompanyCustomer> fromCustomer = repository.findByCompany(from);
        if (fromCustomer.isEmpty()) {
            // 无效数据
            return;
        }
        Optional<CompanyCustomer> toCustomer = repository.findByCompany(to);
        if (toCustomer.isEmpty()) {
            CompanyCustomer customer = fromCustomer.get();
            customer.setCompany(to);
            // 保存更新后的CompanyCustomer对象到数据库
            repository.save(customer);
            return;
        }

        // 把 fromCustomer 信息合并到 toCustomer
        resetTo(fromCustomer.get(), toCustomer.get());

    }

    /***
     * 合并两个CompanyCustomer对象，并将fromCustomer的信息合并到toCustomer中，并保存到数据库中。
     *
     * @param from 源客户对象
     * @param to   目标客户对象
     */
    public void resetTo(CompanyCustomer from, CompanyCustomer to) {
        // file
        companyCustomerFileService.resetTo(from, to);
        // entity
        companyCustomerEntityService.resetTo(from, to);
        // 删除源客户对象
        repository.delete(from);
    }

    /**
     * 删除 company 的 客户
     */
    public void deleteByCompany(Company company) {
        int deleted = repository.deleteAllByCompany(company);
        if (deleted > 0) {
            if (logger.isInfoEnabled()) {
                logger.info("Delete {} records by company:#{}", deleted, company.getId());
            }
        }
    }

    @Override
    public void updateByVo(CompanyCustomer customer, CompanyCustomerVo vo) {
        // 优化关联实体处理逻辑 - 公司关联
        if (vo.getCompanyId() == null) {
            customer.setCompany(null);
        } else {
            CompanyService service = SpringApp.getBean(CompanyService.class);
            // 添加实体匹配检查
            if (customer.getCompany() == null || !customer.getCompany().getId().equals(vo.getCompanyId())) {
                // 使用getById方法替代findById
                customer.setCompany(service.getById(vo.getCompanyId()));
            }
        }

        // 优化关联实体处理逻辑 - 客户分类关联
        if (vo.getCatalogId() == null) {
            customer.setCatalog(null);
        } else {
            CustomerCatalogService service = SpringApp.getBean(CustomerCatalogService.class);
            // 添加实体匹配检查
            if (customer.getCatalog() == null || !customer.getCatalog().getId().equals(vo.getCatalogId())) {
                // 使用getById方法替代findById
                customer.setCatalog(service.getById(vo.getCatalogId()));
            }
        }

        // 映射基本属性
        customer.setDevelopDate(vo.getDevelopDate());
        customer.setPath(vo.getPath());

        // 优化关联实体处理逻辑 - 联系人关联
        if (vo.getContactId() == null) {
            customer.setContact(null);
        } else {
            CompanyContactService service = SpringApp.getBean(CompanyContactService.class);
            // 添加实体匹配检查
            if (customer.getContact() == null || !customer.getContact().getId().equals(vo.getContactId())) {
                // 使用getById方法替代findById
                customer.setContact(service.getById(vo.getContactId()));
            }
        }

        // 映射其他属性
        customer.setDescription(vo.getDescription());
        customer.setCreated(vo.getCreated());

        if (customer.getVersion() != vo.getVersion()) {
            logger.warn("customer version not equal, customer id: {}, version: {}, vo version: {}", customer.getId(),
                    customer.getVersion(), vo.getVersion());
        }
    }

}
