package com.tourism.webadmin.app.website.service.impl;


import com.tourism.common.additional.utils.StringUtils;
import com.tourism.common.core.upload.BaseUpDownloader;
import com.tourism.common.core.upload.UpDownloaderFactory;
import com.tourism.common.core.upload.UploadResponseInfo;
import com.tourism.common.core.upload.UploadStoreTypeEnum;
import com.tourism.webadmin.app.website.service.CleanDataService;
import com.tourism.webadmin.back.dao.JobContentMapper;
import com.tourism.webadmin.back.dao.TourTourismTravelNotesContentMapper;
import com.tourism.webadmin.back.dao.TourismContentMapper;
import com.tourism.webadmin.back.dto.MultipartFileDto;
import com.tourism.webadmin.back.model.JobContent;
import com.tourism.webadmin.back.model.TourTourismTravelNotesContent;
import com.tourism.webadmin.back.model.TourismContent;
import com.tourism.webadmin.back.service.JobContentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tourism.webadmin.back.service.*;
import com.tourism.common.additional.config.ApplicationConfig;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 门户网站首页Service
 *
 * @author tourism
 */
@Slf4j
@Service("CleanDataService")
public class CleanDataServiceImpl implements CleanDataService {

    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private TourismContentService tourismContentService;
    @Autowired
    private TourTourismTravelNotesContentService tourTourismTravelNotesContentService;
    @Autowired
    private JobContentService jobContentService;
    @Autowired
    private UpDownloaderFactory upDownloaderFactory;
    @Autowired
    private TourTourismTravelNotesContentMapper tourTourismTravelNotesContentMapper;
    @Autowired
    private TourismContentMapper tourismContentMapper;
    @Autowired
    private JobContentMapper jobContentMapper;
    @Override
    public void cleanRichTextData() throws Exception {

        //对项目关联的富文本表进行数据清洗
        List<Long> tourismContentIdList = tourismContentMapper.selectAllIds();
        for (Long id : tourismContentIdList) {
            TourismContent tourismContent = tourismContentService.getById(id);
            if(tourismContent != null && StringUtils.isNotEmpty(tourismContent.getContent())){
                String content = tourismContent.getContent();
                if(StringUtils.isNotBlank(content)){
                    String processedTextContent = replaceImagesWithUrlsTourismContent(content);
                    tourismContent.setContent(processedTextContent);
                }

                String bookingNotice = tourismContent.getBookingNotice();
                if(StringUtils.isNotEmpty(bookingNotice)){
                    String processedTextBookingNotice = replaceImagesWithUrlsTourismContent(bookingNotice);
                    tourismContent.setBookingNotice(processedTextBookingNotice);
                }

                String costDescription = tourismContent.getCostDescription();
                if(StringUtils.isNotEmpty(costDescription)){
                    String processedTextCostDescription = replaceImagesWithUrlsTourismContent(costDescription);
                    tourismContent.setBookingNotice(processedTextCostDescription);
                }
                tourismContentService.updateById(tourismContent);
            }
        }
//        List<TourismContent> allList = tourismContentService.getAllList();
//        for(TourismContent tourismContent : allList){
//
//        }

        //对旅游游记的富文本表进行数据清洗
        List<Long> travelNotesIdList = tourTourismTravelNotesContentMapper.selectAllIds();
        for(Long travelNotesId : travelNotesIdList) {
            TourTourismTravelNotesContent tourTourismTravelNotesContent = tourTourismTravelNotesContentService.getById(travelNotesId);
            if (tourTourismTravelNotesContent != null && StringUtils.isNotEmpty(tourTourismTravelNotesContent.getContent())) {
                String content = tourTourismTravelNotesContent.getContent();
                if (StringUtils.isNotBlank(content)) {
                    String processedTextContent = replaceImagesWithUrlsTravelNotesContent(content);
                    tourTourismTravelNotesContent.setContent(processedTextContent);
                }

                String bookingNotice = tourTourismTravelNotesContent.getBookingNotice();
                if (StringUtils.isNotEmpty(bookingNotice)) {
                    String processedTextBookingNotice = replaceImagesWithUrlsTravelNotesContent(bookingNotice);
                    tourTourismTravelNotesContent.setBookingNotice(processedTextBookingNotice);
                }

                String costDescription = tourTourismTravelNotesContent.getCostDescription();
                if (StringUtils.isNotEmpty(costDescription)) {
                    String processedTextCostDescription = replaceImagesWithUrlsTravelNotesContent(costDescription);
                    tourTourismTravelNotesContent.setBookingNotice(processedTextCostDescription);
                }
                tourTourismTravelNotesContentService.updateById(tourTourismTravelNotesContent);
            }
        }
//        List<TourTourismTravelNotesContent> allListTravelNotesContent = tourTourismTravelNotesContentService.getAllList();
//        for(TourTourismTravelNotesContent tourTourismTravelNotesContent : allListTravelNotesContent){
//        }

        //对劳务富文本表进行数据清洗
        List<Long> jobContentIdList = jobContentMapper.selectAllIds();
        for(Long jobContentId : jobContentIdList) {
            JobContent jobContent = jobContentService.getById(jobContentId);
            if (jobContent != null && StringUtils.isNotEmpty(jobContent.getContent())) {
                String content = jobContent.getContent();
                if (StringUtils.isNotBlank(content)) {
                    String processedTextContent = replaceImagesWithUrlsJobContentContent(content);
                    jobContent.setContent(processedTextContent);
                }
                jobContentService.updateById(jobContent);
            }
        }
//        List<JobContent> allListJonContent = jobContentService.getAllList();
//        for(JobContent jobContent : allListJonContent) {
//            String content = jobContent.getContent();
//            if (StringUtils.isNotEmpty(content)) {
//                String processedTextContent = replaceImagesWithUrls(content);
//                jobContent.setContent(processedTextContent);
//            }
//        jobContentService.updateById(jobContent);
//        }
    }



//    public static String extractText(String richText) {
//        // 使用正则表达式提取汉字
//        Pattern textPattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
//        Matcher textMatcher = textPattern.matcher(richText);
//        StringBuilder textBuilder = new StringBuilder();
//
//        while (textMatcher.find()) {
//            textBuilder.append(textMatcher.group());
//        }
//
//        return textBuilder.toString();
//    }


