package com.sonic.cow.controller.web;

import com.sonic.common.auth.domains.Session;
import com.sonic.common.rpc.Result;
import com.sonic.common.utils.IpAddressUtils;
import com.sonic.common.utils.RedisLock;
import com.sonic.cow.domain.input.GenImageInput;
import com.sonic.cow.domain.input.GetGenImageInput;
import com.sonic.cow.domain.output.GenImageListOutput;
import com.sonic.cow.domain.output.GenImageOutput;
import com.sonic.cow.service.GenImageTaskService;
import com.sonic.cow.utils.RedisKeyUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Web-AI生成图片
 *
 * @author: mzc
 * @date: 2025-07-11 11:43
 **/
@RestController
@Slf4j
public class AiGenImageWeb {

    @Autowired
    private GenImageTaskService genImageTaskService;
    @Autowired
    private RedisLock.RedisWrapper redisWrapper;
    @Autowired
    private RedisKeyUtils redisKeyUtils;

    @ApiOperation(value = "创建生成图片任务", tags = {"Web-AI生成图片"})
    @PostMapping(value = "/web/gen/image-ct")
    public Result<GenImageOutput> genImageCreate(@RequestBody GenImageInput input, @ApiParam(hidden = true) Session session, @ApiParam(hidden = true) HttpServletRequest request) {
        input.setIp(IpAddressUtils.getIpAddress(request));
        input.setDeviceId(session.getDeviceCode());
        AtomicReference atomicReference = new AtomicReference();
        //操作人加锁，防止并发操作
        RedisLock redisLock = new RedisLock(redisKeyUtils.genImageLockKey(session.getUserId()), redisWrapper);
        redisLock.tryAcquireRun(3 * 1000L, () -> {
            GenImageOutput output = genImageTaskService.genImage(session, input);
            atomicReference.set(output);
            return true;
        });
        return Result.success(atomicReference.get());
    }

    @ApiOperation(value = "轮询查询图片生成结果", tags = {"Web-AI生成图片"})
    @PostMapping(value = "/web/gen/image-pl")
    public Result<List<GenImageListOutput>> poolingGetGenImage(@RequestBody GetGenImageInput input, @ApiParam(hidden = true) Session session, @ApiParam(hidden = true) HttpServletRequest request) {
        //轮询任务接口，前端每5s请求一次，超过10s未请求的话直接关闭掉任务
        return Result.success(genImageTaskService.getImage(session.getUserId(), input.getBatchNo()));
    }
}
