package org.hzhub.crm.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hzhub.common.core.exception.ServiceException;
import org.hzhub.common.core.utils.StringUtils;
import org.hzhub.common.satoken.utils.LoginHelper;
import org.hzhub.system.domain.SysTenantCompany;
import org.hzhub.system.mapper.SysTenantCompanyMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 租户与ERP公司映射服务
 *
 * @author hzhub
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TenantCompanyService {

    private final SysTenantCompanyMapper tenantCompanyMapper;
    private final ErpIntegrationService erpIntegrationService;

    /**
     * 获取当前租户关联的所有ERP公司ID列表
     *
     * @return ERP公司ID列表
     */
    public List<String> getCurrentTenantCompanyIds() {
        String tenantId = LoginHelper.getTenantId();
        return getTenantCompanyIds(tenantId);
    }

    /**
     * 获取指定租户关联的所有ERP公司ID列表
     *
     * @param tenantId 租户编号
     * @return ERP公司ID列表
     */
    public List<String> getTenantCompanyIds(String tenantId) {
        if (StringUtils.isBlank(tenantId)) {
            return Collections.emptyList();
        }

        List<SysTenantCompany> mappings = tenantCompanyMapper.selectList(
            new LambdaQueryWrapper<SysTenantCompany>()
                .eq(SysTenantCompany::getTenantId, tenantId)
                .eq(SysTenantCompany::getStatus, "0")
                .orderByAsc(SysTenantCompany::getSort)
        );

        return mappings.stream()
            .map(SysTenantCompany::getErpCompanyId)
            .filter(StringUtils::isNotBlank)
            .collect(Collectors.toList());
    }

    /**
     * 获取当前租户关联的所有ERP公司映射列表
     *
     * @return 映射列表
     */
    public List<SysTenantCompany> getCurrentTenantCompanies() {
        String tenantId = LoginHelper.getTenantId();
        return tenantCompanyMapper.selectList(
            new LambdaQueryWrapper<SysTenantCompany>()
                .eq(SysTenantCompany::getTenantId, tenantId)
                .orderByAsc(SysTenantCompany::getSort)
        );
    }

    /**
     * 获取所有租户的ERP公司映射列表（全局管理）
     *
     * @return 映射列表
     */
    public List<SysTenantCompany> getAllTenantCompanies() {
        return tenantCompanyMapper.selectList(
            new LambdaQueryWrapper<SysTenantCompany>()
                .orderByAsc(SysTenantCompany::getTenantId)
                .orderByAsc(SysTenantCompany::getSort)
        );
    }

    /**
     * 绑定租户与ERP公司
     *
     * @param tenantId    租户编号
     * @param tenantName  租户名称（可选）
     * @param erpCompanyId ERP公司ID
     * @param erpCompanyName ERP公司名称（可选）
     * @return 绑定结果
     */
    @Transactional(rollbackFor = Exception.class)
    public int bindCompany(String tenantId, String tenantName, String erpCompanyId, String erpCompanyName) {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(erpCompanyId)) {
            throw new ServiceException("租户编号和ERP公司ID不能为空");
        }

        // 检查是否已绑定
        SysTenantCompany existing = tenantCompanyMapper.selectOne(
            new LambdaQueryWrapper<SysTenantCompany>()
                .eq(SysTenantCompany::getTenantId, tenantId)
                .eq(SysTenantCompany::getErpCompanyId, erpCompanyId)
        );

        if (existing != null) {
            if ("0".equals(existing.getStatus())) {
                throw new ServiceException("该ERP公司已绑定到该租户");
            }
            // 恢复已停用的绑定
            existing.setStatus("0");
            if (StringUtils.isNotBlank(erpCompanyName)) {
                existing.setErpCompanyName(erpCompanyName);
            }
            if (StringUtils.isNotBlank(tenantName)) {
                existing.setTenantName(tenantName);
            }
            return tenantCompanyMapper.updateById(existing);
        }

        // 新建绑定
        SysTenantCompany mapping = new SysTenantCompany();
        mapping.setTenantId(tenantId);
        mapping.setTenantName(tenantName);
        mapping.setErpCompanyId(erpCompanyId);
        mapping.setErpCompanyName(erpCompanyName);
        mapping.setStatus("0");
        mapping.setSort(0);

        return tenantCompanyMapper.insert(mapping);
    }

    /**
     * 解绑租户与ERP公司（停用状态）
     *
     * @param id 映射ID
     * @return 解绑结果
     */
    @Transactional(rollbackFor = Exception.class)
    public int unbindCompany(Long id) {
        SysTenantCompany mapping = tenantCompanyMapper.selectById(id);
        if (mapping == null) {
            throw new ServiceException("映射关系不存在");
        }

        mapping.setStatus("1");
        return tenantCompanyMapper.updateById(mapping);
    }

    /**
     * 删除租户与ERP公司映射
     *
     * @param id 映射ID
     * @return 删除结果
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteMapping(Long id) {
        return tenantCompanyMapper.deleteById(id);
    }

    /**
     * 校验ERP客户是否属于当前租户关联的公司
     *
     * @param customerCode ERP客户编码
     * @return 是否属于
     */
    public boolean isCustomerBelongsToCurrentTenant(String customerCode) {
        if (StringUtils.isBlank(customerCode)) {
            return false;
        }

        List<String> companyIds = getCurrentTenantCompanyIds();
        if (companyIds.isEmpty()) {
            // 如果租户没有配置公司映射，暂时允许（后续可改为拒绝）
            log.warn("租户[{}]未配置ERP公司映射，暂时允许所有客户", LoginHelper.getTenantId());
            return true;
        }

        // 获取ERP客户详情，检查其companyCode
        var customerDetail = erpIntegrationService.getCustomerDetail(customerCode);
        if (customerDetail == null) {
            return false;
        }

        String customerCompanyCode = (String) customerDetail.get("companyCode");
        return companyIds.contains(customerCompanyCode);
    }

    /**
     * 获取租户的ERP公司筛选条件（用于ERP客户查询）
     *
     * @return companyIds字符串（逗号分隔），如果未配置返回null
     */
    public String getCompanyFilterForCurrentTenant() {
        List<String> companyIds = getCurrentTenantCompanyIds();
        if (companyIds.isEmpty()) {
            return null;
        }
        return companyIds.stream().collect(Collectors.joining(","));
    }
}