package org.jeecg.modules.okki.showlist.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.okki.common.service.IUploadService;
import org.jeecg.modules.okki.showlist.entity.OkkiShowlist;
import org.jeecg.modules.okki.showlist.entity.OkkiOverview;
import org.jeecg.modules.okki.showlist.entity.OkkiProductList;
import org.jeecg.modules.okki.showlist.entity.OkkiAdvantage;
import org.jeecg.modules.okki.showlist.entity.OkkiRecommendedProducts;
import org.jeecg.modules.okki.showlist.entity.OkkiKeywords;
import org.jeecg.modules.okki.showlist.entity.OkkiFaq;
import org.jeecg.modules.okki.showlist.entity.OkkiShowlistBlog;
import org.jeecg.modules.okki.showlist.mapper.OkkiOverviewMapper;
import org.jeecg.modules.okki.showlist.mapper.OkkiProductListMapper;
import org.jeecg.modules.okki.showlist.mapper.OkkiAdvantageMapper;
import org.jeecg.modules.okki.showlist.mapper.OkkiRecommendedProductsMapper;
import org.jeecg.modules.okki.showlist.mapper.OkkiKeywordsMapper;
import org.jeecg.modules.okki.showlist.mapper.OkkiFaqMapper;
import org.jeecg.modules.okki.showlist.mapper.OkkiShowlistBlogMapper;
import org.jeecg.modules.okki.showlist.mapper.OkkiShowlistMapper;
import org.jeecg.modules.okki.showlist.service.IOkkiShowlistService;
import org.jeecg.modules.okki.showlist.param.*;
import org.jeecg.modules.okki.showlist.vo.ProductListVO;
import org.jeecg.modules.okki.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: showlist
 * @Author: jeecg-boot
 * @Date:   2024-07-08
 * @Version: V1.0
 */
@Slf4j
@Service
public class OkkiShowlistServiceImpl extends ServiceImpl<OkkiShowlistMapper, OkkiShowlist> implements IOkkiShowlistService {

	@Value("${OKKI.BASE_URL}")
	private String URL;

	@Value("${OKKI.CLIENT_SECRET}")
	private String CLIENT_SECRET;

	@Autowired
	private OkkiShowlistMapper okkiShowlistMapper;
	@Autowired
	private OkkiOverviewMapper okkiOverviewMapper;
	@Autowired
	private OkkiProductListMapper okkiProductListMapper;
	@Autowired
	private OkkiAdvantageMapper okkiAdvantageMapper;
	@Autowired
	private OkkiRecommendedProductsMapper okkiRecommendedProductsMapper;
	@Autowired
	private OkkiKeywordsMapper okkiKeywordsMapper;
	@Autowired
	private OkkiFaqMapper okkiFaqMapper;
	@Autowired
	private OkkiShowlistBlogMapper okkiShowlistBlogMapper;

