package com.fs.doctor.service.impl;

import com.fs.common.BeanCopyUtils;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyProduct;
import com.fs.company.mapper.CompanyProductMapper;
import com.fs.company.vo.DoctorCompanyUserVO;
import com.fs.doctor.domain.DoctorCompanyUser;
import com.fs.doctor.mapper.DoctorCompanyUserMapper;
import com.fs.doctor.service.IDoctorCompanyUserService;
import com.fs.doctor.vo.CompanyProductOptionVO;
import com.fs.doctor.vo.DoctorAndCompanyUserInfoVO;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 讲者业务员绑定Service业务层处理
 *
 * @author fs
 * @date 2025-12-30
 */
@Service
public class DoctorCompanyUserServiceImpl implements IDoctorCompanyUserService {
    @Autowired
    private DoctorCompanyUserMapper doctorCompanyUserMapper;
    @Autowired
    private CompanyProductMapper companyProductMapper;

    /**
     * 查询讲者业务员绑定
     *
     * @param id 讲者业务员绑定主键
     * @return 讲者业务员绑定
     */
    @Override
    public DoctorCompanyUser selectDoctorCompanyUserById(Long id) {
        return doctorCompanyUserMapper.selectDoctorCompanyUserById(id);
    }

    /**
     * 查询讲者业务员绑定列表
     *
     * @param doctorCompanyUser 讲者业务员绑定
     * @return 讲者业务员绑定
     */
    @Override
    public List<DoctorCompanyUserVO> selectDoctorCompanyUserList(DoctorCompanyUser doctorCompanyUser) {

        // 1) 查产品列表（别传 null，避免 mapper NPE）
        CompanyProduct query = new CompanyProduct();
        // 视业务决定是否加过滤：
        // query.setStatus(ProductStatus.ENABLED.getCode().longValue());
        // query.setDelFlag(0L);
        // query.setCompanyId(doctorCompanyUser.getCompanyId());
        List<CompanyProduct> companyProducts = companyProductMapper.selectCompanyProductList(query);

        // 2) 转 map（防重复）
        Map<String, String> productMap = companyProducts.stream()
                .filter(p -> p.getProductCode() != null)
                .collect(Collectors.toMap(
                        CompanyProduct::getProductCode,
                        CompanyProduct::getProductName,
                        (a, b) -> b
                ));

        // 3) 查绑定列表并复制 VO
        List<DoctorCompanyUser> doctorCompanyUsers =
                doctorCompanyUserMapper.selectDoctorCompanyUserList(doctorCompanyUser);
        List<DoctorCompanyUserVO> vos =
                BeanCopyUtils.copyList(doctorCompanyUsers, DoctorCompanyUserVO.class);

        // 4) 补 productName
        for (DoctorCompanyUserVO vo : vos) {
            String product = vo.getProduct();
            if (product == null || product.trim().isEmpty()) {
                vo.setProductName("");
                continue;
            }

            List<String> codes = Arrays.stream(product.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .distinct()
                    .collect(Collectors.toList());

            String productNameListStr = codes.stream()
                    .map(productMap::get)
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining(","));

            vo.setProductName(productNameListStr);
        }

        return vos;
    }


    /**
     * 新增讲者业务员绑定
     *
     * @param doctorCompanyUser 讲者业务员绑定
     * @return 结果
     */
    @Override
    public int insertDoctorCompanyUser(DoctorCompanyUser doctorCompanyUser) {
        doctorCompanyUser.setCreateTime(DateUtils.getNowDate());
        return doctorCompanyUserMapper.insertDoctorCompanyUser(doctorCompanyUser);
    }

    /**
     * 修改讲者业务员绑定
     *
     * @param doctorCompanyUser 讲者业务员绑定
     * @return 结果
     */
    @Override
    public int updateDoctorCompanyUser(DoctorCompanyUser doctorCompanyUser) {
        doctorCompanyUser.setUpdateTime(DateUtils.getNowDate());
        return doctorCompanyUserMapper.updateDoctorCompanyUser(doctorCompanyUser);
    }

    /**
     * 批量删除讲者业务员绑定
     *
     * @param ids 需要删除的讲者业务员绑定主键
     * @return 结果
     */
    @Override
    public int deleteDoctorCompanyUserByIds(Long[] ids) {
        return doctorCompanyUserMapper.deleteDoctorCompanyUserByIds(ids);
    }

    /**
     * 删除讲者业务员绑定信息
     *
     * @param id 讲者业务员绑定主键
     * @return 结果
     */
    @Override
    public int deleteDoctorCompanyUserById(Long id) {
        return doctorCompanyUserMapper.deleteDoctorCompanyUserById(id);
    }
    @Override
    public String queryProductGroup(Long companyId, String doctorId) {
        // 1) 查绑定关系
        List<DoctorCompanyUser> list = doctorCompanyUserMapper.queryProductGroup(companyId, doctorId);
        if (list == null || list.isEmpty()) {
            return "";
        }

        // 2) 合并所有 product 字段（逗号分割） -> 做并集去重
        Set<String> producCodeSet = new LinkedHashSet<>();

        for (DoctorCompanyUser item : list) {
            String product = item.getProduct(); // 例如 "1,2,3"
            if (product == null || product.trim().isEmpty()) {
                continue;
            }

            String[] arr = product.split(",");
            for (String s : arr) {
                if (s == null || s.trim().isEmpty()) {
                    continue;
                }
                try {
                    producCodeSet.add(s.trim());
                } catch (NumberFormatException ignore) {
                    // 避免脏数据导致接口报错
                }
            }
        }

        if (producCodeSet.isEmpty()) {
            return "";
        }

        // 3) 查产品名字（限制 companyId，防止串公司产品）
        List<CompanyProduct> products = doctorCompanyUserMapper.selectCompanyProductByProductCodes(new ArrayList<String>(producCodeSet));
        if (products == null || products.isEmpty()) {
            return "";
        }

        // 4) 拼 productName 字符串返回（逗号分隔）
        return products.stream()
                .map(CompanyProduct::getProductName)
                .filter(n -> n != null && !n.trim().isEmpty())
                .distinct()
                .collect(Collectors.joining(","));
    }

    @Override
    public DoctorCompanyUser selectCompanyUserByDoctorId(String doctorId) {
        return doctorCompanyUserMapper.selectCompanyUserByDoctorId(doctorId);
    }

    @Override
    public DoctorCompanyUser selectByDoctorIdAndCompanyUserId(String doctorId, String companyUserId) {
        return doctorCompanyUserMapper.selectByDoctorIdAndCompanyUserId(doctorId, companyUserId);
    }

    @Override
    public List<DoctorAndCompanyUserInfoVO> getDoctorOptionsByCompanyUser(Long companyId, Long companyUserId,String productCode ,String keyword) {
        if (companyId == null ) {
            return java.util.Collections.emptyList();
        }
        return doctorCompanyUserMapper.selectDoctorOptionsByCompanyUser(companyId, companyUserId, productCode, keyword);
    }

    @Override
    public List<CompanyProductOptionVO> getProductOptionsByCompanyUser(Long companyId, Long companyUserId, String keyword) {
        return doctorCompanyUserMapper.getProductOptionsByCompanyUser(companyId,companyUserId,keyword);
    }
}
