package com.cyksj.service.midjourney.impl;

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.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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @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);
    }

    @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());
    }

    @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);
    }

    @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").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 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());
        return param;
    }

    private void delAcount(Long id) {
        String body = HttpRequest.delete(HOST + "/mj/account/"+id+"/delete").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").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")
                .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").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.getIsMirror()) {
            return getMidjourneyUser(userId, relationId, groupsRelation, goodsDonSku);
        } else {
            throw BusinessRuntimeException.getInstance("服务器出了点问题");
        }
    }

    /**
     * 获取车位信息
     *
     * @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());
        midjourneyUser.setMjFastNum(goodsDonSku.getMjFastNum());
        midjourneyUser.setMjRelaxNum((goodsDonSku.getMjRelaxNum() == null || goodsDonSku.getMjRelaxNum() == 0) ? null : goodsDonSku.getMjRelaxNum());
        midjourneyUserMapper.insert(midjourneyUser);
        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);
        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));
        return result.getJSONObject("value").getJSONArray("saved").getJSONObject(0).getJSONObject("info").getStr("cdnUrl");
    }

}
