package com.cyksj.service.midjourney.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
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.MidjourneyAccountService;
import com.cyksj.service.user.UserBindRelationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.stream.FileImageOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;

/**
 * @author zwhui
 * @date 2024/4/12 15:54
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MidJourneyAccountServiceImpl extends ServiceImpl<MidjourneyAccountMapper, MidjourneyAccount> implements MidjourneyAccountService {

    private static final String HOST = "http://43.154.230.104:8080";

    private final GroupsRelationMapper groupsRelationMapper;

    private final GroupsMapper groupsMapper;

    private final GoodsDonSkuMapper skuMapper;

    private final UserMapper userMapper;

    private final UserBindRelationService userBindRelationService;

    private final MidjourneyUserMapper midjourneyUserMapper;

    private final RedisService redisService;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void addAccount(MidjourneyAccount midjourneyAccount) throws Exception {
        baseMapper.insert(midjourneyAccount);
        addAcount(midjourneyAccount);
        //拉取plus服务账号实例id
        Long instanceId = getAccount(midjourneyAccount.getId());
        midjourneyAccount.setInstanceId(instanceId);
        baseMapper.updateById(midjourneyAccount);
        String key = RedisService.key.MIDJOURNEY_ACCOUNT.getName();
        Map<Object, Object> accountsUsage = redisService.hmget(key);
        if (MapUtil.isNotEmpty(accountsUsage)) {
            redisService.hset(key,midjourneyAccount.getInstanceId().toString(),accountsUsage.values().toArray()[0]);
        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void removeAccount(Long id) {
        MidjourneyAccount midjourneyAccount = baseMapper.selectById(id);
        if (midjourneyAccount == null) {
            throw BusinessRuntimeException.getInstance("账号不存在");
        }
        baseMapper.deleteById(id);
        //删除plus服务账号信息
        delAcount(midjourneyAccount.getInstanceId());
        redisService.hdel(RedisService.key.MIDJOURNEY_ACCOUNT.getName(),midjourneyAccount.getInstanceId());
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateAccount(MidjourneyAccount midjourneyAccount) {
        MidjourneyAccount account = baseMapper.selectById(midjourneyAccount.getId());
        if (account == null) {
            throw BusinessRuntimeException.getInstance("账号不存在");
        }
        baseMapper.updateById(midjourneyAccount);
        midjourneyAccount.setInstanceId(account.getInstanceId());
        updAccount(midjourneyAccount);
    }

    @Override
    public void updateStatus(Long id) {
        MidjourneyAccount midjourneyAccount = baseMapper.selectById(id);
        if (midjourneyAccount == null) {
            throw BusinessRuntimeException.getInstance("账号不存在");
        }
        midjourneyAccount.setStatus(!midjourneyAccount.getStatus());
        baseMapper.updateById(midjourneyAccount);
        updAccount(midjourneyAccount);
        String key = RedisService.key.MIDJOURNEY_ACCOUNT.getName();
        if (!midjourneyAccount.getStatus()) {
            redisService.hdel(key,midjourneyAccount.getInstanceId());
        }else {
            Map<Object, Object> accountsUsage = redisService.hmget(key);
            if (MapUtil.isNotEmpty(accountsUsage)) {
                redisService.hset(key,midjourneyAccount.getInstanceId().toString(),accountsUsage.values().toArray()[0]);
            }
        }
    }

    @Override
    public void syncAccount(Long id) {
        MidjourneyAccount midjourneyAccount = baseMapper.selectById(id);
        if (midjourneyAccount == null) {
            throw BusinessRuntimeException.getInstance("账号不存在");
        }
        String fastRemainTime = syncInfo(midjourneyAccount.getInstanceId());
        midjourneyAccount.setFastRemainTime(fastRemainTime);
        baseMapper.updateById(midjourneyAccount);
    }


    private void addAcount(MidjourneyAccount midjourneyAccount) throws Exception {
        Map<String, Object> accountParam = createAccountParam(midjourneyAccount);
        String body = HttpRequest.post(HOST + "/mj/account/create").header("mj-api-secret", "5a9a3e9b-5a5e-4b6b-9a5a-9a5a5a5a5a5a").body(Jsons.toJson(accountParam)).execute().body();
        log.info("addAccount body:{}", body);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if (jsonObject.getInt("code") != 1) {
            throw BusinessRuntimeException.getInstance("addAccount error message:" + jsonObject.getStr("description"));
        }
    }
    private static final List<String> User_Agent_LIST =  List.of(
            "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
            "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
            "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
            "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
            "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
            "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
            "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10");
    private Map<String, Object> createAccountParam(MidjourneyAccount midjourneyAccount) {
        Map<String, Object> param = new HashMap<>();
        param.put("channelId", midjourneyAccount.getChannelId());
        param.put("guildId", midjourneyAccount.getGuildId());
        param.put("userToken", midjourneyAccount.getUserToken());
        param.put("remark", midjourneyAccount.getId());
        param.put("userAgent", User_Agent_LIST.get(new Random().nextInt(User_Agent_LIST.size())));
        param.put("timeoutMinutes", 10);
        return param;
    }

    private void delAcount(Long id) {
        String body = HttpRequest.delete(HOST + "/mj/account/"+id+"/delete").header("mj-api-secret", "5a9a3e9b-5a5e-4b6b-9a5a-9a5a5a5a5a5a").execute().body();
        log.info("delAcount body:{}", body);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if (jsonObject.getInt("code") != 1) {
            throw BusinessRuntimeException.getInstance("delAcount error message:" + jsonObject.getStr("description"));
        }
    }

    private Long getAccount(Long id) throws Exception {
        String body = HttpRequest.post(HOST + "/mj/account/query").header("mj-api-secret", "5a9a3e9b-5a5e-4b6b-9a5a-9a5a5a5a5a5a").body(Jsons.toJson(MapUtil.of("remark", id))).execute().body();
        log.info("getAccount body:{}", body);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        return JSONUtil.parseObj(JSONUtil.parseArray(jsonObject.getStr("content")).get(0)).get("id", Long.class);
    }

    private void updAccount(MidjourneyAccount midjourneyAccount){
        Map<String, Object> accountParam = createAccountParam(midjourneyAccount);
        String body = HttpRequest.put(HOST + "/mj/account/"+midjourneyAccount.getInstanceId()+"/update-reconnect")
                .header("mj-api-secret", "5a9a3e9b-5a5e-4b6b-9a5a-9a5a5a5a5a5a").body(JSONUtil.toJsonStr(accountParam)).execute().body();
        log.info("updAccount body:{}", body);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if (jsonObject.getInt("code") != 1) {
            throw BusinessRuntimeException.getInstance("updAccount error message:" + jsonObject.getStr("description"));
        }
    }

    private String syncInfo(Long id){
        String body = HttpRequest.post(HOST + "/mj/account/"+id+"/sync-info").header("mj-api-secret", "5a9a3e9b-5a5e-4b6b-9a5a-9a5a5a5a5a5a").execute().body();
        log.info("syncInfo body:{}", body);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if (jsonObject.getInt("code") != 1) {
            throw BusinessRuntimeException.getInstance("syncInfo error message:" + jsonObject.getStr("description"));
        }
        return JSONUtil.parseObj(jsonObject.getStr("result")).getStr("fastTimeRemaining");
    }


    @Override
    public MidjourneyUser getMidjourneyUserToken(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 void updateUserExpiryTime(Long relationId, Date expiryTime) {
        midjourneyUserMapper.update(null, Wrappers.lambdaUpdate(MidjourneyUser.class)
                .set(MidjourneyUser::getExpireTime, expiryTime)
                .eq(MidjourneyUser::getRelationId, relationId));
    }

    /**
     * 获取车位信息
     *
     * @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(getWxImg(user.getHeadimgurl(), user));
        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(getWxImg(user.getHeadimgurl(), user));
        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());
    }

    /**
     * 更换wx头像至oss
     */
    private String getWxImg(String headimgurl, User user) {
        if (headimgurl.contains("thirdwx.qlogo.cn")) {
            try {
                return uploadPic(headimgurl, "wxheadimg-" + user.getId());
            } catch (Exception ex) {
                log.error("上传微信头像错误！msg:{}", StringUtil.getErrorText(ex));
                return "./avatars.png";
            }
        } else {
            return user.getHeadimgurl();
        }
    }

    private static String uploadPic(String url, String prefix) throws IOException {
        byte[] body = HttpUtil.downloadBytes(url);
        Path tempFile = Files.createTempFile(prefix, ".jpeg");
        try (FileImageOutputStream imageOutput = new FileImageOutputStream(tempFile.toFile())) {
            imageOutput.write(body, 0, body.length);
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("file", tempFile.toFile());
        JSONObject result = JSONUtil.parseObj(HttpUtil.post("https://files.liuliangbang.vip/pic/ups", paramMap));
        FileUtil.del(tempFile);
        return result.getJSONObject("value").getJSONArray("saved").getJSONObject(0).getJSONObject("info").getStr("cdnUrl");
    }

}
