package org.jeecg.modules.okki.linkedin.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.linkedin.entity.OkkiLinkedinMarketingData;
import org.jeecg.modules.okki.linkedin.entity.OkkiLinkedinMarketingDataDetail;
import org.jeecg.modules.okki.linkedin.mapper.OkkiLinkedinMarketingDataDetailMapper;
import org.jeecg.modules.okki.linkedin.mapper.OkkiLinkedinMarketingDataMapper;
import org.jeecg.modules.okki.linkedin.param.LinkedinMarketingDataParam;
import org.jeecg.modules.okki.linkedin.param.LinkedinReportListParam;
import org.jeecg.modules.okki.linkedin.service.IOkkiLinkedinMarketingDataService;
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.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: Linkedin营销效果数据
 * @Author: jeecg-boot
 * @Date:   2024-05-16
 * @Version: V1.0
 */
@Slf4j
@Service
public class OkkiLinkedinMarketingDataServiceImpl extends ServiceImpl<OkkiLinkedinMarketingDataMapper, OkkiLinkedinMarketingData> implements IOkkiLinkedinMarketingDataService {

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

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

	@Autowired
	private OkkiLinkedinMarketingDataMapper okkiLinkedinMarketingDataMapper;
	@Autowired
	private OkkiLinkedinMarketingDataDetailMapper okkiLinkedinMarketingDataDetailMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(OkkiLinkedinMarketingData okkiLinkedinMarketingData, List<OkkiLinkedinMarketingDataDetail> okkiLinkedinMarketingDataDetailList) {
		okkiLinkedinMarketingDataMapper.insert(okkiLinkedinMarketingData);
		if(okkiLinkedinMarketingDataDetailList!=null && okkiLinkedinMarketingDataDetailList.size()>0) {
			for(OkkiLinkedinMarketingDataDetail entity:okkiLinkedinMarketingDataDetailList) {
				//外键设置
				entity.setOkkiLinkedinMarketingDataId(okkiLinkedinMarketingData.getId());
				okkiLinkedinMarketingDataDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(OkkiLinkedinMarketingData okkiLinkedinMarketingData,List<OkkiLinkedinMarketingDataDetail> okkiLinkedinMarketingDataDetailList) {
		okkiLinkedinMarketingDataMapper.updateById(okkiLinkedinMarketingData);
		
		//1.先删除子表数据
		okkiLinkedinMarketingDataDetailMapper.deleteByMainId(okkiLinkedinMarketingData.getId());
		
		//2.子表数据重新插入
		if(okkiLinkedinMarketingDataDetailList!=null && okkiLinkedinMarketingDataDetailList.size()>0) {
			for(OkkiLinkedinMarketingDataDetail entity:okkiLinkedinMarketingDataDetailList) {
				//外键设置
				entity.setOkkiLinkedinMarketingDataId(okkiLinkedinMarketingData.getId());
				okkiLinkedinMarketingDataDetailMapper.insert(entity);
			}
		}
	}

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

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

	@Override
	public boolean changeStatus(OkkiLinkedinMarketingData param) {
		OkkiLinkedinMarketingData okkiLinkedinMarketingData = okkiLinkedinMarketingDataMapper.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(okkiLinkedinMarketingData.getSiteId()));
		query.put("method", "linkedin_report");
		okkiLinkedinMarketingData.setStatus(1);
		LinkedinMarketingDataParam linkedinMarketingDataParam  = new LinkedinMarketingDataParam();
		try {
			String queryStr = HttpClientUtils.buildQueryString(query);
			List<OkkiLinkedinMarketingDataDetail> okkiLinkedinMarketingDataDetails = okkiLinkedinMarketingDataDetailMapper.selectByMainId(okkiLinkedinMarketingData.getId());
			ArrayList<LinkedinReportListParam> linkedinReportListParams = new ArrayList<>();
			for (OkkiLinkedinMarketingDataDetail okkiLinkedinMarketingDataDetail : okkiLinkedinMarketingDataDetails) {
				LinkedinReportListParam linkedinReportListParam = new LinkedinReportListParam();
				linkedinReportListParam.setId(okkiLinkedinMarketingDataDetail.getId());
				linkedinReportListParam.setTitle(okkiLinkedinMarketingDataDetail.getTitle());
				linkedinReportListParam.setUrl(okkiLinkedinMarketingDataDetail.getUrl());
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				linkedinReportListParam.setCreate_time(format.format(okkiLinkedinMarketingDataDetail.getCreateTime()));
				linkedinReportListParams.add(linkedinReportListParam);
			}
			linkedinMarketingDataParam.setReport_list(linkedinReportListParams);
			linkedinMarketingDataParam.setCount(linkedinReportListParams.size());
			String body = HttpClientUtils.toJsonString(linkedinMarketingDataParam);
			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 = okkiLinkedinMarketingDataMapper.updateById(okkiLinkedinMarketingData);
				if (result == 0) {
					return false;
				}else {
					return true;
				}
			}else {
				throw new RuntimeException(jsonObject.get("msg").toString());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
