package com.ruoyi.ibs.list.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.ibs.list.domain.*;
import com.ruoyi.ibs.list.mapper.CustLeadImageMapper;
import com.ruoyi.ibs.list.mapper.CustLeadRegMapper;
import com.ruoyi.system.domain.OssFileUploadDTO;
import com.ruoyi.system.enums.OssFileEnum;
import com.ruoyi.system.service.OssFileService;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author 吴凯程
 * @Date 2025/10/3
 **/
@Service
@Slf4j
public class CustLeadRegService {
    @Resource
    private OssFileService ossFileService;

    @Resource
    private CustLeadRegMapper custLeadRegMapper;

    @Resource
    private CustLeadImageMapper custLeadImageMapper;

    public List<CustLeadReg> selectList(CustLeadRegListDTO custLeadRegListDTO){
        LambdaQueryWrapper<CustLeadReg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(CustLeadReg::getCreateBy, SecurityUtils.getHeadId());
        if (Objects.nonNull(custLeadRegListDTO.getKeyword())){
            queryWrapper.like(CustLeadReg::getCustName, custLeadRegListDTO.getKeyword());
        }
        if(Objects.nonNull(custLeadRegListDTO.getRegStatus())){
            queryWrapper.eq(CustLeadReg::getRegStatus, custLeadRegListDTO.getRegStatus());
        }
        queryWrapper.orderByAsc(CustLeadReg::getRegStatus);
        return custLeadRegMapper.selectList(queryWrapper);
    }


    /**
     * 新增客户登记信息
     *
     * @param custLeadRegDTO 客户登记信息传输对象，包含客户的基本信息和图片列表
     * @return 操作结果提示信息："潜在客户信息保存成功"
     * @throws ServiceException 当新增客户登记失败时抛出异常
     */
    @Transactional(rollbackFor = Exception.class)
    public String addCustLeadReg(CustLeadRegDTO custLeadRegDTO){
        String uuid = IdUtils.fastSimpleUUID();
        CustLeadReg custLeadReg = new CustLeadReg();
        custLeadReg.setId(uuid);
        custLeadReg.setRegStatus(Boolean.FALSE);
        BeanUtils.copyProperties(custLeadRegDTO,custLeadReg);
        if (custLeadRegMapper.insert(custLeadReg) < 1){
            throw new ServiceException("新增客户登记失败") ;
        }
        // 如果存在图片列表，则上传图片到OSS并保存图片关联关系
        if (custLeadRegDTO.getImageList() != null && !custLeadRegDTO.getImageList().isEmpty()){
            ArrayList<String> msgList = new ArrayList<>();
            msgList.add(SecurityUtils.getUsername());
            msgList.add(custLeadRegDTO.getCustName());
            uploadCustLeadImagesToOss(custLeadRegDTO.getImageList(), msgList, uuid);
        }
        return "潜在客户信息保存成功";
    }

    /**
     * 更新客户登记状态（开户状态）
     *
     * @param custId 客户ID
     * @return 操作结果提示信息："潜在客户开户状态修改成功"
     * @throws ServiceException 当客户登记信息不存在时抛出异常
     */
    public String updateCustLeadRegStatus(String custId){
        CustLeadReg custLeadReg = custLeadRegMapper.selectById(custId);
        if (Objects.isNull(custLeadReg)){
            throw new ServiceException("客户登记信息不存在");
        }
        custLeadReg.setRegStatus(!custLeadReg.getRegStatus());
        custLeadRegMapper.updateById(custLeadReg);
        return "潜在客户开户状态修改成功";
    }

    /**
     * 根据客户ID获取客户登记信息
     *
     * @param custId 客户ID
     * @return 客户登记信息视图对象，包含客户基本信息和图片列表（Base64格式）
     * @throws ServiceException 当客户登记信息不存在时抛出异常
     */
    public CustLeadRegVO getCustLeadReg(String custId){
        CustLeadReg custLeadReg = custLeadRegMapper.selectById(custId);
        if (Objects.isNull(custLeadReg)){
            throw new ServiceException("客户登记信息不存在");
        }
        CustLeadRegVO custLeadRegVO = new CustLeadRegVO();
        BeanUtils.copyProperties(custLeadReg,custLeadRegVO);
        List<String> imageList = downloadCustLeadImagesToOss(custId);
        custLeadRegVO.setImageList(imageList);
        return custLeadRegVO;
    }

    /**
     * 上传客户登记图片到OSS
     *
     * @param imageList 图片文件列表
     * @param msgList 水印文本信息列表，包含用户名、客户名称和地址
     * @param custId 客户UUID，用于关联图片与客户
     */
    private void uploadCustLeadImagesToOss(List<MultipartFile> imageList, List<String> msgList, String custId){
        for (int i = 0; i < imageList.size(); i++) {
            OssFileUploadDTO ossFileUploadDTO = new OssFileUploadDTO();
            MultipartFile compressImage = ImageUtils.compressPictureForScale(imageList.get(i), 512);
            MultipartFile file = ImageUtils.addMultilineTextWatermark(compressImage, msgList, Positions.CENTER, 0.7f);
            ossFileUploadDTO.setFile(file);
            ossFileUploadDTO.setOssFileEnum(OssFileEnum.CUST_LEAD_IMAGE);
            ossFileUploadDTO.setUserName(SecurityUtils.getUsername());
            String fileId = ossFileService.uploadFileToOss(ossFileUploadDTO);

            CustLeadImage custLeadImage = new CustLeadImage();
            custLeadImage.setFileId(fileId);
            custLeadImage.setCustUuid(custId);
            custLeadImageMapper.insert(custLeadImage);
            log.info("上传第{}张图片到OSS成功，总共{}张", i + 1, imageList.size());
        }
    }

    /**
     * 从OSS下载客户登记图片
     *
     * @param custId 客户ID
     * @return 图片Base64字符串列表
     */
    private List<String> downloadCustLeadImagesToOss(String custId) {
        List<String> imageList = new ArrayList<>();

        LambdaQueryWrapper<CustLeadImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustLeadImage::getCustUuid, custId);
        List<CustLeadImage> custLeadImages = custLeadImageMapper.selectList(queryWrapper);
        if (custLeadImages.isEmpty()){
            return imageList;
        }
        for (CustLeadImage custLeadImage:custLeadImages) {
            MultipartFile fileFromOss = ossFileService.getFileFromOss(custLeadImage.getFileId());
            imageList.add(ImageUtils.multiplePartFileToBase64(fileFromOss));
        }
        return imageList;
    }

}
