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

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.visit.controller.admin.product.vo.ProductPageReqVO;
import cn.iocoder.yudao.module.visit.dal.dataobject.product.ProductDO;
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 javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import cn.iocoder.yudao.module.visit.controller.admin.customerinfo.vo.*;
import cn.iocoder.yudao.module.visit.dal.dataobject.customerinfo.CustomerInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.visit.dal.mysql.customerinfo.CustomerInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.visit.enums.ErrorCodeConstants.*;

/**
 * 客户信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class CustomerInfoServiceImpl implements CustomerInfoService {

    @Resource
    private CustomerInfoMapper customerInfoMapper;

    @Resource
    private FileService fileService;

    @Override
    public Long createCustomerInfo(CustomerInfoSaveReqVO createReqVO) {
        // 插入
        CustomerInfoDO customerInfo = BeanUtils.toBean(createReqVO, CustomerInfoDO.class);
        //校验companyName是否重复
        CustomerInfoDO customerInfoDO = customerInfoMapper.selectByCompanyName(customerInfo.getCompanyName());
        if (customerInfoDO != null) {
            throw exception(CUSTOMER_INFO_COMPANY_NAME_DUPLICATE);
        }
        String url = uploadMapImageByUrl(customerInfo.getLocationImage(), null);
        customerInfo.setLocationImage(url);
        customerInfoMapper.insert(customerInfo);
        // 返回
        return customerInfo.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 updateCustomerInfo(CustomerInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateCustomerInfoExists(updateReqVO.getId());
        // 更新
        CustomerInfoDO updateObj = BeanUtils.toBean(updateReqVO, CustomerInfoDO.class);
        CustomerInfoDO customerInfoDO = customerInfoMapper.selectByCompanyName(updateObj.getCompanyName());
        if (customerInfoDO != null && !customerInfoDO.getId().equals(updateObj.getId())) {
            throw exception(CUSTOMER_INFO_COMPANY_NAME_DUPLICATE);
        }
        if (updateObj.getLocationImage() != null&& updateObj.getLocationImage().startsWith("https://apis.map.qq.com/ws/staticmap/v2/")){
            String url = uploadMapImageByUrl(updateObj.getLocationImage(), null);
            updateObj.setLocationImage(url);
        }
        customerInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteCustomerInfo(Long id) {
        // 校验存在
        validateCustomerInfoExists(id);
        // 删除
        customerInfoMapper.deleteById(id);
    }

    private void validateCustomerInfoExists(Long id) {
        if (customerInfoMapper.selectById(id) == null) {
            throw exception(CUSTOMER_INFO_NOT_EXISTS);
        }
    }

    @Override
    public CustomerInfoDO getCustomerInfo(Long id) {
        return customerInfoMapper.selectById(id);
    }

    @Override
    public PageResult<CustomerInfoDO> getCustomerInfoPage(CustomerInfoPageReqVO pageReqVO) {
        return customerInfoMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CustomerInfoDO> getCustomerInfoByCompanyName(String companyName) {
        return customerInfoMapper.selectListByCompanyName(companyName);
    }
    @Override
    public List<CustomerInfoDO> getCustomerInfoByContact(String contact) {
        return customerInfoMapper.selectListByContact(contact);
    }

    @Override
    public List<CustomerInfoDO> getAllCustomerInfo() {
        return customerInfoMapper.selectList();
    }

    @Override
    public CustomerImportRespVO importCustomerList(List<CustomerImportExcelVO> list, Boolean updateSupport) {
        // 1 参数校验
        if (CollUtil.isEmpty(list)) {
            throw exception(CUSTOMER_INFO_IMPORT_LIST_IS_EMPTY);
        }

        // 2. 遍历，逐个创建 or 更新
        CustomerImportRespVO respVO = CustomerImportRespVO.builder().createCompanyNames(new ArrayList<>())
                .updateCompanyNames(new ArrayList<>()).failureCompanyNames(new LinkedHashMap<>()).build();
        list.forEach(importCompany -> {

            // 2.1.1 校验，判断是否有不符合的原因
            try {
                validateCompanyUnique(importCompany.getCompanyName());
            } catch (ServiceException ex) {
                respVO.getFailureCompanyNames().put(importCompany.getCompanyName(), ex.getMessage());
                return;
            }

            // 2.2.1 判断如果不存在，在进行插入
            CustomerInfoDO existCompany = customerInfoMapper.selectByCompanyName(importCompany.getCompanyName());
            if (existCompany == null) {
                customerInfoMapper.insert(BeanUtils.toBean(importCompany, CustomerInfoDO.class));
                respVO.getCreateCompanyNames().add(importCompany.getCompanyName());
            }
        });
        return respVO;
    }

    private void validateCompanyUnique(String companyName) {
        CustomerInfoPageReqVO customerPageReqVO = new CustomerInfoPageReqVO();
        customerPageReqVO.setCompanyName(companyName);
        PageResult<CustomerInfoDO> customerInfoDOPageResult = customerInfoMapper.selectPage(customerPageReqVO);
        if (customerInfoDOPageResult.getTotal() > 0) {
            throw exception(CUSTOMER_INFO_EXISTS);
        }
    }
}