package org.jeecg.modules.adweb.dmp.controller;

import io.swagger.v3.oas.annotations.tags.Tag;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.tuple.Pair;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.adweb.dmp.entity.GoogleGTM;
import org.jeecg.modules.adweb.dmp.service.google.GTMAdminService;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * GTM容器和标签管理
 *
 * @author wfansh
 */
@Tag(name = "Google Tag Manager")
@RestController
@RequestMapping("/gtm")
@Slf4j
public class GTMController {

    @Autowired private IAdwebSiteService adwebSiteService;

    @Autowired private GTMAdminService gtmAdminService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Result<AdwebSite> getGTMSnippets(Integer id) {
        AdwebSite adwebSite = adwebSiteService.getById(id);

        // 如果GoogleGTM表中已存在，不再创建，返回现有记录
        GoogleGTM googleGTM =
                gtmAdminService.createContainer(
                        adwebSite.getCode(), adwebSite.getDomain(), adwebSite.getName());

        Pair<String, String> snippets = gtmAdminService.getSnippets(googleGTM.getGtmTagId());
        adwebSite.setGtmHead(snippets.getKey());
        adwebSite.setGtmBody(snippets.getValue());

        return Result.ok(adwebSite);
    }
}