	@Autowired
	private IUploadService uploadService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(OkkiShowlist okkiShowlist, List<OkkiOverview> okkiOverviewList,List<OkkiProductList> okkiProductListList,List<OkkiAdvantage> okkiAdvantageList,List<OkkiRecommendedProducts> okkiRecommendedProductsList,List<OkkiKeywords> okkiKeywordsList,List<OkkiFaq> okkiFaqList,List<OkkiShowlistBlog> okkiShowlistBlogList) {
		if ("".equals(okkiShowlist.getUrl()) || okkiShowlist.getUrl() == null) {
			okkiShowlist.setUrl(okkiOverviewList.get(0).getTitle().replaceAll(" +", "-"));
		}
		okkiShowlistMapper.insert(okkiShowlist);
		if(okkiOverviewList!=null && okkiOverviewList.size()>0) {
			for(OkkiOverview entity:okkiOverviewList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiOverviewMapper.insert(entity);
			}
		}
		if(okkiProductListList!=null && okkiProductListList.size()>0) {
			for(OkkiProductList entity:okkiProductListList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiProductListMapper.insert(entity);
			}
		}
		if(okkiAdvantageList!=null && okkiAdvantageList.size()>0) {
			for(OkkiAdvantage entity:okkiAdvantageList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiAdvantageMapper.insert(entity);
			}
		}
		if(okkiRecommendedProductsList!=null && okkiRecommendedProductsList.size()>0) {
			for(OkkiRecommendedProducts entity:okkiRecommendedProductsList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiRecommendedProductsMapper.insert(entity);
			}
		}
		if(okkiKeywordsList!=null && okkiKeywordsList.size()>0) {
			for(OkkiKeywords entity:okkiKeywordsList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiKeywordsMapper.insert(entity);
			}
		}
		if(okkiFaqList!=null && okkiFaqList.size()>0) {
			for(OkkiFaq entity:okkiFaqList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiFaqMapper.insert(entity);
			}
		}
		if(okkiShowlistBlogList!=null && okkiShowlistBlogList.size()>0) {
			for(OkkiShowlistBlog entity:okkiShowlistBlogList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiShowlistBlogMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(OkkiShowlist okkiShowlist,List<OkkiOverview> okkiOverviewList,List<OkkiProductList> okkiProductListList,List<OkkiAdvantage> okkiAdvantageList,List<OkkiRecommendedProducts> okkiRecommendedProductsList,List<OkkiKeywords> okkiKeywordsList,List<OkkiFaq> okkiFaqList,List<OkkiShowlistBlog> okkiShowlistBlogList) {
		okkiShowlistMapper.updateById(okkiShowlist);

		//1.先删除子表数据
		okkiOverviewMapper.deleteByMainId(okkiShowlist.getId());
		okkiProductListMapper.deleteByMainId(okkiShowlist.getId());
		okkiAdvantageMapper.deleteByMainId(okkiShowlist.getId());
		okkiRecommendedProductsMapper.deleteByMainId(okkiShowlist.getId());
		okkiKeywordsMapper.deleteByMainId(okkiShowlist.getId());
		okkiFaqMapper.deleteByMainId(okkiShowlist.getId());
		okkiShowlistBlogMapper.deleteByMainId(okkiShowlist.getId());

		//2.子表数据重新插入
		if(okkiOverviewList!=null && okkiOverviewList.size()>0) {
			for(OkkiOverview entity:okkiOverviewList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiOverviewMapper.insert(entity);
			}
		}
		if(okkiProductListList!=null && okkiProductListList.size()>0) {
			for(OkkiProductList entity:okkiProductListList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiProductListMapper.insert(entity);
			}
		}
		if(okkiAdvantageList!=null && okkiAdvantageList.size()>0) {
			for(OkkiAdvantage entity:okkiAdvantageList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiAdvantageMapper.insert(entity);
			}
		}
		if(okkiRecommendedProductsList!=null && okkiRecommendedProductsList.size()>0) {
			for(OkkiRecommendedProducts entity:okkiRecommendedProductsList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiRecommendedProductsMapper.insert(entity);
			}
		}
		if(okkiKeywordsList!=null && okkiKeywordsList.size()>0) {
			for(OkkiKeywords entity:okkiKeywordsList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiKeywordsMapper.insert(entity);
			}
		}
		if(okkiFaqList!=null && okkiFaqList.size()>0) {
			for(OkkiFaq entity:okkiFaqList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiFaqMapper.insert(entity);
			}
		}
		if(okkiShowlistBlogList!=null && okkiShowlistBlogList.size()>0) {
			for(OkkiShowlistBlog entity:okkiShowlistBlogList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiShowlistBlogMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		okkiOverviewMapper.deleteByMainId(id);
		okkiProductListMapper.deleteByMainId(id);
		okkiAdvantageMapper.deleteByMainId(id);
		okkiRecommendedProductsMapper.deleteByMainId(id);
		okkiKeywordsMapper.deleteByMainId(id);
		okkiFaqMapper.deleteByMainId(id);
		okkiShowlistBlogMapper.deleteByMainId(id);
		okkiShowlistMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			okkiOverviewMapper.deleteByMainId(id.toString());
			okkiProductListMapper.deleteByMainId(id.toString());
			okkiAdvantageMapper.deleteByMainId(id.toString());
			okkiRecommendedProductsMapper.deleteByMainId(id.toString());
			okkiKeywordsMapper.deleteByMainId(id.toString());
			okkiFaqMapper.deleteByMainId(id.toString());
			okkiShowlistBlogMapper.deleteByMainId(id.toString());
			okkiShowlistMapper.deleteById(id);
		}
	}

	@Override
	public boolean changeStatus(OkkiShowlist param, String domain){
		// 主表id
		String id = param.getId();
		OkkiShowlist okkiShowlist = okkiShowlistMapper.selectById(id);
		List<OkkiOverview> okkiOverviews = okkiOverviewMapper.selectByMainId(id);
		List<OkkiProductList> okkiProductLists = okkiProductListMapper.selectByMainId(id);
		List<OkkiAdvantage> okkiAdvantages = okkiAdvantageMapper.selectByMainId(id);
		List<OkkiKeywords> okkiKeywords = okkiKeywordsMapper.selectByMainId(id);
		List<OkkiFaq> okkiFaqs = okkiFaqMapper.selectByMainId(id);
		// 组装传入参数
		try {
			String imageBaseUrl = domain + "/shop-api/sys/common/static/";
			System.out.println(imageBaseUrl);
//			 将内容图片和其他图片地址通过接口上传到小满
			if (okkiOverviews.size()>0) {
				if (!"".equals(okkiOverviews.get(0).getPic()) && okkiOverviews.get(0).getPic() != null) {
					String imgUrl = uploadService.uploadImage(imageBaseUrl + okkiOverviews.get(0).getPic(), String.valueOf(okkiShowlist.getSiteId()));
					System.out.println(imgUrl);
					okkiOverviews.get(0).setPic(imgUrl);
				}
				// 将内容中图片地址获取到
				// 将所有src="../../替换成domain
				okkiOverviews.get(0).setContent(okkiOverviews.get(0).getContent().replaceAll("src=\"../..", domain));
				final ArrayList<String> imgTags = findImgTags(okkiOverviews.get(0).getContent());
				if (imgTags.size()>0) {
					for (String imgTag : imgTags) {
						String imgUrl = uploadService.uploadImage(imgTag, String.valueOf(okkiShowlist.getSiteId()));
						okkiOverviews.get(0).setContent(okkiOverviews.get(0).getContent().replace(imgTag,imgUrl));
					}
				}
			}
			// 请求okki平台接口
			Map<String, String> query = new TreeMap<>();
			query.put("sign_method", "hmac-md5");
			query.put("timestamp", String.valueOf(System.currentTimeMillis()));
			query.put("site_id", String.valueOf(okkiShowlist.getSiteId()));
			query.put("method", "save_showlist");
			PushShowlistParam pushShowlistParam = new PushShowlistParam();
			String queryStr = HttpClientUtils.buildQueryString(query);
			pushShowlistParam.setShowlist_id(id);
			pushShowlistParam.setUrl(okkiShowlist.getUrl());
			// overview
			OverviewParam overviewParam = new OverviewParam();
			overviewParam.setOverview_type(1);
			overviewParam.setTitle(okkiOverviews.get(0).getTitle());
			overviewParam.setContent(okkiOverviews.get(0).getContent());
			pushShowlistParam.setOverview(overviewParam);
			// product_list
			ProductParam productListParam = new ProductParam();
			productListParam.setProduct_list_type(1);
			productListParam.setTitle(okkiProductLists.get(0).getTitle());
			// 将字符串转数组
			String pidList = okkiProductLists.get(0).getPidList();
			if (!"".equals(pidList) && pidList != null) {
				String[] split = pidList.split(",");
				productListParam.setPid_list(split);
			}
			pushShowlistParam.setProduct_list(productListParam);
			// advantage
			ArrayList<BlockParam> blockParams = new ArrayList<>();
			ArrayList<AdvantageParam> advantageParams = new ArrayList<>();
			AdvantageParam advantageParam = new AdvantageParam();
			if (okkiAdvantages.size()>0) {
				for (OkkiAdvantage okkiAdvantage : okkiAdvantages) {
					if (!"".equals(okkiAdvantage.getBlockPic()) && okkiAdvantage.getBlockPic() != null) {
						String imgUrl = uploadService.uploadImage(imageBaseUrl + okkiAdvantage.getBlockPic(), String.valueOf(okkiShowlist.getSiteId()));
						System.out.println(imgUrl);
						okkiAdvantage.setBlockPic(imgUrl);
					}
					BlockParam blockParam = new BlockParam();
					blockParam.setTitle(okkiAdvantage.getBlockTitle());
					blockParam.setContent(okkiAdvantage.getBlockContent());
					blockParam.setPic(okkiAdvantage.getBlockPic());
					blockParams.add(blockParam);
				}
			}
			advantageParam.setTitle(okkiShowlist.getAdvantageTitle());
			// 处理优势内容图片
			// 将内容中图片地址获取到
			if (okkiShowlist.getAdvantageContent() != null) {
				// 将所有src="../../替换成domain
				okkiShowlist.setAdvantageContent(okkiShowlist.getAdvantageContent().replaceAll("src=\"../..", domain));
				final ArrayList<String> imgTags = findImgTags(okkiShowlist.getAdvantageContent());
				if (imgTags.size()>0) {
					for (String imgTag : imgTags) {
						String imgUrl = uploadService.uploadImage(imgTag, String.valueOf(okkiShowlist.getSiteId()));
						okkiShowlist.setAdvantageContent(okkiShowlist.getAdvantageContent().replace(imgTag,imgUrl));
					}
				}
			}
			advantageParam.setContent(okkiShowlist.getAdvantageContent());
			advantageParam.setBlock(blockParams);
			advantageParams.add(advantageParam);
			pushShowlistParam.setAdvantage(advantageParams);
			// keywords
			KeywordsParam keywordsParam = new KeywordsParam();
			keywordsParam.setTitle(okkiShowlist.getKeywordsTitle());
			ArrayList<KeywordListParam> keywordListParams = new ArrayList<>();
			for (OkkiKeywords okkiKeyword : okkiKeywords) {
				KeywordListParam keywordListParam = new KeywordListParam();
				keywordListParam.setName(okkiKeyword.getKeywordListName());
				keywordListParam.setLink_url(okkiKeyword.getKeywordListLinkUrl());
				keywordListParams.add(keywordListParam);
			}
			keywordsParam.setKeyword_list(keywordListParams);
			pushShowlistParam.setKeywords(keywordsParam);
			// faq
			FaqParam faqParam = new FaqParam();
			faqParam.setTitle(okkiShowlist.getFaqTitle());
			faqParam.setSubtitles(okkiShowlist.getFaqSubtitles());
			ArrayList<FaqListParam> faqListParams = new ArrayList<>();
			for (OkkiFaq okkiFaq : okkiFaqs) {
				FaqListParam faqListParam = new FaqListParam();
				faqListParam.setQuestion(okkiFaq.getQuestion());
				faqListParam.setAnswer(okkiFaq.getAnswer());
				faqListParams.add(faqListParam);
			}
			faqParam.setFaq_list(faqListParams);
			pushShowlistParam.setFaq(faqParam);
			// tdk
			TdkParam tdkParam = new TdkParam();
			tdkParam.setTitle(okkiOverviews.get(0).getTitle());
			tdkParam.setDescription(okkiOverviews.get(0).getTitle());
			tdkParam.setKeywords(okkiShowlist.getKeywordsTitle());
			pushShowlistParam.setTdk(tdkParam);
			// 组装完成
			String body = JSON.toJSONString(pushShowlistParam);
			String signStr = queryStr + body;
			query.put("signature", HttpClientUtils.generateHmacMD5(signStr, CLIENT_SECRET));
			String okkiUrl = URL + "?" + HttpClientUtils.buildQueryString(query);
			log.info("url:" + okkiUrl + ",body:" + body);
			String res = HttpClientUtils.doPost(okkiUrl, body);
			log.info(res);
			// {"code":0,"msg":"success","now":"2024-05-06 15:34:54","data":[]}
			JSONObject jsonObject= JSONObject.parseObject(res);
			if (jsonObject.get("code").equals(0)) {
				okkiShowlist.setStatus(1);
				int result = okkiShowlistMapper.updateById(okkiShowlist);
				if (result == 0) {
					return false;
				}else {
					return true;
				}
			}else {
				throw new RuntimeException(jsonObject.get("msg").toString());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public ProductListVO getProductList(String siteId) throws Exception{
		// 请求okki平台接口
		Map<String, String> query = new TreeMap<>();
		query.put("sign_method", "hmac-md5");
		query.put("timestamp", String.valueOf(System.currentTimeMillis()));
		query.put("site_id", siteId);
		query.put("method", "search_content");
		String queryStr = HttpClientUtils.buildQueryString(query);
		final HashMap<String, String> map = new HashMap<>();
		map.put("type", "product");
		String body = JSON.toJSONString(map);
		String signStr = queryStr + body;
		query.put("signature", HttpClientUtils.generateHmacMD5(signStr, CLIENT_SECRET));
		String okkiUrl = URL + "?" + HttpClientUtils.buildQueryString(query);
		log.info("url:" + okkiUrl + ",body:" + body);
		String res = HttpClientUtils.doPost(okkiUrl, body);
		log.info(res);
		JSONObject jsonObject= JSONObject.parseObject(res);
		ProductListVO productListVO = new ProductListVO();
		if (jsonObject.get("code").equals(0)) {
			final Object data = jsonObject.get("data");
			productListVO = JSONObject.parseObject(data.toString(), ProductListVO.class);
		}
		return productListVO;
	}

	private static ArrayList<String> findImgTags(String html) {
		final ArrayList<String> strings = new ArrayList<>();
		// 定义正则表达式
//		String regex = "<img\\s+src=\"([^\"]+)\"\\s*/>";
		String regex = "<img src=\"([^\"]+)\"";
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(html);

		// 查找所有匹配项
		while (matcher.find()) {
			// 打印图片的src属性值
			strings.add(matcher.group(1));
			System.out.println(matcher.group(1));
		}
		return strings;
	}
}
