package com.moka.gdtauto.controller;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moka.gdtauto.annotation.AuthUser;
import com.moka.gdtauto.common.AutoPlanRule;
import com.moka.gdtauto.common.Result;
import com.moka.gdtauto.entity.AdAutoConf;
import com.moka.gdtauto.entity.SysUser;
import com.moka.gdtauto.mapper.AdAutoConfMapper;
import com.moka.gdtauto.service.AdAutoConfService;
import com.moka.gdtauto.service.AdPlanAutoExecutor;
import com.moka.gdtauto.service.AdPlanCreativeAutoExecutor;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 广告自动划配置表 前端控制器
 * </p>
 *
 * @author mokamvp
 * @since 2026-03-12
 */
@Tag(name = "广告自动划配置管理", description = "广告自动划配置的增删改查")
@Slf4j
@RestController
@RequestMapping("/api/ad-auto-conf")
@RequiredArgsConstructor
public class AdAutoConfController {

    private final AdAutoConfService adAutoConfService;
    private final AdAutoConfMapper adAutoConfMapper;
    private final AdPlanCreativeAutoExecutor adPlanCreativeAutoExecutor;
    private final AdPlanAutoExecutor adPlanAutoExecutor;

    /**
     * 分页查询广告自动划配置列表
     */
    @Operation(summary = "分页查询", description = "根据条件分页查询广告自动划配置列表")
    @GetMapping("/list")
    public Result<Page<AdAutoConf>> list(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "ruleName") @RequestParam(required = false) String ruleName) {
        try {
            Page<AdAutoConf> pageParam = new Page<>(page, size);
            LambdaQueryWrapper<AdAutoConf> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(StringUtils.hasText(ruleName), AdAutoConf::getRuleName, ruleName)
                    .orderByDesc(AdAutoConf::getCreateTime);
            Page<AdAutoConf> result = adAutoConfService.page(pageParam, wrapper);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询广告自动划配置列表失败", e);
            return Result.fail("查询广告自动划配置列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询广告自动划配置详情
     */
    @Operation(summary = "查询详情", description = "根据ID查询广告自动划配置详情")
    @GetMapping("/{id}")
    public Result<AdAutoConf> getById(
            @Parameter(description = "配置ID", required = true)
            @PathVariable Long id) {
        try {
            AdAutoConf conf = adAutoConfService.getById(id);
            if (conf == null) {
                return Result.fail("广告自动划配置不存在");
            }
            return Result.success(conf);
        } catch (Exception e) {
            log.error("查询广告自动划配置详情失败，ID: {}", id, e);
            return Result.fail("查询广告自动划配置详情失败: " + e.getMessage());
        }
    }

    /**
     * 新增或更新广告自动划配置
     * 使用 INSERT INTO ... ON DUPLICATE KEY UPDATE 实现
     */
    @Operation(summary = "保存配置", description = "新增或更新广告自动划配置，jobNumber+adGroupId唯一")
    @PostMapping
    public Result<AdAutoConf> save(
            @RequestBody AdAutoConf adAutoConf,
            @AuthUser SysUser sysUser) {
        try {
            adAutoConf.setJobNumber(sysUser.getJobNumber());
            adAutoConf.setCreateTime(LocalDateTime.now());
            adAutoConf.setUpdateTime(LocalDateTime.now());
            List<AutoPlanRule> rules = adPlanCreativeAutoExecutor.parseRules(adAutoConf.getRules());
            adAutoConf.setRules(JSON.toJSONString(rules));
            boolean success = adAutoConfMapper.saveOrUpdate(adAutoConf);
            if (success) {
                return Result.success(adAutoConf, "保存成功");
            } else {
                return Result.fail("保存失败");
            }
        } catch (Exception e) {
            log.error("保存广告自动划配置失败", e);
            return Result.fail("保存广告自动划配置失败: " + e.getMessage());
        }
    }

    //编辑
    @Operation(summary = "编辑配置", description = "根据ID编辑广告自动划配置")
    @PostMapping("/update")
    public Result<AdAutoConf> update(
            @RequestBody AdAutoConf adAutoConf) {
        try {
            adAutoConf.setUpdateTime(LocalDateTime.now());
             List<AutoPlanRule> rules = adPlanCreativeAutoExecutor.parseRules(adAutoConf.getRules());
            adAutoConf.setRules(JSON.toJSONString(rules));
            boolean success = adAutoConfService.updateById(adAutoConf);
            if (success) {
                return Result.success(adAutoConf, "编辑成功");
            } else {
                return Result.fail("编辑失败");
            }
        } catch (Exception e) {
            log.error("编辑广告自动划配置失败", e);
            return Result.fail("编辑广告自动划配置失败: " + e.getMessage());
        }
    }

    /**
     * 删除广告自动划配置
     */
    @Operation(summary = "删除配置", description = "根据ID删除广告自动划配置")
    @DeleteMapping("/{id}")
    public Result<Void> delete(
            @Parameter(description = "配置ID", required = true)
            @PathVariable Long id) {
        try {
            AdAutoConf conf = adAutoConfService.getById(id);
            if (conf == null) {
                return Result.fail("广告自动划配置不存在");
            }
            boolean success = adAutoConfService.removeById(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除广告自动划配置失败，ID: {}", id, e);
            return Result.fail("删除广告自动划配置失败: " + e.getMessage());
        }
    }

    @Operation(summary = "执行配置", description = "根据ID执行广告自动划配置")
    @PostMapping("/execute")
    public Result<Void> execute(
            @Parameter(description = "配置ID", required = true)
            @RequestParam Long id) {
        try {
            AdAutoConf conf = adAutoConfService.getById(id);
            if (conf == null) {
                return Result.fail("广告自动划配置不存在");
            }
            adPlanAutoExecutor.asyncExecute(conf);
            adPlanCreativeAutoExecutor.asyncExecute(conf);
            return Result.success("执行中，请稍候");
        } catch (Exception e) {
            log.error("执行广告自动划配置失败，ID: {}", id, e);
            return Result.fail("执行广告自动划配置失败: " + e.getMessage());
        }
    }
}
