package cn.iocoder.yudao.module.visit.service.info;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.visit.controller.admin.customerinfo.vo.CustomerInfoSaveReqVO;
import cn.iocoder.yudao.module.visit.controller.admin.info.vo.InfoPageReqVO;
import cn.iocoder.yudao.module.visit.controller.admin.info.vo.InfoPrintVO;
import cn.iocoder.yudao.module.visit.controller.admin.info.vo.InfoSaveReqVO;
import cn.iocoder.yudao.module.visit.dal.dataobject.customerinfo.CustomerInfoDO;
import cn.iocoder.yudao.module.visit.dal.dataobject.info.InfoDO;
import cn.iocoder.yudao.module.visit.dal.mysql.customerinfo.CustomerInfoMapper;
import cn.iocoder.yudao.module.visit.dal.mysql.info.InfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.visit.enums.ErrorCodeConstants.INFO_LIST_NOT_EXISTS;
import static cn.iocoder.yudao.module.visit.enums.ErrorCodeConstants.INFO_NOT_EXISTS;
import static java.nio.file.Files.createFile;

/**
 * 客户拜访记录 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class InfoServiceImpl implements InfoService {

    private static final Logger log = LoggerFactory.getLogger(InfoServiceImpl.class);
    @Resource
    private InfoMapper infoMapper;

    @Resource
    private CustomerInfoMapper customerInfoMapper;

    @Resource
    private FileService fileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createInfo(InfoSaveReqVO createReqVO) {
        // 插入
        InfoDO info = BeanUtils.toBean(createReqVO, InfoDO.class);
        String url = uploadMapImageByUrl(info.getLocationImage(), null);
        info.setLocationImage(url);
        int insert = infoMapper.insert(info);
        if (insert >0){
            //拜访记录插入成功，根据【公司名称】判断该客户是否记录在案，如果没有，则插入一条客户信息
            CustomerInfoDO customerInfoDO = customerInfoMapper.selectByCompanyName(info.getCompanyName());
            if (customerInfoDO == null){
                //没查到说明该客户没有记录，插入一条客户信息
                CustomerInfoSaveReqVO customerInfoSaveReqVO = new CustomerInfoSaveReqVO();
                customerInfoSaveReqVO.setCustomerName(info.getCustomerName());
                customerInfoSaveReqVO.setContact(info.getContact());
                customerInfoSaveReqVO.setCompanyName(info.getCompanyName());
                customerInfoSaveReqVO.setCustomerType(info.getCustomerStatus());
                customerInfoSaveReqVO.setDepartment(info.getDepartment());
                customerInfoSaveReqVO.setProvinceName(info.getProvinceName());
                customerInfoSaveReqVO.setCityName(info.getCityName());
                customerInfoSaveReqVO.setAreaName(info.getAreaName());
                customerInfoSaveReqVO.setRegionFullName(info.getRegionFullName());
                customerInfoSaveReqVO.setLocationText(info.getLocationText());
                customerInfoSaveReqVO.setLongitude(info.getLongitude());
                customerInfoSaveReqVO.setLatitude(info.getLatitude());
                customerInfoSaveReqVO.setLocationImage(info.getLocationImage());
                customerInfoSaveReqVO.setProductIds(info.getVisitProductIds());
                customerInfoSaveReqVO.setProductNames(info.getVisitProductNames());
                customerInfoMapper.insert(BeanUtils.toBean(customerInfoSaveReqVO, CustomerInfoDO.class));
            }
        }

        // 返回
        return info.getId();
    }

    public String uploadMapImageByUrl(String imageUrl, String directory) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String fixedUrl = imageUrl.replace("|", "%7C");
            HttpGet request = new HttpGet(fixedUrl);
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                HttpEntity entity = response.getEntity();
                byte[] content = EntityUtils.toByteArray(entity);

                // 文件名：你可以从 URL 中提取或自定义
                String name = "map_" + System.currentTimeMillis() + ".jpg";
                String type = ContentType.getOrDefault(entity).getMimeType();

                // 调用你已有的 createFile 方法
                return fileService.createFile(content, name, directory, type);
            }
        } catch (IOException e) {
            throw new RuntimeException("下载地图图片失败：" + imageUrl, e);
        }
    }

    @Override
    public void updateInfo(InfoSaveReqVO updateReqVO) {
        // 校验存在
        validateInfoExists(updateReqVO.getId());
        // 更新
        InfoDO updateObj = BeanUtils.toBean(updateReqVO, InfoDO.class);
        //按id查询获取companyId原本归属
        InfoDO infoDO = infoMapper.selectById(updateReqVO.getId());
        if (updateObj.getLocationImage() != null&& updateObj.getLocationImage().startsWith("https://apis.map.qq.com/ws/staticmap/v2/")){
            String url = uploadMapImageByUrl(updateObj.getLocationImage(), null);
            updateObj.setLocationImage(url);
        }
        if (infoDO != null){
            updateObj.setCompanyId(infoDO.getCompanyId());
        }
        infoMapper.updateById(updateObj);
    }

    @Override
    public void deleteInfo(Long id) {
        // 校验存在
        validateInfoExists(id);
        // 删除
        infoMapper.deleteById(id);
    }



    @Override
    public void deleteInfoByIds(List<Long> idList) {
        //  校验存在
        if(infoMapper.selectByIds(idList).size()  != idList.size()){
            throw exception(INFO_LIST_NOT_EXISTS);
        }
        // 删除
        infoMapper.deleteByIds(idList);
    }

    @Override
    public List<InfoPrintVO> getUnionAllInfoByIds(List<InfoDO> list) {
        List<InfoPrintVO> vos = new ArrayList<>();
        if (list.isEmpty()){
            return vos;
        }
        List<List<InfoDO>> groupedByCompany = list.stream()
                // 按 (companyName, companyId) 组合分组
                .collect(Collectors.groupingBy(info -> info.getCompanyName() + "::" + info.getCompanyId()))
                .values().stream()
                .map(companyRecords ->
                        companyRecords.stream()
                                .sorted(Comparator.comparing(InfoDO::getVisitDate).reversed()) // 按时间降序
                                .limit(4) // 取前 4 条
                                .collect(Collectors.toList())
                )
                .collect(Collectors.toList());

        groupedByCompany.forEach(info -> {
            //服务内容（最近四次）
            List<String> serviceContent = new ArrayList<>();
            //服务图片（最多四张）
            List<String> serviceImages = new ArrayList<>();
            //拜访时间记录
            List<LocalDate> visitDateList = new ArrayList<>();
            //以第一个公司名称作为合并打印的公司
            //取最多4张服务图片
            int maxImages = 4;
            for (InfoDO infoDO : info) {
                if (serviceImages.size() >= maxImages) break;

                String imagesStr = infoDO.getServiceImages();
                if (StringUtils.isNotBlank(imagesStr)) {
                    List<String> imageList = Arrays.asList(imagesStr.split(","));
                    int remaining = maxImages - serviceImages.size();
                    serviceImages.addAll(imageList.stream().limit(remaining).collect(Collectors.toList()));
                }
            }
            //获取客户拜访记录成功，获取客户信息
            info.forEach(infoDO -> {
                //服务内容记录
                serviceContent.add(infoDO.getServiceContent());
                //拜访时间记录
                visitDateList.add(infoDO.getVisitDate().toLocalDate());
            });
            //下面获取客户信息
            InfoPrintVO infoPrintVO = new InfoPrintVO();
            InfoDO infoDO = info.get(0);
            if (infoDO != null){
                infoPrintVO.setVisitProductNames(infoDO.getVisitProductNames());//本次拜访品种
                infoPrintVO.setCompanyName(infoDO.getCompanyName());//公司名称
                infoPrintVO.setSalesman(infoDO.getCreator());//拜访记录的创建者就是该记录的业务员
                infoPrintVO.setLocationImage(infoDO.getLocationImage());//公司定位图
                infoPrintVO.setContact(infoDO.getContact());
                infoPrintVO.setDepartment(infoDO.getDepartment());
            }
            //添加多次的信息
            infoPrintVO.setServiceContent(serviceContent);
            infoPrintVO.setVisitDate(visitDateList);
            infoPrintVO.setServiceImages(String.join(",", serviceImages));
            //拜访次数
            infoPrintVO.setServiceCount(info.size());
            vos.add(infoPrintVO);
        });
        return vos;
    }

    private void validateInfoExists(Long id) {
        if (infoMapper.selectById(id) == null) {
            throw exception(INFO_NOT_EXISTS);
        }
    }

    @Override
    public InfoDO getInfo(Long id) {
        return infoMapper.selectById(id);
    }

    @Override
    public PageResult<InfoDO> getInfoPage(InfoPageReqVO pageReqVO) {
        return infoMapper.selectPage(pageReqVO);
    }

    @Override
    public List<InfoPrintVO> getInfoByIds(List<Long> ids) {
        List<InfoPrintVO> vos = new ArrayList<>();
        //先获取客户拜访记录
        List<InfoDO> info = infoMapper.selectByIds(ids);
        if (info != null && !info.isEmpty()){
            //获取客户拜访记录成功，获取客户信息
            info.forEach(infoDO -> {
                InfoPrintVO infoPrintVO = new InfoPrintVO();
                infoPrintVO.setServiceContent(Collections.singletonList(infoDO.getServiceContent()));//本次服务内容
                //服务图片（最多10张）
                String imagesStr = infoDO.getServiceImages();
                if (StringUtils.isNotBlank(imagesStr)) {
                    String limitedImagesStr = Arrays.stream(imagesStr.split(","))
                            .limit(10)
                            .collect(Collectors.joining(","));
                    infoPrintVO.setServiceImages(limitedImagesStr);
                } else {
                    infoPrintVO.setServiceImages("");
                }
                infoPrintVO.setVisitProductNames(infoDO.getVisitProductNames());//本次拜访品种
                infoPrintVO.setCompanyName(infoDO.getCompanyName());//公司名称
                infoPrintVO.setDepartment(infoDO.getDepartment());//部门
                infoPrintVO.setContact(infoDO.getContact());//联系方式
                infoPrintVO.setSalesman(infoDO.getCreator());//拜访记录的创建者就是该记录的业务员
                infoPrintVO.setLocationImage(infoDO.getLocationImage());
                infoPrintVO.setVisitDate(Collections.singletonList(infoDO.getVisitDate().toLocalDate()));
                //拜访次数按拜访id打印都是1
                infoPrintVO.setServiceCount(1);
                vos.add(infoPrintVO);
            });
        }
        return vos;
    }

    @Override
    public InfoPrintVO getInfoByCompanyName(String companyName) {
        InfoPrintVO infoPrintVO = new InfoPrintVO();
        //服务内容（最近五次）
        List<String> serviceContent = new ArrayList<>();
        //服务图片（最多十张）
        List<String> serviceImages = new ArrayList<>();
        //拜访时间记录
        List<LocalDate> visitDateList = new ArrayList<>();
        // 获取当前年月（用于比较月份）
        YearMonth currentYearMonth = YearMonth.now();
        //现根据客户名称获取历史拜访记录
        List<InfoDO> info = infoMapper.selectByCompanyName(companyName);

        System.out.println("拜访信息" + info);

        if (info != null && !info.isEmpty()){
            //取最近五次
            info = info.stream()
                    // 筛选本月记录（基于 LocalDateTime）
//                    .filter(infoDO -> {
//                        LocalDateTime visitDateTime = infoDO.getVisitDate();
//                        return YearMonth.from(visitDateTime.toLocalDate()).equals(currentYearMonth);
//                    })
                    .sorted(Comparator.comparing(InfoDO::getVisitDate)).limit(5).collect(Collectors.toList());
            //取最多10张服务图片
            int maxImages = 10;
            int maxObjects = 5; // 最多处理5个对象
            int objectCount = 0; // 对象计数器
            for (InfoDO infoDO : info) {
                // 超过最大对象数或已收集足够图片则停止
                if (objectCount >= maxObjects || serviceImages.size() >= maxImages) break;

                String imagesStr = infoDO.getServiceImages();
                if (StringUtils.isNotBlank(imagesStr)) {
                    List<String> imageList = Arrays.asList(imagesStr.split(","));
                    int remaining = maxImages - serviceImages.size();
                    // 每个对象最多取2张，同时不超过剩余需要数量
                    int take = Math.min(2, remaining);
                    serviceImages.addAll(imageList.stream().limit(take).collect(Collectors.toList()));
                }
                objectCount++;
            }
            //获取客户拜访记录成功，获取客户信息
            info.forEach(infoDO -> {
                //服务内容记录
                serviceContent.add(infoDO.getServiceContent());
                //拜访时间记录
                visitDateList.add(infoDO.getVisitDate().toLocalDate());
            });
            //下面获取客户信息
//            CustomerInfoDO customerInfoDO = customerInfoMapper.selectByCompanyName(companyName,companyId);//这个companyId是从根据companyId获取得数据List中获取得，一定和点得这条匹配
            //根据第一条数据去展示
            InfoDO infoDO1 = info.get(0);
            infoPrintVO.setVisitProductNames(infoDO1.getVisitProductNames());//本次拜访品种
            infoPrintVO.setCompanyName(infoDO1.getCompanyName());//公司名称
            infoPrintVO.setSalesman(infoDO1.getCreator());//拜访记录的创建者就是该记录的业务员
            infoPrintVO.setLocationImage(infoDO1.getLocationImage());//公司定位图
            infoPrintVO.setContact(infoDO1.getContact());
            infoPrintVO.setDepartment(infoDO1.getDepartment());
            //添加多次的信息
            infoPrintVO.setServiceContent(serviceContent);
            infoPrintVO.setVisitDate(visitDateList);
            infoPrintVO.setServiceImages(String.join(",", serviceImages));
            //拜访次数
            infoPrintVO.setServiceCount(info.size());
        }else {
            return infoPrintVO;
        }
        return infoPrintVO;
    }

    @Override
    public List<InfoPrintVO> getUnionInfoByIds(List<Long> idList) {
        List<InfoPrintVO> vos = new ArrayList<>();

        //现根据客户名称获取历史拜访记录
        List<InfoDO> infoAll = infoMapper.selectByIds(idList);

        if (infoAll != null && !infoAll.isEmpty()){

            List<List<InfoDO>> groupedByCompany = infoAll.stream()
                    // 按公司名称分组,取每个公司最近四次（结果：Map<String, List<InfoDO>>）
                    .collect(Collectors.groupingBy(InfoDO::getCompanyName))
                    .values().stream() // 遍历每个公司的记录列表
                    .map(companyRecords ->
                            companyRecords.stream()
                                    // 按拜访时间降序排序
                                    .sorted(Comparator.comparing(InfoDO::getVisitDate).reversed())
                                    .limit(4) // 取最近 4 条
                                    .collect(Collectors.toList())
                    )
                    .collect(Collectors.toList()); // 收集为 List<List<InfoDO>>
            groupedByCompany.forEach(info -> {
                //服务内容（最近四次）
                List<String> serviceContent = new ArrayList<>();
                //服务图片（最多四张）
                List<String> serviceImages = new ArrayList<>();
                //拜访时间记录
                List<LocalDate> visitDateList = new ArrayList<>();
                //以第一个公司名称作为合并打印的公司
//                String companyName = info.get(0).getCompanyName();
//                Long companyId = info.get(0).getCompanyId();
                //取最多4张服务图片
                int maxImages = 4;
                for (InfoDO infoDO : info) {
                    if (serviceImages.size() >= maxImages) break;

                    String imagesStr = infoDO.getServiceImages();
                    if (StringUtils.isNotBlank(imagesStr)) {
                        List<String> imageList = Arrays.asList(imagesStr.split(","));
                        int remaining = maxImages - serviceImages.size();
                        serviceImages.addAll(imageList.stream().limit(remaining).collect(Collectors.toList()));
                    }
                }
                //获取客户拜访记录成功，获取客户信息
                info.forEach(infoDO -> {
                    //服务内容记录
                    serviceContent.add(infoDO.getServiceContent());
                    //拜访时间记录
                    visitDateList.add(infoDO.getVisitDate().toLocalDate());
                });
                //下面获取客户信息
                InfoPrintVO infoPrintVO = new InfoPrintVO();
//                CustomerInfoDO customerInfoDO = customerInfoMapper.selectByCompanyName(companyName,companyId);
                InfoDO infoDO = info.get(0);

                if (infoDO != null){
                    infoPrintVO.setVisitProductNames(infoDO.getVisitProductNames());//本次拜访品种
                    infoPrintVO.setCompanyName(infoDO.getCompanyName());//公司名称
                    infoPrintVO.setSalesman(infoDO.getCreator());//拜访记录的创建者就是该记录的业务员
                    infoPrintVO.setLocationImage(infoDO.getLocationImage());//公司定位图
                    infoPrintVO.setContact(infoDO.getContact());
                    infoPrintVO.setDepartment(infoDO.getDepartment());
                }
                //添加多次的信息
                infoPrintVO.setServiceContent(serviceContent);
                infoPrintVO.setVisitDate(visitDateList);
                infoPrintVO.setServiceImages(String.join(",", serviceImages));
                //拜访次数
                infoPrintVO.setServiceCount(info.size());
                vos.add(infoPrintVO);
            });
        }
        return vos;
    }

}