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.framework.security.core.util.SecurityFrameworkUtils;
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 customerInfoDO0 = customerInfoMapper.selectById(updateObj.getId());
        CustomerInfoDO customerInfoDO = customerInfoMapper.selectByCompanyName(updateObj.getCompanyName(), customerInfoDO0.getCompanyId());//修改的这条数据的所属分公司中，是否有重复的companyName
        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);
        }
        if (customerInfoDO != null) {
            updateObj.setCompanyId(customerInfoDO.getCompanyId());// 设置原本的companyId
        }
        customerInfoMapper.updateById(updateObj);
    }

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

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

    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 CustomerInfoDO getCustomerInfoByCompanyName(String companyName) {
        return customerInfoMapper.selectListByCompanyName(companyName);
    }
    @Override
    public List<CustomerInfoDO> getCustomerInfoByContact(String contact) {
        return customerInfoMapper.selectListByContact(contact);
    }

    @Override
    public List<CustomerInfoDO> getAllCustomerInfo() {
        Long companyId = SecurityFrameworkUtils.getLoginUserDeptId();
        return customerInfoMapper.selectList(companyId);
    }

    @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);
        }
    }
}