package com.moka.gdtauto.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moka.gdtauto.annotation.AuthUser;
import com.moka.gdtauto.common.Constant;
import com.moka.gdtauto.common.Result;
import com.moka.gdtauto.entity.TencentAssetFiction;
import com.moka.gdtauto.service.TencentAssetFictionService;
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.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.moka.gdtauto.entity.SysUser;


/**
 * 腾讯广告小说资产控制器
 *
 * @author mokamvp
 * @since 2026-03-11
 */
@Tag(name = "小说资产管理", description = "腾讯广告小说资产查询")
@Slf4j
@RestController
@RequestMapping("/api/gdt/asset/fiction")
@RequiredArgsConstructor
public class TencentAssetFictionController {
    private final RedisTemplate<String, String> redisTemplate;
    private final TencentAssetFictionService assetFictionService;

    /**
     * 同步小说资产到数据库
     *
     * @param accountId 推广账号ID
     * @return 同步结果
     */
    @Operation(
        summary = "同步小说资产到数据库",
        description = "从腾讯广告API获取指定账户的小说资产并同步到数据库"
    )
    @PostMapping("/sync")
    public Result<Void> syncAssets(
            @Parameter(description = "推广账号ID", required = true, example = "69781948")
            @RequestParam Long accountId,
        @AuthUser SysUser user) {
        try {
            String lockKey = "tencent_asset_fiction_sync_system_status_lock_" + user.getJobNumber();
            Boolean isLocked = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 1, TimeUnit.MINUTES);
            if (!isLocked) {
                return Result.fail("请勿重复操作");
            }
            int count = assetFictionService.syncMarketingAssets(user.getJobNumber(), Constant.MAIN_ORG_ACCOUNT_ID, accountId);
            return Result.<Void>success("同步成功，共同步" + count + "个小说资产")
                    .withCount(count);
        } catch (Exception e) {
            log.error("同步小说资产失败，jobNumber={},accountId={}",
                user.getJobNumber(), accountId, e);
            return Result.fail("同步失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询小说资产列表
     *
     * @param page 页码
     * @param pageSize 每页数量
     * @return 小说资产列表
     */
    @Operation(
        summary = "分页查询小说资产列表",
        description = "从数据库分页查询小说资产信息"
    )
    @GetMapping("/list")
    public Result<List<TencentAssetFiction>> listAssets(
            @Parameter(description = "小说资产名称", example = "fictionName")
            @RequestParam(required = false) String fictionName,
            @Parameter(description = "页码，从1开始", example = "1")
            @RequestParam(defaultValue = "1") Long page,
            @Parameter(description = "每页数量", example = "20")
            @RequestParam(defaultValue = "20") Long pageSize, @AuthUser SysUser user) {
        try {
            // 计算偏移量
            long offset = (page - 1) * pageSize;

            // 查询总数
            LambdaQueryWrapper<TencentAssetFiction> countWrapper = new LambdaQueryWrapper<>();
            countWrapper.eq(TencentAssetFiction::getIsDeleted, false);
            if (StringUtils.isNotBlank(fictionName)) {
                countWrapper.like(TencentAssetFiction::getMarketingAssetName, fictionName);
            }
            countWrapper.eq(TencentAssetFiction::getJobNumber, user.getJobNumber());
            long total = assetFictionService.count(countWrapper);

            // 分页查询
            LambdaQueryWrapper<TencentAssetFiction> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TencentAssetFiction::getIsDeleted, false)
                   .eq(TencentAssetFiction::getJobNumber, user.getJobNumber())
                   .orderByDesc(TencentAssetFiction::getMarketingAssetId)
                   .last("LIMIT " + offset + ", " + pageSize);
            if (StringUtils.isNotBlank(fictionName)) {
                wrapper.like(TencentAssetFiction::getMarketingAssetName, fictionName);
            }

            List<TencentAssetFiction> assetList = assetFictionService.list(wrapper);

            return Result.success(assetList, "查询成功")
                    .withPage(page, pageSize, total);
        } catch (Exception e) {
            log.error("查询小说资产列表失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    @GetMapping("/myFictionAssets")
    public Result<List<TencentAssetFiction>> getMyFictionAssets(
            @Parameter(description = "小说资产名称", example = "fictionName")
            @RequestParam(required = false) String fictionName,
        @AuthUser SysUser user) {
        try {
            LambdaQueryWrapper<TencentAssetFiction> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TencentAssetFiction::getJobNumber, user.getJobNumber());
            if (StringUtils.isNotBlank(fictionName)) {
                wrapper.like(TencentAssetFiction::getMarketingAssetName, fictionName);
            }
            wrapper.orderByDesc(TencentAssetFiction::getMarketingAssetId);
            List<TencentAssetFiction> assetList = assetFictionService.list(wrapper);
            return Result.success(assetList, "查询成功");
        } catch (Exception e) {
            log.error("查询小说资产列表失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据小说资产ID查询详情
     *
     * @param id 小说资产ID
     * @return 小说资产详情
     */
    @Operation(
        summary = "查询小说资产详情",
        description = "根据ID查询小说资产的详细信息"
    )
    @GetMapping("/detail")
    public Result<TencentAssetFiction> getAssetDetail(
            @Parameter(description = "小说资产ID", required = true)
            @RequestParam Long id) {
        try {
            LambdaQueryWrapper<TencentAssetFiction> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TencentAssetFiction::getMarketingAssetId, id)
                   .eq(TencentAssetFiction::getIsDeleted, false);

            TencentAssetFiction asset = assetFictionService.getOne(wrapper);
            if (asset != null) {
                return Result.success(asset, "查询成功");
            } else {
                return Result.fail("未找到该小说资产信息");
            }
        } catch (Exception e) {
            log.error("查询小说资产详情失败，id={}", id, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }
}
