package org.jeecg.modules.adweb.enquiry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.modules.adweb.common.constant.NumConstant;
import org.jeecg.modules.adweb.enquiry.dto.matomo.MatomoBrowsingEnquiryIdDto;
import org.jeecg.modules.adweb.enquiry.entity.AdwebEnquiry;
import org.jeecg.modules.adweb.enquiry.entity.AdwebMatomo;
import org.jeecg.modules.adweb.enquiry.mapper.AdwebMatomoMapper;
import org.jeecg.modules.adweb.enquiry.service.IAdwebEnquiryService;
import org.jeecg.modules.adweb.enquiry.service.IAdwebMatomoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: matoto @Author: Cyan @Date: 2022-07-27 @Version: V1.0
 */
@Service
public class AdwebMatomoServiceImpl extends ServiceImpl<AdwebMatomoMapper, AdwebMatomo>
    implements IAdwebMatomoService {

  @Value("${admp.matomo.token}")
  private String matomoToken;

  @Value("${admp.matomo.url}")
  private String matomoUrl;

  @Value("${admp.matomocn.token}")
  private String matomoCnToken;

  @Value("${admp.matomocn.url}")
  private String matomoCnUrl;

  @Autowired private IAdwebEnquiryService adwebEnquiryService;

  /**
   * 根据询盘Id获取网站访问记录
   *
   * @param enquiryId
   * @return9yue
   */
  @Override
  public List<MatomoBrowsingEnquiryIdDto> getMatomoWebTrackFromEnquiryId(String enquiryId) {
    List<MatomoBrowsingEnquiryIdDto> matomoBrowsingEnquiryIpDtos = new ArrayList<>();
    AdwebEnquiry adwebEnquiry = adwebEnquiryService.getById(enquiryId);
    if (adwebEnquiry == null) {
      throw new JeecgBootException("询盘不存在");
    }

    QueryWrapper<AdwebMatomo> admpMatomoQueryWrapper = new QueryWrapper<>();
    admpMatomoQueryWrapper.eq("site_id", adwebEnquiry.getSiteId());
    admpMatomoQueryWrapper.eq("is_del", CommonConstant.DEL_FLAG_1);
    List<AdwebMatomo> admpMatomos = this.list(admpMatomoQueryWrapper);
    if (CollectionUtils.isNotEmpty(admpMatomos)) {
      RestTemplate restTemplate = getRestTemplate(NumConstant.ONEHUNDREDTWENTY);
      try {
        if (StringUtils.isNotBlank(adwebEnquiry.getVisitId())) {
          String code = null;
          String url =
              matomoCnUrl
                  + "/index.php?module=API&method=Live.getLastVisitsDetails&idSite="
                  + admpMatomos.get(NumConstant.ZERO).getMmSiteId()
                  + "&format=JSON&token_auth="
                  + matomoCnToken
                  + "&segment=visitorId=="
                  + adwebEnquiry.getVisitId()
                  + "&language=zh-cn";
          log.warn("getMatomoWebTrackFromEnquiryId - url:{}" + url);
          code = restTemplate.getForObject(url, String.class);
          log.warn("code：" + code);
          if (StringUtils.isNotBlank(code) && !"[]".equals(code)) {
            //                            Map<String, Object> map = FastJsonUtil.parseObject(code,
            // Map.class);
            matomoBrowsingEnquiryIpDtos =
                FastJsonUtil.parseList(code, MatomoBrowsingEnquiryIdDto.class);
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
        log.error("请求超时");
        throw new JeecgBootException("请求超时,请重试！");
      }
    }

    return matomoBrowsingEnquiryIpDtos;
  }

  /**
   * 根据网站id获取Matomo网站浏览记录
   *
   * @param siteId
   * @return
   */
  @Override
  public List<MatomoBrowsingEnquiryIdDto> getMatomoSiteTrackFromSiteId(String siteId) {
    List<MatomoBrowsingEnquiryIdDto> matomoBrowsingEnquiryIpDtos = new ArrayList<>();
    QueryWrapper<AdwebMatomo> admpMatomoQueryWrapper = new QueryWrapper<>();
    admpMatomoQueryWrapper.eq("site_id", siteId);
    admpMatomoQueryWrapper.eq("is_del", CommonConstant.DEL_FLAG_1);
    List<AdwebMatomo> admpMatomos = this.list(admpMatomoQueryWrapper);
    if (CollectionUtils.isNotEmpty(admpMatomos)) {
      // 获取自定义restTemplate
      RestTemplate restTemplate = getRestTemplate(NumConstant.ONEHUNDREDTWENTY);
      try {
        String code = null;
        String url =
            matomoCnUrl
                + "/index.php?module=API&method=Live.getLastVisitsDetails&idSite="
                + admpMatomos.get(NumConstant.ZERO).getMmSiteId()
                + "&format=JSON&token_auth="
                + matomoCnToken
                + "&language=zh-cn&period=day&date=today";
        log.warn("getMatomoSiteTrackFromSiteId url:{}" + url);
        code = restTemplate.getForObject(url, String.class);
        log.warn("code：" + code);
        if (StringUtils.isNotBlank(code) && !"[]".equals(code)) {
          matomoBrowsingEnquiryIpDtos =
              FastJsonUtil.parseList(code, MatomoBrowsingEnquiryIdDto.class);
        }
      } catch (Exception e) {
        e.printStackTrace();
        log.error("请求超时");
        throw new JeecgBootException("请求超时,请重试！");
      }
    }
    return matomoBrowsingEnquiryIpDtos;
  }

  /**
   * 创建restTemplate对象
   *
   * @param second
   * @return
   */
  private RestTemplate getRestTemplate(Integer second) {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setConnectTimeout(second * 1000);
    factory.setReadTimeout(second * 1000);
    return new RestTemplate(factory);
  }
}
