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.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.LocalDateTime;
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_NOT_EXISTS;
import static java.nio.file.Files.createFile;

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

    @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);
        if (updateObj.getLocationImage() != null&& updateObj.getLocationImage().startsWith("https://apis.map.qq.com/ws/staticmap/v2/")){
            String url = uploadMapImageByUrl(updateObj.getLocationImage(), null);
            updateObj.setLocationImage(url);
        }
        infoMapper.updateById(updateObj);
    }

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

    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()));//本次服务内容
                //服务图片（最多四张）
                String imagesStr = infoDO.getServiceImages();
                if (StringUtils.isNotBlank(imagesStr)) {
                    String limitedImagesStr = Arrays.stream(imagesStr.split(","))
                            .limit(4)
                            .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()));
                //拜访次数按拜访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<LocalDateTime> visitDateList = new ArrayList<>();
        //现根据客户名称获取历史拜访记录
        List<InfoDO> info = infoMapper.selectByCompanyName(companyName);
        if (info != null && !info.isEmpty()){
            //取最近四次
            info = info.stream().sorted(Comparator.comparing(InfoDO::getVisitDate).reversed()).limit(4).collect(Collectors.toList());
            //取最多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());
            });
            //下面获取客户信息
            CustomerInfoDO customerInfoDO = customerInfoMapper.selectByCompanyName(companyName);
            infoPrintVO.setVisitProductNames(customerInfoDO.getProductNames());//本次拜访品种
            infoPrintVO.setCompanyName(customerInfoDO.getCompanyName());//公司名称
            infoPrintVO.setSalesman(customerInfoDO.getCreator());//拜访记录的创建者就是该记录的业务员
            infoPrintVO.setLocationImage(customerInfoDO.getLocationImage());//公司定位图
            infoPrintVO.setContact(customerInfoDO.getContact());
            infoPrintVO.setDepartment(customerInfoDO.getDepartment());
            //添加多次的信息
            infoPrintVO.setServiceContent(serviceContent);
            infoPrintVO.setVisitDate(visitDateList);
            infoPrintVO.setServiceImages(String.join(",", serviceImages));
            //拜访次数
            infoPrintVO.setServiceCount(info.size());
        }else {
            return null;
        }
        return infoPrintVO;
    }

}