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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.okki.utils.HttpClientUtils;
import org.jeecg.modules.okki.youtube.entity.OkkiYoutubeMarketingData;
import org.jeecg.modules.okki.youtube.entity.OkkiYoutubeMarketingDataDetail;
import org.jeecg.modules.okki.youtube.mapper.OkkiYoutubeMarketingDataDetailMapper;
import org.jeecg.modules.okki.youtube.mapper.OkkiYoutubeMarketingDataMapper;
import org.jeecg.modules.okki.youtube.param.ReportListParam;
import org.jeecg.modules.okki.youtube.param.YoutubeMarketingDataParam;
import org.jeecg.modules.okki.youtube.service.IOkkiYoutubeMarketingDataService;
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: Youtube营销效果数据
 * @Author: jeecg-boot
 * @Date:   2024-05-16
 * @Version: V1.0
 */
@Slf4j
@Service
public class OkkiYoutubeMarketingDataServiceImpl extends ServiceImpl<OkkiYoutubeMarketingDataMapper, OkkiYoutubeMarketingData> implements IOkkiYoutubeMarketingDataService {

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

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


	@Autowired
	private OkkiYoutubeMarketingDataMapper okkiYoutubeMarketingDataMapper;
	@Autowired
	private OkkiYoutubeMarketingDataDetailMapper okkiYoutubeMarketingDataDetailMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(OkkiYoutubeMarketingData okkiYoutubeMarketingData, List<OkkiYoutubeMarketingDataDetail> okkiYoutubeMarketingDataDetailList) {
		okkiYoutubeMarketingDataMapper.insert(okkiYoutubeMarketingData);
		if(okkiYoutubeMarketingDataDetailList!=null && okkiYoutubeMarketingDataDetailList.size()>0) {
			for(OkkiYoutubeMarketingDataDetail entity:okkiYoutubeMarketingDataDetailList) {
				//外键设置
				entity.setOkkiYoutubeMarketingDataId(okkiYoutubeMarketingData.getId());
				okkiYoutubeMarketingDataDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(OkkiYoutubeMarketingData okkiYoutubeMarketingData,List<OkkiYoutubeMarketingDataDetail> okkiYoutubeMarketingDataDetailList) {
		okkiYoutubeMarketingDataMapper.updateById(okkiYoutubeMarketingData);
		
		//1.先删除子表数据
		okkiYoutubeMarketingDataDetailMapper.deleteByMainId(okkiYoutubeMarketingData.getId());
		
		//2.子表数据重新插入
		if(okkiYoutubeMarketingDataDetailList!=null && okkiYoutubeMarketingDataDetailList.size()>0) {
			for(OkkiYoutubeMarketingDataDetail entity:okkiYoutubeMarketingDataDetailList) {
				//外键设置
				entity.setOkkiYoutubeMarketingDataId(okkiYoutubeMarketingData.getId());
				okkiYoutubeMarketingDataDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		okkiYoutubeMarketingDataDetailMapper.deleteByMainId(id);
		okkiYoutubeMarketingDataMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			okkiYoutubeMarketingDataDetailMapper.deleteByMainId(id.toString());
			okkiYoutubeMarketingDataMapper.deleteById(id);
		}
	}

	@Override
	public boolean changeStatus(OkkiYoutubeMarketingData param) {
		OkkiYoutubeMarketingData okkiYoutubeMarketingData = okkiYoutubeMarketingDataMapper.selectById(param.getId());
		// 请求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(okkiYoutubeMarketingData.getSiteId()));
		query.put("method", "youtube_report");
		okkiYoutubeMarketingData.setStatus(1);
		YoutubeMarketingDataParam youtubeMarketingDataParam = new YoutubeMarketingDataParam();
		try {
			String queryStr = HttpClientUtils.buildQueryString(query);
			List<OkkiYoutubeMarketingDataDetail> okkiYoutubeMarketingDataDetails = okkiYoutubeMarketingDataDetailMapper.selectByMainId(okkiYoutubeMarketingData.getId());
			ArrayList<ReportListParam> reportListParams = new ArrayList<>();
			for (OkkiYoutubeMarketingDataDetail okkiYoutubeMarketingDataDetail : okkiYoutubeMarketingDataDetails) {
				ReportListParam reportListParam = new ReportListParam();
				reportListParam.setVid(okkiYoutubeMarketingDataDetail.getVid());
				reportListParam.setTitle(okkiYoutubeMarketingDataDetail.getTitle());
				reportListParam.setAddtime(okkiYoutubeMarketingDataDetail.getAddtime());
				reportListParam.setViews(okkiYoutubeMarketingDataDetail.getViews());
				reportListParam.setDuration(okkiYoutubeMarketingDataDetail.getDuration());
				reportListParam.setSubscribe(okkiYoutubeMarketingDataDetail.getSubscribe());
				reportListParam.setShowtimes(okkiYoutubeMarketingDataDetail.getShowtimes());
				reportListParam.setMonth(okkiYoutubeMarketingDataDetail.getMonth());
				reportListParams.add(reportListParam);
			}
			youtubeMarketingDataParam.setReport_list(reportListParams);
			youtubeMarketingDataParam.setCount(reportListParams.size());
			String body = HttpClientUtils.toJsonString(youtubeMarketingDataParam);
			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)) {
				int result = okkiYoutubeMarketingDataMapper.updateById(okkiYoutubeMarketingData);
				if (result == 0) {
					return false;
				}else {
					return true;
				}
			}else {
				throw new RuntimeException(jsonObject.get("msg").toString());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