    public String replaceImagesWithUrlsTourismContent(String richText) throws Exception {
        // 使用正则表达式提取图片的 Base64 数据
        Pattern imgPattern = Pattern.compile("<img.*?src\\s*=\\s*\"data:image/([^;]+);base64,([^\"]+)\"[^>]*?>", Pattern.CASE_INSENSITIVE);
        Matcher imgMatcher = imgPattern.matcher(richText);
        StringBuffer sb = new StringBuffer();

        while (imgMatcher.find()) {
//            String mimeType = imgMatcher.group(1);
            String base64Data = imgMatcher.group(2);
//            byte[] imageData = Base64.getDecoder().decode(base64Data);
//             根据字段注解中的存储类型，通过工厂方法获取匹配的上传下载实现类，从而解耦。
            BaseUpDownloader upDownloader = upDownloaderFactory.get(UploadStoreTypeEnum.HUAWEI_OBS_SYSTEM);
            MultipartFile multipartFile = base64ToMultipartFile(base64Data);
            UploadResponseInfo responseInfo = upDownloader.doUpload(null,
                    applicationConfig.getUploadFileBaseDir(), TourismContent.class.getSimpleName(), "ContentImages", true, multipartFile);
            String uploadPath = responseInfo.getUploadPath();

            // 替换图片的 src 属性
            //示例:https://v.xiaoyaotravel.com/image/TourTourismProjectTravelNotes/homeHotPicture/0063b1b69810401c9cef2a11c36dd14c.webp
            imgMatcher.appendReplacement(sb, "<img src=\"" + "https://v.xiaoyaotravel.com/" + uploadPath + "/"+responseInfo.getFilename() +"\"/>");
        }

        imgMatcher.appendTail(sb);
        return sb.toString();
    }

