package com.cyksj.web.controller.mirror;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.MidjourneyUserConversationMapper;
import com.cyksj.mapper.UpgradePackageMapper;
import com.cyksj.model.entity.MidjourneyUser;
import com.cyksj.model.entity.UpgradePackage;
import com.cyksj.model.views.MidjouneyCarInfoView;
import com.cyksj.model.views.MidjourneyUserConversationRecordHistoryView;
import com.cyksj.model.views.MidjourneyUserView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.midjourney.MidjourneyService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;

/** server/镜像服务/mj绘画
 * @author zwhui
 * @date 2024/4/23 10:31
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/applets/midjourney")
public class MidjourneyController {


    private final HttpServletRequest request;

    private final MidjourneyService midjourneyService;

    private final BeanSearcher beanSearcher;

    private final UpgradePackageMapper upgradePackageMapper;

    private final UserBindRelationService userBindRelationService;

    private final RedisService redisService;

    private final MidjourneyUserConversationMapper midjourneyUserConversationMapper;


    //-------------------------alpha -----------------------

    /**
     * 获取车队列表
     *
     * @param relationId
     * @return
     */
    @GetMapping("/mj/cars")
    public Result<SearchResult<MidjouneyCarInfoView>> getCarInfoList(Long relationId) {
        Long userId = StpUserUtil.getUserIdAfterLogin();
        if (relationId != null) {
            //查看用户是否存在车票
            MidjourneyUser midjourneyUser = midjourneyService.getUser(userId, relationId);
            if (midjourneyUser == null) {
                throw BusinessRuntimeException.getInstance("您还未购买车票");
            }
        }
        SearchResult<MidjouneyCarInfoView> carInfoList = beanSearcher.search(MidjouneyCarInfoView.class,MapUtils.flatBuilder(request.getParameterMap()).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(carInfoList);
    }
    /**
     * 获取指定车队ID在滑动窗口内的提问次数
     *
     * @param carId 车队ID
     * @return 滑动窗口内的请求次数
     */
    private Long getCarConversationCount(String carId, Long limitTime) {
        // 定义键名
        String key = RedisService.key.MIDJOURNEY_CAR_TASK.getName() + carId;
        long timestamp = System.currentTimeMillis();

        long windowStartMillis = timestamp - (limitTime * 60 * 1000);

        // 清除时间窗口之前的请求记录（可选，根据需要决定是否在此处清理过期记录）
        redisService.zRemoveRangeByScore(key, 0, windowStartMillis);

        // 获取当前窗口内的请求次数
        Long currentSize = redisService.zCard(key);
        return currentSize != null ? currentSize : 0L;
    }
    /**
     * 获取mj车票信息
     */
    @GetMapping("/mj/userInfo")
    public Result<MidjourneyUserView> getUserInfo(Long relationId) {
        long userId = StpUserUtil.getLoginIdAsLong();
        List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
        MidjourneyUser user = midjourneyService.getUser(userId, relationId);
        if (user == null) {
            throw BusinessRuntimeException.getInstance("您还未购买车票");
        }
        MidjourneyUserView search = beanSearcher.searchFirst(MidjourneyUserView.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(MidjourneyUserView::getUserId, userIdList).op(Operator.InList)
                .field(MidjourneyUserView::getRelationId, relationId)
                .build());
        if (search == null) {
            throw BusinessRuntimeException.getInstance("您还未购买车票");
        }
        List<UpgradePackage> upgradePackages = upgradePackageMapper.selectList(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + search.getSkuId() + "\"')").eq(UpgradePackage::getStatus, Boolean.TRUE).eq(UpgradePackage::getDeleted, Boolean.TRUE));
        if (CollectionUtil.isNotEmpty(upgradePackages)){
            upgradePackages.stream().map(e -> e.getPrice().divide(BigDecimal.valueOf(e.getNum()), 2, RoundingMode.HALF_UP)).min(BigDecimal::compareTo).ifPresent(search::setMjPackagePrice);
        }
        Integer upgradeNum = upgradePackageMapper.countUpgradenum(userId,relationId);
        search.setMjUpgradeNum(upgradeNum);
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }




    /**
     * 根据userToken mj车队跳转登录
     *
     * @param carId 车队id
     */
    @GetMapping("/mirrorLogin/{relationId}/{carId}")
    public Result<String> chatGPtCarLoginWithToken(@PathVariable Long relationId, @PathVariable String carId) {
        Long userId = StpUserUtil.getLoginIdAsLong();
        midjourneyService.getUser(userId, relationId);
        String url = midjourneyService.getCarLoginUrl(userId, relationId, carId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(url);
    }

    @PutMapping("/updateIsCar")
    public Result<String> updateIsCar(@RequestBody MidjourneyUser midjourneyUser){
        long userId = StpUserUtil.getLoginIdAsLong();
        if (midjourneyUser.getRelationId() == null || midjourneyUser.getRelationId() == 0L) {
            throw BusinessRuntimeException.getInstance("车票错误");
        }

        MidjourneyUser user = midjourneyService.getUser(userId, midjourneyUser.getRelationId());

        if (user != null) {
            midjourneyService.updateIcar(user.getId(), Optional.ofNullable(midjourneyUser.getIsCar()).orElse(true));
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 获取车队历史记录
     */
    @GetMapping("/get/car/history")
    public Result<SearchResult<MidjourneyUserConversationRecordHistoryView>> getCarHistory(Long relationId) {
        long userId = StpUserUtil.getLoginIdAsLong();
        MidjourneyUser midjourneyUser = midjourneyService.getUser(userId, relationId);
        if (midjourneyUser == null) {
            throw BusinessRuntimeException.getInstance("车票出现了异常.");
        }
        List<MidjourneyUserConversationRecordHistoryView> mjCarHistory = midjourneyUserConversationMapper.getMjCarHistory(midjourneyUser.getUserToken());
        return GatewayResponse.SUCCESS.newBuilder().toResult(new SearchResult<>(mjCarHistory));
    }

}
