package com.moka.gdtauto.controller;

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.Result;
import com.moka.gdtauto.entity.LoadPageConf;
import com.moka.gdtauto.entity.SysUser;
import com.moka.gdtauto.mapper.LoadPageConfMapper;
import com.moka.gdtauto.service.LoadPageConfService;
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;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * <p>
 * 落地页配置表 前端控制器
 * </p>
 *
 * @author mokamvp
 * @since 2026-03-10
 */
@Tag(name = "落地页配置管理", description = "落地页配置的增删改查")
@Slf4j
@RestController
@RequestMapping("/api/load-page-conf")
@RequiredArgsConstructor
public class LoadPageConfController {

    private final LoadPageConfService loadPageConfService;
    private final LoadPageConfMapper loadPageConfMapper;

    @GetMapping("/all")
    public Result<List<LoadPageConf>> getAll() {
        List<LoadPageConf> loadPageConfList = loadPageConfService.lambdaQuery()
        .eq(LoadPageConf::getDeleted, false)
        .list();
        return Result.success(loadPageConfList);
    }
    

    /**
     * 分页查询落地页配置列表
     */
    @Operation(summary = "分页查询", description = "根据条件分页查询落地页配置列表")
    @GetMapping("/list")
    public Result<Page<LoadPageConf>> list(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "页面名称") @RequestParam(required = false) String name,
            @Parameter(description = "落地页ID") @RequestParam(required = false) Long pageId) {
        try {
            Page<LoadPageConf> pageParam = new Page<>(page, size);
            LambdaQueryWrapper<LoadPageConf> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(StringUtils.hasText(name), LoadPageConf::getName, name)
                    .eq(pageId != null, LoadPageConf::getPageId, pageId)
                    .orderByDesc(LoadPageConf::getCreateTime);
            Page<LoadPageConf> result = loadPageConfService.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<LoadPageConf> getById(
            @Parameter(description = "配置ID", required = true)
            @PathVariable Long id) {
        try {
            LoadPageConf conf = loadPageConfService.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());
        }
    }

    /**
     * 新增落地页配置
     */
    @Operation(summary = "新增配置", description = "新增落地页配置")
    @PostMapping
    public Result<LoadPageConf> save(
            @RequestBody LoadPageConf loadPageConf,
            @AuthUser SysUser sysUser) {
        try {
            if (!StringUtils.hasText(loadPageConf.getName())) {
                return Result.fail("页面名称不能为空");
            }
            if (loadPageConf.getPageId() == null) {
                return Result.fail("落地页ID不能为空");
            }
            loadPageConf.setCreateUserId(sysUser.getId());
            loadPageConf.setCreateUserName(sysUser.getName());
            loadPageConf.setCreateTime(LocalDateTime.now());
            loadPageConf.setUpdateTime(LocalDateTime.now());
            loadPageConf.setDeleted(false);
            boolean success = loadPageConfMapper.saveIfNeed(loadPageConf);
            if (success) {
                return Result.success(loadPageConf, "新增成功");
            } else {
                return Result.fail("新增失败");
            }
        } catch (Exception e) {
            log.error("新增落地页配置失败", e);
            return Result.fail("新增落地页配置失败: " + e.getMessage());
        }
    }

    /**
     * 更新落地页配置
     */
    @Operation(summary = "更新配置", description = "更新落地页配置")
    @PutMapping
    public Result<LoadPageConf> update(
        @AuthUser SysUser sysUser,
            @RequestBody LoadPageConf loadPageConf) {
        try {
            if (loadPageConf.getId() == null) {
                return Result.fail("配置ID不能为空");
            }
            LoadPageConf existConf = loadPageConfService.getById(loadPageConf.getId());
            if (existConf == null) {
                return Result.fail("落地页配置不存在");
            }
            loadPageConf.setCreateUserId(sysUser.getId());
            loadPageConf.setCreateUserName(sysUser.getName());
            loadPageConf.setDeleted(false);
            boolean success = loadPageConfMapper.saveIfNeed(loadPageConf);
            if (success) {
                return Result.success(loadPageConf, "更新成功");
            } else {
                return Result.fail("更新失败");
            }
        } catch (Exception e) {
            log.error("更新落地页配置失败", e);
            return Result.fail("更新落地页配置失败: " + e.getMessage());
        }
    }

}
