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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.okki.showlist.entity.*;
import org.jeecg.modules.okki.showlist.mapper.*;
import org.jeecg.modules.okki.showlist.param.*;
import org.jeecg.modules.okki.showlist.service.IOkkiShowlistService;
import org.jeecg.modules.okki.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * @Description: showlist
 * @Author: jeecg-boot
 * @Date:   2024-05-14
 * @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 OkkiHighlightMapper okkiHighlightMapper;
	@Autowired
	private OkkiAdvantageMapper okkiAdvantageMapper;
	@Autowired
	private OkkiRecommendedProductsMapper okkiRecommendedProductsMapper;
	@Autowired
	private OkkiKeywordsMapper okkiKeywordsMapper;
	@Autowired
	private OkkiKeywordsSeriesMapper okkiKeywordsSeriesMapper;
	@Autowired
	private OkkiReviewMapper okkiReviewMapper;
	@Autowired
	private OkkiFaqMapper okkiFaqMapper;
	@Autowired
	private OkkiShowlistBlogMapper okkiShowlistBlogMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(OkkiShowlist okkiShowlist, List<OkkiOverview> okkiOverviewList,List<OkkiProductList> okkiProductListList,List<OkkiHighlight> okkiHighlightList,List<OkkiAdvantage> okkiAdvantageList,List<OkkiRecommendedProducts> okkiRecommendedProductsList,List<OkkiKeywords> okkiKeywordsList,List<OkkiKeywordsSeries> okkiKeywordsSeriesList,List<OkkiReview> okkiReviewList,List<OkkiFaq> okkiFaqList,List<OkkiShowlistBlog> okkiShowlistBlogList) {
		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(okkiHighlightList!=null && okkiHighlightList.size()>0) {
			for(OkkiHighlight entity:okkiHighlightList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiHighlightMapper.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(okkiKeywordsSeriesList!=null && okkiKeywordsSeriesList.size()>0) {
			for(OkkiKeywordsSeries entity:okkiKeywordsSeriesList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiKeywordsSeriesMapper.insert(entity);
			}
		}
		if(okkiReviewList!=null && okkiReviewList.size()>0) {
			for(OkkiReview entity:okkiReviewList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiReviewMapper.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<OkkiHighlight> okkiHighlightList,List<OkkiAdvantage> okkiAdvantageList,List<OkkiRecommendedProducts> okkiRecommendedProductsList,List<OkkiKeywords> okkiKeywordsList,List<OkkiKeywordsSeries> okkiKeywordsSeriesList,List<OkkiReview> okkiReviewList,List<OkkiFaq> okkiFaqList,List<OkkiShowlistBlog> okkiShowlistBlogList) {
		okkiShowlistMapper.updateById(okkiShowlist);
		
		//1.先删除子表数据
		okkiOverviewMapper.deleteByMainId(okkiShowlist.getId());
		okkiProductListMapper.deleteByMainId(okkiShowlist.getId());
		okkiHighlightMapper.deleteByMainId(okkiShowlist.getId());
		okkiAdvantageMapper.deleteByMainId(okkiShowlist.getId());
		okkiRecommendedProductsMapper.deleteByMainId(okkiShowlist.getId());
		okkiKeywordsMapper.deleteByMainId(okkiShowlist.getId());
		okkiKeywordsSeriesMapper.deleteByMainId(okkiShowlist.getId());
		okkiReviewMapper.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(okkiHighlightList!=null && okkiHighlightList.size()>0) {
			for(OkkiHighlight entity:okkiHighlightList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiHighlightMapper.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(okkiKeywordsSeriesList!=null && okkiKeywordsSeriesList.size()>0) {
			for(OkkiKeywordsSeries entity:okkiKeywordsSeriesList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiKeywordsSeriesMapper.insert(entity);
			}
		}
		if(okkiReviewList!=null && okkiReviewList.size()>0) {
			for(OkkiReview entity:okkiReviewList) {
				//外键设置
				entity.setOkkiShowlistId(okkiShowlist.getId());
				okkiReviewMapper.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);
		okkiHighlightMapper.deleteByMainId(id);
		okkiAdvantageMapper.deleteByMainId(id);
		okkiRecommendedProductsMapper.deleteByMainId(id);
		okkiKeywordsMapper.deleteByMainId(id);
		okkiKeywordsSeriesMapper.deleteByMainId(id);
		okkiReviewMapper.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());
			okkiHighlightMapper.deleteByMainId(id.toString());
			okkiAdvantageMapper.deleteByMainId(id.toString());
			okkiRecommendedProductsMapper.deleteByMainId(id.toString());
			okkiKeywordsMapper.deleteByMainId(id.toString());
			okkiKeywordsSeriesMapper.deleteByMainId(id.toString());
			okkiReviewMapper.deleteByMainId(id.toString());
			okkiFaqMapper.deleteByMainId(id.toString());
			okkiShowlistBlogMapper.deleteByMainId(id.toString());
			okkiShowlistMapper.deleteById(id);
		}
	}

	@Override
	public boolean changeStatus(OkkiShowlist param) {
		// 主表id
		String id = param.getId();
		OkkiShowlist okkiShowlist = okkiShowlistMapper.selectById(id);
		List<OkkiOverview> okkiOverviews = okkiOverviewMapper.selectByMainId(id);
		List<OkkiProductList> okkiProductLists = okkiProductListMapper.selectByMainId(id);
		List<OkkiHighlight> okkiHighlights = okkiHighlightMapper.selectByMainId(id);
		List<OkkiAdvantage> okkiAdvantages = okkiAdvantageMapper.selectByMainId(id);
		List<OkkiRecommendedProducts> okkiRecommendedProducts = okkiRecommendedProductsMapper.selectByMainId(id);
		List<OkkiKeywords> okkiKeywords = okkiKeywordsMapper.selectByMainId(id);
//		List<OkkiKeywordsSeries> okkiKeywordsSeries = okkiKeywordsSeriesMapper.selectByMainId(id);
		List<OkkiReview> okkiReviews = okkiReviewMapper.selectByMainId(id);
		List<OkkiFaq> okkiFaqs = okkiFaqMapper.selectByMainId(id);
		List<OkkiShowlistBlog> okkiShowlistBlogs = okkiShowlistBlogMapper.selectByMainId(id);
		// 请求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();
		// 组装传入参数
		try {
			String queryStr = HttpClientUtils.buildQueryString(query);
			pushShowlistParam.setShowlist_id(id);
			pushShowlistParam.setUrl(okkiShowlist.getUrl());
			pushShowlistParam.setJson_ld(okkiShowlist.getJsonLd());
			// overview
			OverviewParam overviewParam = new OverviewParam();
			overviewParam.setOverview_type(okkiOverviews.get(0).getOverviewType());
			overviewParam.setTitle(okkiOverviews.get(0).getTitle());
			overviewParam.setContent(okkiOverviews.get(0).getContent());
			overviewParam.setPic(okkiOverviews.get(0).getPic());
			ButtonParam buttonParam = new ButtonParam();
			buttonParam.setName(okkiOverviews.get(0).getButtonName());
			buttonParam.setUrl(okkiOverviews.get(0).getButtonUrl());
			overviewParam.setButton(buttonParam);
			pushShowlistParam.setOverview(overviewParam);
			// product_list
			ProductParam productListParam = new ProductParam();
			productListParam.setProduct_list_type(okkiProductLists.get(0).getProductListType());
			productListParam.setTitle(okkiProductLists.get(0).getTitle());
			productListParam.setSubtitles(okkiProductLists.get(0).getSubtitles());
			// 将字符串转数组
			String pidList = okkiProductLists.get(0).getPidList();
			if (!"".equals(pidList) && pidList != null) {
				String[] split = pidList.split(",");
				productListParam.setPid_list(split);
			}
			productListParam.setSid(okkiProductLists.get(0).getSid());
			pushShowlistParam.setProduct_list(productListParam);
			// highlight
			HighlightParam highlightParam = new HighlightParam();
			highlightParam.setTitle(okkiShowlist.getHighlightTitle());
			highlightParam.setContent(okkiShowlist.getHighlightContent());
			LayoutParam highlightLayoutParam = new LayoutParam();
			highlightLayoutParam.setAlignment(okkiShowlist.getHighlightLayoutAlignment());
			highlightLayoutParam.setColumns_per_row(okkiShowlist.getHighlightLayoutColumnsPerRow());
			highlightParam.setLayout(highlightLayoutParam);
			List<BlockParam> highlightBlockParams = new ArrayList<>();
			for (OkkiHighlight okkiHighlight : okkiHighlights) {
				BlockParam blockParam = new BlockParam();
				blockParam.setTitle(okkiHighlight.getBlockTitle());
				blockParam.setContent(okkiHighlight.getBlockContent());
				blockParam.setPic(okkiHighlight.getBlockPic());
				// button
				ButtonParam highlightBlockButtonParam = new ButtonParam();
				highlightBlockButtonParam.setName(okkiHighlight.getButtonName());
				highlightBlockButtonParam.setUrl(okkiHighlight.getButtonUrl());
				blockParam.setButton(highlightBlockButtonParam);
				highlightBlockParams.add(blockParam);
			}
			highlightParam.setBlock(highlightBlockParams);
			// advantage
			ArrayList<AdvantageParam> advantageParams = new ArrayList<>();
			AdvantageParam advantageParam = new AdvantageParam();
			advantageParam.setTitle(okkiShowlist.getAdvantageTitle());
			advantageParam.setContent(okkiShowlist.getAdvantageContent());
			LayoutParam advantageLayoutParam = new LayoutParam();
			advantageLayoutParam.setAlignment(okkiShowlist.getAdvantageLayoutAlignment());
			advantageLayoutParam.setColumns_per_row(okkiShowlist.getAdvantageLayoutColumnsPerRow());
			advantageParam.setLayout(advantageLayoutParam);
			List<BlockParam> advantageBlockParams = new ArrayList<>();
			for (OkkiAdvantage okkiAdvantage : okkiAdvantages) {
				BlockParam blockParam = new BlockParam();
				blockParam.setTitle(okkiAdvantage.getBlockTitle());
				blockParam.setContent(okkiAdvantage.getBlockContent());
				blockParam.setPic(okkiAdvantage.getBlockPic());
				// button
				ButtonParam  advantageBlockButtonParam = new ButtonParam();
				advantageBlockButtonParam.setName(okkiAdvantage.getButtonName());
				advantageBlockButtonParam.setUrl(okkiAdvantage.getButtonUrl());
				blockParam.setButton(advantageBlockButtonParam);
				advantageBlockParams.add(blockParam);
			}
			advantageParam.setBlock(advantageBlockParams);
			advantageParams.add(advantageParam);
			pushShowlistParam.setAdvantage(advantageParams);
			// recommended_products
			ProductParam recommendedProductParam = new ProductParam();
			recommendedProductParam.setProduct_list_type(okkiRecommendedProducts.get(0).getProductListType());
			recommendedProductParam.setTitle(okkiRecommendedProducts.get(0).getTitle());
			recommendedProductParam.setSubtitles(okkiRecommendedProducts.get(0).getSubtitles());
			recommendedProductParam.setSid(okkiRecommendedProducts.get(0).getSid());
			// 将字符串转数组
			String pidList1 = okkiRecommendedProducts.get(0).getPidList();
			if (!"".equals(pidList1) && pidList1 != null) {
				String[] split1 = pidList1.split(",");
				recommendedProductParam.setPid_list(split1);
			}
			pushShowlistParam.setRecommended_products(recommendedProductParam);
			// 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);
			//TODO:: keyword_series

			// review
			ReviewParam reviewParam = new ReviewParam();
			reviewParam.setTitle(okkiShowlist.getReviewTitle());
			reviewParam.setSubtitles(okkiShowlist.getReviewSubtitles());
			LayoutParam reviewLayoutParam = new LayoutParam();
			reviewLayoutParam.setAlignment(okkiShowlist.getReviewLayoutAlignment());
			reviewLayoutParam.setColumns_per_row(okkiShowlist.getReviewLayoutColumnsPerRow());
			reviewParam.setLayout(reviewLayoutParam);
			ArrayList<ReviewListParam> reviewListParams = new ArrayList<>();
			for (OkkiReview okkiReview : okkiReviews) {
				ReviewListParam reviewListParam = new ReviewListParam();
				reviewListParam.setContent(okkiReview.getReviewListContent());
				reviewListParam.setAvatar_url(okkiReview.getReviewListAvatarUrl());
				reviewListParam.setName(okkiReview.getReviewListName());
				reviewListParams.add(reviewListParam);
			}
			reviewParam.setReview_list(reviewListParams);
			pushShowlistParam.setReview(reviewParam);
			// 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);
			// blog
			BlogParam blogParam = new BlogParam();
			blogParam.setTitle(okkiShowlistBlogs.get(0).getTitle());
			LayoutParam blogLayoutParam = new LayoutParam();
			blogLayoutParam.setAlignment(okkiShowlistBlogs.get(0).getLayoutAlignment());
			blogLayoutParam.setColumns_per_row(okkiShowlistBlogs.get(0).getLayoutColumnsPerRow());
			blogParam.setLayout(blogLayoutParam);
			// 将字符串转数组
			String blogList = okkiShowlistBlogs.get(0).getBlogList();
			if (!"".equals(blogList) && blogList != null) {
				String[] blogSplit = blogList.split(",");
				blogParam.setBlog_list(blogSplit);
			}
			pushShowlistParam.setBlog(blogParam);
			pushShowlistParam.setInquiry_type(okkiShowlist.getInquiryType());
			// tdk
			TdkParam tdkParam = new TdkParam();
			tdkParam.setTitle(okkiShowlist.getTdkTitle());
			tdkParam.setDescription(okkiShowlist.getTdkDescription());
			tdkParam.setKeywords(okkiShowlist.getTdkKeywords());
			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);
		}
	}

}
