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.TencentAssetDrama;
import com.moka.gdtauto.service.TencentAssetDramaService;
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 moka
 * @since 2026-02-06
 */
@Tag(name = "短剧资产管理", description = "腾讯广告短剧资产查询")
@Slf4j
@RestController
@RequestMapping("/api/gdt/asset/drama")
@RequiredArgsConstructor
public class TencentAssetDramaController {

    private final TencentAssetDramaService assetDramaService;
    private final RedisTemplate<String, String> redisTemplate;
    /**
     * 同步短剧资产到数据库
     * 
     * @param orgAccountId 组织账户ID
     * @param phone 手机号
     * @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_drama_sync_system_status_lock_" + user.getJobNumber();
            Boolean isLocked = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 1, TimeUnit.MINUTES);
            if (!isLocked) {
                return Result.fail("请勿重复操作");
            }
            int count = assetDramaService.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<TencentAssetDrama>> listAssets(
            @Parameter(description = "短剧资产名称", example = "dramaName")
            @RequestParam(required = false) String dramaName,
            @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<TencentAssetDrama> countWrapper = new LambdaQueryWrapper<>();
            countWrapper.eq(TencentAssetDrama::getIsDeleted, 0);
            if (StringUtils.isNotBlank(dramaName)) {
                countWrapper.like(TencentAssetDrama::getMarketingAssetName, dramaName);
            }
            countWrapper.eq(TencentAssetDrama::getJobNumber, user.getJobNumber());
            long total = assetDramaService.count(countWrapper);
            
            // 分页查询
            LambdaQueryWrapper<TencentAssetDrama> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TencentAssetDrama::getIsDeleted, 0)
                   .eq(TencentAssetDrama::getJobNumber, user.getJobNumber())
                   .orderByDesc(TencentAssetDrama::getMarketingAssetId)
                   .last("LIMIT " + offset + ", " + pageSize);
            if (StringUtils.isNotBlank(dramaName)) {
                wrapper.like(TencentAssetDrama::getMarketingAssetName, dramaName);
            }
            
            List<TencentAssetDrama> assetList = assetDramaService.list(wrapper);
            
            return Result.success(assetList, "查询成功")
                    .withPage(page, pageSize, total);
        } catch (Exception e) {
            log.error("查询短剧资产列表失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    @GetMapping("/myDramaAssets")
    public Result<List<TencentAssetDrama>> getMyDramaAssets(
            @Parameter(description = "短剧资产名称", example = "dramaName")
            @RequestParam(required = false) String dramaName,
        @AuthUser SysUser user) {
        try {
            LambdaQueryWrapper<TencentAssetDrama> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TencentAssetDrama::getJobNumber, user.getJobNumber());
            if (StringUtils.isNotBlank(dramaName)) {
                wrapper.like(TencentAssetDrama::getMarketingAssetName, dramaName);
            }
            wrapper.orderByDesc(TencentAssetDrama::getMarketingAssetId);
            List<TencentAssetDrama> assetList = assetDramaService.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<TencentAssetDrama> getAssetDetail(
            @Parameter(description = "短剧资产ID", required = true)
            @RequestParam Long id) {
        try {
            LambdaQueryWrapper<TencentAssetDrama> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TencentAssetDrama::getMarketingAssetId, id)
                   .eq(TencentAssetDrama::getIsDeleted, 0);
            
            TencentAssetDrama asset = assetDramaService.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());
        }
    }
}
