package com.fs.company.controller.newAdv;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.common.result.Result;
import com.fs.newAdv.domain.LandingPageTemplate;
import com.fs.newAdv.domain.Lead;
import com.fs.newAdv.domain.Site;
import com.fs.newAdv.dto.req.LandingIndexReq;
import com.fs.newAdv.enums.AdvertiserTypeEnum;
import com.fs.newAdv.service.ILandingPageTemplateService;
import com.fs.newAdv.service.ILeadService;
import com.fs.newAdv.service.ISiteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

/**
 * 投放页面模板Controller
 *
 * @author zhangqin
 * @date 2025-11-06
 */
@Slf4j
@RestController
@RequestMapping("/adv/landing-page-templates")
@Validated
public class LandingPageTemplateController {

    @Autowired
    private ILandingPageTemplateService templateService;
    @Autowired
    private ISiteService siteService;
    @Autowired
    private ILeadService leadService;

    /**
     * 分页查询模板列表
     *
     * @param templateName 模板名称（模糊查询）
     * @param templateType 模板类型
     * @param status       状态
     * @return 模板列表
     */
    @GetMapping("/page")
    public Result<IPage<LandingPageTemplate>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String templateName,
            @RequestParam(required = false) String templateType,
            @RequestParam(required = false) Integer status) {


        Page<LandingPageTemplate> pageParam = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LandingPageTemplate> queryWrapper = new LambdaQueryWrapper<>();

        if (StrUtil.isNotBlank(templateName)) {
            queryWrapper.like(LandingPageTemplate::getTemplateName, templateName);
        }
        if (StrUtil.isNotBlank(templateType)) {
            queryWrapper.eq(LandingPageTemplate::getTemplateType, templateType);
        }
        if (status != null) {
            queryWrapper.eq(LandingPageTemplate::getStatus, status);
        }
        queryWrapper.ne(LandingPageTemplate::getStatus, 2);
        queryWrapper.orderByDesc(LandingPageTemplate::getCreateTime);

        IPage<LandingPageTemplate> result = templateService.page(pageParam, queryWrapper);
        return Result.success(result);
    }

    /**
     * 根据ID查询模板详情
     *
     * @param id 模板ID
     * @return 模板详情
     */
    @GetMapping("/{id}")
    public Result<LandingPageTemplate> getById(@PathVariable String id) {
        LandingPageTemplate template = templateService.getById(id);
        if (template == null) {
            return Result.error("模板不存在");
        }

        return Result.success(template);
    }

    /**
     * 新增模板
     *
     * @param request 模板信息
     * @return 操作结果
     */
    @PostMapping
    public Result<Void> create(@RequestBody @Validated LandingPageTemplate request) {
        log.info("新增模板 | templateName={}, templateType={}",
                request.getTemplateName(), request.getTemplateType());
        boolean success = templateService.save(request);
        if (!success) {
            return Result.error("新增模板失败");
        }
        return Result.success();
    }

    /**
     * 启停模板
     *
     * @return 操作结果
     */
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable String id,@RequestBody LandingPageTemplate request) {
        return templateService.updateById(request)?Result.success():Result.error("更新模板失败");
    }

    /**
     * 启停模板
     *
     * @return 操作结果
     */
    @PostMapping("/enable/{id}")
    public Result<Void> create(@PathVariable String id, @RequestParam(required = false) Integer status) {
        if (status == 0 && siteService.findByTemplateId(id)) {
            return Result.error("该模板正在被使用中，请先停用");
        }
        templateService.update(new LambdaUpdateWrapper<LandingPageTemplate>()
                .eq(LandingPageTemplate::getId, id)
                .set(LandingPageTemplate::getStatus, status));
        return Result.success();
    }

    /**
     * 落地页访问
     */
    @PostMapping("/index")
    public Result<LandingPageTemplate> track(
            @Valid @RequestBody LandingIndexReq req) {
        log.info("落地页访问追踪：req={}，params={}", req, req.getAllParams());
        Long siteId = Long.valueOf(req.getAllParams().get("siteId"));
        Site byId = siteService.getById(siteId);
        // 保存落地页访问记录
        saveLandingIndexTrace(siteId, req.getAllParams());
        // 查询落地页模板
        return Result.success(templateService.getById(byId.getLaunchPageId()));
    }

    public void saveLandingIndexTrace(Long siteId, Map<String, String> allParams) {
        Site byId = siteService.getById(siteId);
        Long advertiserId = byId.getAdvertiserId();
        String traceId = getTraceIdByAdvertiser(Objects.requireNonNull(AdvertiserTypeEnum.getByCode(advertiserId)), allParams);
        Lead byTraceId = leadService.getByTraceId(traceId);
        if (ObjectUtil.isEmpty(byTraceId)) {
            byTraceId = new Lead();
            byTraceId.setAdvertiserId(advertiserId);
            byTraceId.setSiteId(siteId);
            leadService.save(byTraceId);
        }
        if (!Objects.equals(byTraceId.getSiteId(), siteId)) {
            log.info("落地页站点信息异常:{}---{}", byTraceId.getSiteId(), siteId);
        }
        if (!Objects.equals(byTraceId.getAdvertiserId(), advertiserId)) {
            log.info("落地页站点信息异常:{}---{}", byTraceId.getAdvertiserId(), advertiserId);
        }
        byTraceId.setLandingPageRawParams(JSONUtil.toJsonStr(allParams));
        byTraceId.setLandingPageTrigger(1);
        byTraceId.setLandingPageTs(LocalDateTime.now());
        byTraceId.setUpdateTime(LocalDateTime.now());
        leadService.updateById(byTraceId);
    }


    private String getTraceIdByAdvertiser(AdvertiserTypeEnum byCode, Map<String, String> allParams) {
        switch (byCode) {
            case OCEANENGINE:
                return allParams.get("click_id");
            case TENCENT:
                return allParams.get("click_id");
            case OPPO:
                return allParams.get("traceId");
            case BAIDU:
                return allParams.get("bdVid");
            case VIVO:
                return allParams.get("requestId");
            case IQIYI:
                return allParams.get("traceId");
            default:
                return null;
        }
    }
}

