package com.cyksj.service.midjourney.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.StringUtil;
import com.cyksj.mapper.*;
import com.cyksj.model.entity.*;
import com.cyksj.redis.RedisService;
import com.cyksj.service.midjourney.MidjourneyService;
import com.cyksj.service.sys.SysConfigService;
import com.cyksj.service.user.UserBindRelationService;
import com.ejlchina.searcher.BeanSearcher;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zwhui
 * @date 2024/4/23 15:44
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MidjourneyServiceImpl implements MidjourneyService {

    private final MidjourneyUserMapper midjourneyUserMapper;

    private final GroupsRelationMapper groupsRelationMapper;

    private final BeanSearcher beanSearcher;

    private final UserBindRelationService userBindRelationService;

    private final GroupsMapper groupsMapper;

    private final UserMapper userMapper;

    private final RedisService redisService;

    private final GoodsDonSkuMapper skuMapper;

    private final SysConfigService sysConfigService;

    @Override
    public MidjourneyUser getUser(long userId, Long relationId) {
        GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
        GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
        GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());

        if (goodsDonSku != null && goodsDonSku.getGoodsId() == 26 && goodsDonSku.getIsMirror()) {
            return getMidjourneyUser(userId, relationId, groupsRelation, goodsDonSku);
        } else {
            throw BusinessRuntimeException.getInstance("服务器出了点问题");
        }
    }

    @Override
    public String getCarLoginUrl(Long userId, Long relationId, String carId) {

        GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
        GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
        GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
        if (goodsDonSku != null && goodsDonSku.getIsMirror()) {
            MidjourneyUser midjourneyUser = getMidjourneyUser(userId, relationId, groupsRelation, goodsDonSku);

            String DOMAIN = "https://mj.yinhedvd.com";
            try {
                SysConfig sysConfig = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getSysKey, "mirror_mj_domain"));
                if (sysConfig != null) {
                    String sysValue = sysConfig.getSysValue();
                    if (JSONUtil.isJsonArray(sysValue)) {
                        List<String> domainList = JSONUtil.parseArray(sysValue).toList(String.class);
                        DOMAIN = domainList.get(RandomUtil.randomInt(domainList.size()));
                    }
                }
            } catch (Exception e) {
                log.error("随机抽取域名错误. msg:{}", StringUtil.getErrorText(e));
            }
            log.info("domain:{}，用户:{},所在车次:{},座位id:{},在{}获取跳转Midjourney镜像的登录url", DOMAIN, userId, groupsTrips.getId(), relationId, DateTime.now());
            return DOMAIN + "/auth/logintoken?carid=" + carId + "&usertoken=" + midjourneyUser.getUserToken();
        } else {
            throw BusinessRuntimeException.getInstance("服务器出了点问题");
        }
    }

    @Override
    public void updateIcar(Long id, Boolean isCar) {
        midjourneyUserMapper.update(null,Wrappers.lambdaUpdate(MidjourneyUser.class).eq(MidjourneyUser::getId, id).set(MidjourneyUser::getIsCar,isCar));
    }


    /**
     * 获取车位信息
     *
     * @param userId
     * @param relationId
     * @return
     */
    private GroupsRelation getGroupsRelation(Long userId, Long relationId) {
        List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
        GroupsRelation groupsRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).in(GroupsRelation::getUserId, userIdList).eq(GroupsRelation::getId, relationId));
        if (groupsRelation == null) {
            throw BusinessRuntimeException.getInstance("车票不存在");
        }
        return groupsRelation;
    }

    /**
     * 获取车队信息
     *
     * @param groupsRelation
     * @return
     */
    private GroupsTrips getGroupsTrips(GroupsRelation groupsRelation) {
        GroupsTrips groupsTrips = groupsMapper.selectById(groupsRelation.getGroupsId());
        if (groupsTrips == null) {
            throw BusinessRuntimeException.getInstance("车队异常");
        }
        return groupsTrips;
    }

    private MidjourneyUser getMidjourneyUser(Long userId, Long relationId, GroupsRelation groupsRelation, GoodsDonSku goodsDonSku) {
        MidjourneyUser midjourneyUser = midjourneyUserMapper.selectOne(Wrappers.lambdaQuery(MidjourneyUser.class).eq(MidjourneyUser::getRelationId, relationId));
        User user = userMapper.selectById(userId);
        if (midjourneyUser == null) {
            midjourneyUser = createMidjourneyUser(groupsRelation, user, goodsDonSku);
        } else {
            updateMidjourneyUser(groupsRelation, user, midjourneyUser);
        }
        return midjourneyUser;
    }

    /**
     * 创建MidjourneyUser
     */
    private synchronized MidjourneyUser createMidjourneyUser(GroupsRelation groupsRelation, User user, GoodsDonSku goodsDonSku) {
        MidjourneyUser midjourneyUser = new MidjourneyUser();
        midjourneyUser.setExpireTime(groupsRelation.getExpiryTime());
        midjourneyUser.setName(user.getNickname());
        midjourneyUser.setImg("https://cdn.sxfoundation.com/picture/f6ee11101c4f5f0bc48d88aca7a5dbfd-1666945673391.png");
        midjourneyUser.setRelationId(groupsRelation.getId());
        midjourneyUser.setUserToken(UUID.randomUUID().toString());
        if (groupsRelation.getAqType() == 2) {
            //fast模式 5次
            midjourneyUser.setMjFastNum(5);
            midjourneyUser.setMjRelaxNum(0);
        } else {
            midjourneyUser.setMjFastNum(goodsDonSku.getMjFastNum());
            midjourneyUser.setMjRelaxNum(goodsDonSku.getMjRelaxNum() == null ? null : goodsDonSku.getMjRelaxNum());
        }
        midjourneyUser.setAqType(groupsRelation.getAqType());
        try {
            midjourneyUserMapper.insert(midjourneyUser);
        } catch (DuplicateKeyException e) {
        }
        redisService.set(RedisService.key.MIDJOURNEY_FAST_LIMIT.getName() + midjourneyUser.getId(), midjourneyUser.getMjFastNum(), RedisService.key.MIDJOURNEY_FAST_LIMIT.getTimeout());
        redisService.set(RedisService.key.MIDJOURNEY_USER.getName() + midjourneyUser.getUserToken(), midjourneyUser, RedisService.key.MIDJOURNEY_USER.getTimeout());
        if (midjourneyUser.getMjRelaxNum() != null) {
            redisService.set(RedisService.key.MIDJOURNEY_RELAX_LIMIT.getName() + midjourneyUser.getId(), midjourneyUser.getMjRelaxNum(), RedisService.key.MIDJOURNEY_RELAX_LIMIT.getTimeout());
        }
        return midjourneyUser;
    }

    private void updateMidjourneyUser(GroupsRelation groupsRelation, User user, MidjourneyUser midjourneyUser) {
        midjourneyUser.setName(user.getNickname());
        midjourneyUser.setImg("https://cdn.sxfoundation.com/picture/f6ee11101c4f5f0bc48d88aca7a5dbfd-1666945673391.png");
        midjourneyUser.setExpireTime(groupsRelation.getExpiryTime());
        midjourneyUserMapper.updateById(midjourneyUser);
        midjourneyUser.setAqType(groupsRelation.getAqType());
        redisService.set(RedisService.key.MIDJOURNEY_USER.getName() + midjourneyUser.getUserToken(), midjourneyUser, RedisService.key.MIDJOURNEY_USER.getTimeout());
    }

}
