package com.corewing.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.corewing.app.dto.TrajectoryData;
import com.corewing.app.dto.uploadReplaySessionRequest;
import com.corewing.app.entity.ReplaySession;
import com.corewing.app.mapper.ReplaySessionMapper;
import com.corewing.app.service.ReplaySessionService;
import com.corewing.app.util.OSSUploadUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class ReplaySessionServiceImpl extends ServiceImpl<ReplaySessionMapper, ReplaySession> implements ReplaySessionService {

    @Resource
    private Gson gson;

    /**
     * 获取飞行记录
     * @param loginId
     * @return
     */
    @Override
    public List<ReplaySession> getReplayList(Object loginId) {
        LambdaQueryWrapper<ReplaySession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReplaySession::getUserId, loginId);
        // 去oss里面下载对应的json文件流，解析到文件里面
        List<ReplaySession> list = list(queryWrapper);
        list.forEach(m -> {
            try {
                InputStream inputStream = OSSUploadUtil.downloadFileToStream(m.getOssPath());
                List<TrajectoryData> dataList = new Gson().fromJson(
                        new InputStreamReader(inputStream, StandardCharsets.UTF_8),
                        new TypeToken<List<TrajectoryData>>() {}.getType() // 增加 .getType()
                );
                m.setTrajectoryDataList(dataList);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        return list;
    }

    /**
     * 同步飞行记录
     * @param uploadReplaySessionRequests
     * @return
     */
    @Transactional
    @Override
    public boolean uploadReplaySession(List<uploadReplaySessionRequest> uploadReplaySessionRequests) {
        uploadReplaySessionRequests.forEach(replaySessionRequest -> {

            // 校验是否重复
            LambdaQueryWrapper<ReplaySession> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ReplaySession::getSyncId, replaySessionRequest.getSync_id());
            if (count(queryWrapper) > 0) {
                return;
            }

            ReplaySession replaySession = new ReplaySession();
            replaySession.setSyncId(replaySessionRequest.getSync_id());
            replaySession.setName(replaySessionRequest.getName());
            replaySession.setDuration(replaySessionRequest.getDuration());
            replaySession.setStartTime(replaySessionRequest.getStart_time());
            replaySession.setEndTime(replaySessionRequest.getEnd_time());
            replaySession.setDescription(replaySessionRequest.getDescription());
            replaySession.setDataCount(replaySessionRequest.getData_count());
            replaySession.setCreatedAt(replaySessionRequest.getCreated_at());
            replaySession.setUpdatedAt(replaySessionRequest.getUpdated_at());
            replaySession.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));

            String json = gson.toJson(replaySessionRequest.getTrajectoryDataList());
            // 必须指定编码，避免平台默认编码问题
            InputStream inputStream = new ByteArrayInputStream(
                    json.getBytes(StandardCharsets.UTF_8)
            );
            String ossPath = "trajectory/" + replaySessionRequest.getSync_id() + ".json";
            OSSUploadUtil.uploadFile(inputStream, ossPath);

            replaySession.setOssPath(ossPath);
            save(replaySession);
        });
        return true;
    }

    /**
     * 根据syncId删除数据
     * @param syncId
     * @return
     */
    @Override
    public boolean deleteReplaySession(String syncId) {
        LambdaQueryWrapper<ReplaySession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReplaySession::getSyncId, syncId);
        ReplaySession replaySession = this.getOne(queryWrapper);
        if (replaySession == null) {
            return false;
        }
        OSSUploadUtil.deleteFile("trajectory/" + syncId + ".json");
        return removeById(replaySession.getId());
    }


}