    public String replaceImagesWithUrlsTravelNotesContent(String richText) throws Exception {
        // 使用正则表达式提取图片的 Base64 数据
        Pattern imgPattern = Pattern.compile("<img.*?src\\s*=\\s*\"data:image/([^;]+);base64,([^\"]+)\"[^>]*?>", Pattern.CASE_INSENSITIVE);
        Matcher imgMatcher = imgPattern.matcher(richText);
        StringBuffer sb = new StringBuffer();

        while (imgMatcher.find()) {
//            String mimeType = imgMatcher.group(1);
            String base64Data = imgMatcher.group(2);
//            byte[] imageData = Base64.getDecoder().decode(base64Data);
//             根据字段注解中的存储类型，通过工厂方法获取匹配的上传下载实现类，从而解耦。
            BaseUpDownloader upDownloader = upDownloaderFactory.get(UploadStoreTypeEnum.HUAWEI_OBS_SYSTEM);
            MultipartFile multipartFile = base64ToMultipartFile(base64Data);
            UploadResponseInfo responseInfo = upDownloader.doUpload(null,
                    applicationConfig.getUploadFileBaseDir(), TourTourismTravelNotesContent.class.getSimpleName(), "ContentImages", true, multipartFile);
            String uploadPath = responseInfo.getUploadPath();

            // 替换图片的 src 属性
            //示例:https://v.xiaoyaotravel.com/image/TourTourismProjectTravelNotes/homeHotPicture/0063b1b69810401c9cef2a11c36dd14c.webp
            imgMatcher.appendReplacement(sb, "<img src=\"" + "https://v.xiaoyaotravel.com/" + uploadPath + "/"+responseInfo.getFilename() +"\"/>");
        }

        imgMatcher.appendTail(sb);
        return sb.toString();
    }

    public String replaceImagesWithUrlsJobContentContent(String richText) throws Exception {
        // 使用正则表达式提取图片的 Base64 数据
        Pattern imgPattern = Pattern.compile("<img.*?src\\s*=\\s*\"data:image/([^;]+);base64,([^\"]+)\"[^>]*?>", Pattern.CASE_INSENSITIVE);
        Matcher imgMatcher = imgPattern.matcher(richText);
        StringBuffer sb = new StringBuffer();

        while (imgMatcher.find()) {
//            String mimeType = imgMatcher.group(1);
            String base64Data = imgMatcher.group(2);
//            byte[] imageData = Base64.getDecoder().decode(base64Data);
//             根据字段注解中的存储类型，通过工厂方法获取匹配的上传下载实现类，从而解耦。
            BaseUpDownloader upDownloader = upDownloaderFactory.get(UploadStoreTypeEnum.HUAWEI_OBS_SYSTEM);
            MultipartFile multipartFile = base64ToMultipartFile(base64Data);
            UploadResponseInfo responseInfo = upDownloader.doUpload(null,
                    applicationConfig.getUploadFileBaseDir(), JobContent.class.getSimpleName(), "ContentImages", true, multipartFile);
            String uploadPath = responseInfo.getUploadPath();

            // 替换图片的 src 属性
            //示例:https://v.xiaoyaotravel.com/image/TourTourismProjectTravelNotes/homeHotPicture/0063b1b69810401c9cef2a11c36dd14c.webp
            imgMatcher.appendReplacement(sb, "<img src=\"" + "https://v.xiaoyaotravel.com/" + uploadPath + "/"+responseInfo.getFilename() +"\"/>");
        }

        imgMatcher.appendTail(sb);
        return sb.toString();
    }


    private static MultipartFile base64ToMultipartFile(String base64) throws Exception {
        // 去除可能存在的数据头（例如："data:image/png;base64,"）
//        String base64Data = base64.split(",")[1];

        // 解码Base64字符串到字节数组
        byte[] decodedBytes = Base64.getDecoder().decode(base64);

        // 创建一个输入流
        InputStream inputStream = new ByteArrayInputStream(decodedBytes);

        // 使用MockMultipartFile创建MultipartFile对象
        // 参数分别为：文件名、原始文件名、媒体类型、字节流
        MultipartFile multipartFile = new MultipartFileDto("file", "originalFileName.png", "image/png", inputStream);

        return multipartFile;
    }
}
