package org.hzhub.erp.service.impl;

import lombok.RequiredArgsConstructor;
import org.hzhub.erp.common.page.TableDataInfo;
import org.hzhub.erp.domain.vo.CustomerVO;
import org.hzhub.erp.mapper.CustomerMapper;
import org.hzhub.erp.mapper.SalesOrganizationMapper;
import org.hzhub.erp.service.ICustomerService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 客户档案 Service 实现
 */
@Service
@RequiredArgsConstructor
public class CustomerServiceImpl implements ICustomerService {

    private final CustomerMapper customerMapper;
    private final SalesOrganizationMapper salesOrganizationMapper;

    @Override
    public TableDataInfo<CustomerVO> queryCustomerList(int pageNum, int pageSize, String keyword,
                                                         String companyCode, String salesAreaCode, String brand) {
        long total = customerMapper.selectCustomerCount(keyword, companyCode, salesAreaCode, brand);
        List<CustomerVO> list = customerMapper.selectCustomerPage(pageNum, pageSize, keyword, companyCode, salesAreaCode, brand);
        return new TableDataInfo<>(list, total);
    }

    @Override
    public CustomerVO getCustomerDetail(String customerCode) {
        return customerMapper.selectCustomerDetail(customerCode);
    }

    @Override
    public List<CustomerVO> getSalesAreas() {
        // 从 OSDORG 表获取销区数据
        return salesOrganizationMapper.selectSalesAreasFromOrg();
    }

    @Override
    public List<CustomerVO> getBrands() {
        return customerMapper.selectBrands();
    }

    @Override
    public TableDataInfo<CustomerVO> queryCustomerSelectList(int pageNum, int pageSize, String keyword, String companyIds) {
        // 解析companyIds为列表
        List<String> companyIdList = Collections.emptyList();
        if (companyIds != null && !companyIds.isBlank()) {
            companyIdList = Arrays.asList(companyIds.split(","));
        }

        long total = customerMapper.selectCustomerSelectCount(keyword, companyIds, companyIdList);
        List<CustomerVO> list = customerMapper.selectCustomerSelectPage(pageNum, pageSize, keyword, companyIds, companyIdList);
        return new TableDataInfo<>(list, total);
    }
}
