package com.cyksj.web.controller.manage.mj;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.MidjourneySessionMapper;
import com.cyksj.model.entity.ChatgptSession;
import com.cyksj.model.entity.MidjourneyAccount;
import com.cyksj.model.entity.MidjourneySession;
import com.cyksj.model.manage.views.AccountView;
import com.cyksj.model.views.ChatgptCarSessionView;
import com.cyksj.model.views.MidjourneyAccountView;
import com.cyksj.model.views.MidjourneyCarSessionView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.midjourney.MidjourneyAccountService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapBuilder;
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.util.Optional;

/**
 * @author zwhui
 * @date 2024/4/15 14:38
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/mj")
public class MidJourneyController {

    private final BeanSearcher beanSearcher;

    private final HttpServletRequest request;

    private final MidjourneyAccountService midjourneyAccountService;

    private final MidjourneySessionMapper midjourneySessionMapper;

    private final RedisService redisService;


    /**
     * 移入MJ账号池
     */
    @PostMapping("/addAccount")
    public Result<Void> addAccount(@RequestBody MidjourneyAccount midjourneyAccount) throws Exception {
        log.info("移入MJ账号池 midjourneyAccount:{}", midjourneyAccount);
        midjourneyAccountService.addAccount(midjourneyAccount);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 移除MJ账号池
     */
    @DeleteMapping("/removeAccount/{id}")
    public Result<Void> removeAccount(@PathVariable Long id) {
        log.info("移除MJ账号池 id:{}", id);
        midjourneyAccountService.removeAccount(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 修改MJ账号池
     */
    @PutMapping("/updateAccount")
    public Result<Void> updateAccount(@RequestBody MidjourneyAccount midjourneyAccount) {
        log.info("修改MJ账号池 midjourneyAccount:{}", midjourneyAccount);
        midjourneyAccountService.updateAccount(midjourneyAccount);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 上下架MJ账号
     */
    @PutMapping("/updateStatus/{id}")
    public Result<Void> updateStatus(@PathVariable Long id) {
        log.info("上下架MJ账号 id:{}", id);
        midjourneyAccountService.updateStatus(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 同步账号信息
     */
    @PutMapping("/syncAccount/{id}")
    public Result<Void> syncAccount(@PathVariable Long id) {
        log.info("同步账号信息 id:{}", id);
        midjourneyAccountService.syncAccount(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    /**
     * 查询账号池列表
     */
    @GetMapping("/getAccount")
    public Result<SearchResult<MidjourneyAccountView>> getAccount(String expiryStartTime, String expiryEndTime) {
        log.info("查询账号池列表");
        MapBuilder mapBuilder = MapUtils.flatBuilder(request.getParameterMap());
        if (StrUtil.isNotEmpty(expiryStartTime) || StrUtil.isNotEmpty(expiryEndTime)) {
            mapBuilder.field(MidjourneyAccountView::getExpiryTime, expiryStartTime, expiryEndTime)
                    .op(Operator.Between);
        }
        SearchResult<MidjourneyAccountView> search = beanSearcher.search(MidjourneyAccountView.class, mapBuilder.build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }



    /**
     * 获取镜像车队账号列表
     */
    @GetMapping("/get/midjourneyCar")
    public Result<SearchResult<MidjourneyCarSessionView>> getMirrorCarSession() {
        SearchResult<MidjourneyCarSessionView> search = beanSearcher.search(MidjourneyCarSessionView.class, MapUtils.flatBuilder(request.getParameterMap())
                .orderBy(MidjourneyCarSessionView::getId).desc()
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 编辑镜像车队账号列表
     */
    @PutMapping("/update/midjourneyCar")
    public Result<String> updateMirrorCarSession(@RequestBody MidjourneySession midjourneySession) {
        Integer selectCount = midjourneySessionMapper.selectCount(Wrappers.lambdaQuery(MidjourneySession.class)
                .and(e -> e.eq(MidjourneySession::getEmail, midjourneySession.getEmail())
                        .or().eq(MidjourneySession::getCarId, midjourneySession.getCarId()))
                .ne(MidjourneySession::getId, midjourneySession.getId()));
        if (selectCount > 0) {
            throw BusinessRuntimeException.getInstance("请检验车队ID或账号是否已存在");
        }
        midjourneySessionMapper.updateById(midjourneySession);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 删除镜像车队账号
     */
    @DeleteMapping("/delete/midjourneyCar/{id}")
    public Result<String> deleteMirrorCarSession(@PathVariable Long id) {
        Optional.ofNullable(midjourneySessionMapper.selectById(id))
                .ifPresent(e -> {
                    String carId = e.getCarId();
                    if (StrUtil.isNotBlank(carId)) {
                        midjourneySessionMapper.deleteById(e.getId());
                        String carKey = RedisService.key.MIDJOURNEY_CAR_TASK.getName() + carId;
                        //从zSet中删除车队
                        redisService.del(carKey);
                    }
                });
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 新增镜像车队账号
     */
    @PostMapping("/post/midjourney/car/session")
    public Result<String> postMirrorCarSession(@RequestBody MidjourneySession midjourneySession) {
        Integer selectCount = midjourneySessionMapper.selectCount(Wrappers.lambdaQuery(MidjourneySession.class)
                .eq(MidjourneySession::getCarId, midjourneySession.getCarId()).or().eq(MidjourneySession::getEmail, midjourneySession.getEmail()));
        if (selectCount > 0) {
            throw BusinessRuntimeException.getInstance("请检验车队ID或账号是否已存在");
        }
        midjourneySessionMapper.insert(midjourneySession);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

}
