package com.tzld.piaoquan.api.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.component.ManagerApiService;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.VideoGrowthMultiCoverMapper;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.VideoGrowthMultiTitleMapper;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ext.VideoMultiMapperExt;
import com.tzld.piaoquan.api.model.dto.PageUrlExtData;
import com.tzld.piaoquan.api.model.po.contentplatform.VideoGrowthMultiCover;
import com.tzld.piaoquan.api.model.po.contentplatform.VideoGrowthMultiCoverExample;
import com.tzld.piaoquan.api.model.po.contentplatform.VideoGrowthMultiTitle;
import com.tzld.piaoquan.api.model.po.contentplatform.VideoGrowthMultiTitleExample;
import com.tzld.piaoquan.api.service.VideoMultiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class VideoMultiServiceImpl implements VideoMultiService {

    @Autowired
    private ManagerApiService managerApiService;
    @Autowired
    private VideoMultiMapperExt videoMultiMapperExt;
    @Autowired
    private VideoGrowthMultiTitleMapper titleMapper;
    @Autowired
    private VideoGrowthMultiCoverMapper coverMapper;

    @Override
    public String setVideoMultiTitleCoverPagePath(Long videoId, String pageUrl, String title, String coverUrl) {
        List<VideoGrowthMultiTitle> multiTitleList = getMultiTitleByVideoId(videoId);
        List<VideoGrowthMultiCover> multiCoverList = getMultiCoverByVideoId(videoId);
        PageUrlExtData extData = new PageUrlExtData();
        if (!CollectionUtils.isEmpty(multiTitleList)) {
            Long titleId = null;
            String titleSource = "";
            for (int i = 0; i < multiTitleList.size(); i++) {
                VideoGrowthMultiTitle item = multiTitleList.get(i);
                if (title.equals(item.getTitle())) {
                    titleId = item.getId();
                    titleSource = item.getSource();
                    break;
                }
            }
            try {
                if (Objects.nonNull(titleId)) {
                    extData.setGrowthTitleId(titleId);
                    extData.setGrowthTitleSource(titleSource);
                }
            } catch (Exception e) {
                log.error("VideoMultiService VideoMultiService Error，data：", e);
            }
        }
        if (Objects.isNull(extData.getGrowthTitleId())) {
            JSONArray managerMultiTitleList = managerApiService.videoMultiTitleListV2(videoId);
            String source = "自定义";
            if (!org.springframework.util.CollectionUtils.isEmpty(managerMultiTitleList)) {
                for (int i = 0; i < managerMultiTitleList.size(); i++) {
                    JSONObject item = managerMultiTitleList.getJSONObject(i);
                    if (item.getString("title").equals(title)) {
                        if (item.getInteger("source") == 0) {
                            source = "原始";
                            break;
                        }
                    }
                }
            }
            Long titleId = saveMultiTitle(videoId, source, title);
            extData.setGrowthTitleId(titleId);
            extData.setGrowthTitleSource(source);
        }
        if (!CollectionUtils.isEmpty(multiCoverList)) {
            Long coverId = null;
            String coverSource = "";
            String videoCover = coverUrl.split("\\?")[0];
            for (int i = 0; i < multiCoverList.size(); i++) {
                VideoGrowthMultiCover item = multiCoverList.get(i);
                String itemCover = item.getCover().split("\\?")[0];
                if (videoCover.equals(itemCover)) {
                    coverId = item.getId();
                    coverSource = item.getSource();
                    break;
                }
            }
            try {
                if (Objects.nonNull(coverId)) {
                    extData.setGrowthCoverId(coverId);
                    extData.setGrowthCoverSource(coverSource);
                }
            } catch (Exception e) {
                log.error("VideoMultiService VideoMultiService Error，data：", e);
            }
        }
        if (Objects.isNull(extData.getGrowthCoverId())) {
            JSONArray managerMultiCoverList = managerApiService.videoMultiCoverListV2(videoId);
            String source = "自定义";
            if (!CollectionUtils.isEmpty(managerMultiCoverList)) {
                for (int i = 0; i < managerMultiCoverList.size(); i++) {
                    JSONObject item = managerMultiCoverList.getJSONObject(i);
                    if (item.getInteger("source") == 0) {
                        if (item.getString("coverUrl").equals(coverUrl)
                                || (coverUrl.contains("longvideo") && !coverUrl.contains("/longvideo/pic"))) {
                            source = "原始";
                            break;
                        }
                    }
                }
            }
            Long coverId = saveMultiCover(videoId, source, coverUrl);
            extData.setGrowthCoverId(coverId);
            extData.setGrowthCoverSource(source);
        }
        if (Objects.nonNull(extData.getGrowthTitleId()) || Objects.nonNull(extData.getGrowthCoverId())) {
            try {
                pageUrl = mergeOrAppendGrowthExtData(pageUrl, extData);
            } catch (Exception e) {
                log.error("VideoMultiService VideoMultiService Error，data：", e);
            }
        }
        return pageUrl;
    }

    /**
     * 将 extData 中的字段合并到 pageUrl 的 growthExtData 中：
     * - pageUrl 不含 growthExtData：在末尾拼接 URL 编码后的 &growthExtData={...}
     * - pageUrl 已含 growthExtData：解析出已有 JSON 对象，将新字段合并进去后再替换回原位置
     */
    private String mergeOrAppendGrowthExtData(String pageUrl, PageUrlExtData extData) throws Exception {
        int valueStart = -1;
        int valueEnd = -1;
        int gIdx = pageUrl.indexOf("growthExtData");
        if (gIdx >= 0) {
            int afterKey = gIdx + "growthExtData".length();
            if (pageUrl.length() > afterKey && pageUrl.charAt(afterKey) == '=') {
                valueStart = afterKey + 1;
            } else if (pageUrl.length() >= afterKey + 3
                    && pageUrl.substring(afterKey, afterKey + 3).equalsIgnoreCase("%3D")) {
                valueStart = afterKey + 3;
            }
            if (valueStart > 0) {
                valueEnd = pageUrl.length();
                int ampIdx = pageUrl.indexOf("&", valueStart);
                if (ampIdx >= 0 && ampIdx < valueEnd) {
                    valueEnd = ampIdx;
                }
                int encAmpIdx = pageUrl.indexOf("%26", valueStart);
                if (encAmpIdx >= 0 && encAmpIdx < valueEnd) {
                    valueEnd = encAmpIdx;
                }
            }
        }

        if (valueStart > 0) {
            // 已存在 growthExtData：解析出对象，将新字段合并进去
            String encodedJson = pageUrl.substring(valueStart, valueEnd);
            JSONObject existing = null;
            try {
                String jsonStr = URLDecoder.decode(encodedJson, "UTF-8");
                existing = JSONObject.parseObject(jsonStr);
            } catch (Exception e) {
                log.error("VideoMultiService parse existing growthExtData error", e);
            }
            if (existing == null) {
                existing = new JSONObject();
            }
            if (Objects.nonNull(extData.getGrowthTitleId())) {
                existing.put("growthTitleId", extData.getGrowthTitleId());
                existing.put("growthTitleSource", extData.getGrowthTitleSource());
            }
            if (Objects.nonNull(extData.getGrowthCoverId())) {
                existing.put("growthCoverId", extData.getGrowthCoverId());
                existing.put("growthCoverSource", extData.getGrowthCoverSource());
            }
            String newEncodedJson = URLEncoder.encode(JSONObject.toJSONString(existing), "UTF-8");
            return pageUrl.substring(0, valueStart) + newEncodedJson + pageUrl.substring(valueEnd);
        }

        // pageUrl 中不存在 growthExtData：直接在末尾拼接
        return pageUrl + URLEncoder.encode("&growthExtData=" + JSONObject.toJSONString(extData), "UTF-8");
    }

    @Override
    public Long saveMultiTitle(Long videoId, String source, String title) {
        VideoGrowthMultiTitle multiTitle = new VideoGrowthMultiTitle();
        multiTitle.setVideoId(videoId);
        multiTitle.setSource(source);
        multiTitle.setTitle(title);
        multiTitle.setCreateTimestamp(System.currentTimeMillis());
        videoMultiMapperExt.insertVideoMultiTitleReturnId(multiTitle);
        return multiTitle.getId();
    }

    @Override
    public List<VideoGrowthMultiTitle> getMultiTitleByVideoId(Long videoId) {
        VideoGrowthMultiTitleExample example = new VideoGrowthMultiTitleExample();
        example.createCriteria().andVideoIdEqualTo(videoId);
        return titleMapper.selectByExample(example);
    }

    @Override
    public Long saveMultiCover(Long videoId, String source, String cover) {
        VideoGrowthMultiCover multiCover = new VideoGrowthMultiCover();
        multiCover.setVideoId(videoId);
        multiCover.setSource(source);
        multiCover.setCover(cover);
        multiCover.setCreateTimestamp(System.currentTimeMillis());
        videoMultiMapperExt.insertVideoMultiCoverReturnId(multiCover);
        return multiCover.getId();
    }

    @Override
    public List<VideoGrowthMultiCover> getMultiCoverByVideoId(Long videoId) {
        VideoGrowthMultiCoverExample example = new VideoGrowthMultiCoverExample();
        example.createCriteria().andVideoIdEqualTo(videoId);
        return coverMapper.selectByExample(example);
    }

    @Override
    public List<VideoGrowthMultiTitle> getVideoGrowthMultiTitleList(List<Long> customTitleIds) {
        VideoGrowthMultiTitleExample example = new VideoGrowthMultiTitleExample();
        example.createCriteria().andIdIn(customTitleIds);
        return titleMapper.selectByExample(example);
    }

    @Override
    public List<VideoGrowthMultiCover> getVideoGrowthMultiCoverList(List<Long> customCoverIds) {
        VideoGrowthMultiCoverExample example = new VideoGrowthMultiCoverExample();
        example.createCriteria().andIdIn(customCoverIds);
        return coverMapper.selectByExample(example);
    }
}
