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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.component.AigcApiService;
import com.tzld.piaoquan.api.component.ManagerApiService;
import com.tzld.piaoquan.api.component.TouLiuHttpClient;
import com.tzld.piaoquan.api.dao.mapper.GhDetailExtMapper;
import com.tzld.piaoquan.api.dao.mapper.GhDetailMapperExt;
import com.tzld.piaoquan.api.model.po.GhDetailExt;
import com.tzld.piaoquan.api.model.po.GhDetailExtExample;
import com.tzld.piaoquan.api.model.po.contentplatform.VideoGrowthMultiCover;
import com.tzld.piaoquan.api.model.po.contentplatform.VideoGrowthMultiTitle;
import com.tzld.piaoquan.api.model.vo.GhDetailVo;
import com.tzld.piaoquan.api.service.GhDetailService;
import com.tzld.piaoquan.api.service.VideoMultiService;
import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
import com.tzld.piaoquan.growth.common.common.enums.GhTypeEnum;
import com.tzld.piaoquan.growth.common.common.enums.StrategyStatusEnum;
import com.tzld.piaoquan.growth.common.dao.mapper.CgiReplyBucketDataMapper;
import com.tzld.piaoquan.growth.common.dao.mapper.GhDetailMapper;
import com.tzld.piaoquan.growth.common.model.po.CgiReplyBucketData;
import com.tzld.piaoquan.growth.common.model.po.CgiReplyBucketDataExample;
import com.tzld.piaoquan.growth.common.model.po.GhDetail;
import com.tzld.piaoquan.growth.common.model.po.GhDetailExample;
import com.tzld.piaoquan.growth.common.utils.DateUtil;
import com.tzld.piaoquan.growth.common.utils.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GhDetailServiceImpl implements GhDetailService {

    @Autowired
    private GhDetailMapper ghDetailMapper;
    @Autowired
    private GhDetailExtMapper ghDetailExtMapper;
    @Autowired
    private GhDetailMapperExt ghDetailMapperExt;
    @Autowired
    private AigcApiService aigcApiService;
    @Autowired
    private TouLiuHttpClient touLiuHttpClient;
    @Autowired
    private CgiReplyBucketDataMapper cgiReplyBucketDataMapper;
    @Autowired
    private ManagerApiService managerApiService;
    @Autowired
    private VideoMultiService videoMultiService;

    @Value("${small_page_url}")
    private String GET_SMALL_PAGE_URL;
    @Value("${rootSourceConfig:{}}")
    private String rootSourceConfig;

    @Override
    public CommonResponse<Page<GhDetailVo>> getGhDetailList(Integer pageNum, Integer pageSize,
                                                            String accountId, String accountName, Long videoId) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }
        if (pageSize > 100) {
            pageSize = 100;
        }
        Page<GhDetailVo> page = new Page<>();
        page.setCurrentPage(pageNum);
        page.setPageSize(pageSize);
        GhDetailExample example = new GhDetailExample();
        example.setOrderByClause("create_time desc");
        GhDetailExample.Criteria criteria = example.createCriteria().andIsDeleteEqualTo(0);
        if (StringUtils.isNotEmpty(accountId)) {
            criteria.andGhIdEqualTo(accountId);
        }
        if (StringUtils.isNotEmpty(accountName)) {
            criteria.andGhNameLike("%" + accountName + "%");
        }
        if (Objects.nonNull(videoId)) {
            criteria.andVideoIdsLike("%" + videoId + "%");
        }
        example.setPage(page);
        long total = ghDetailMapper.countByExample(example);
        page.setTotalSize((int) total);
        List<GhDetail> ghDetails = ghDetailMapper.selectByExample(example);
        List<GhDetailVo> ghDetailVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(ghDetails)) {
            List<Long> ghDetailIds = ghDetails.stream().map(GhDetail::getId).collect(Collectors.toList());
            GhDetailExtExample exampleExt = new GhDetailExtExample();
            exampleExt.createCriteria().andGhDetailIdIn(ghDetailIds).andIsDeleteEqualTo(0);
            List<GhDetailExt> ghDetailExts = ghDetailExtMapper.selectByExample(exampleExt);
            Map<Long, List<GhDetailExt>> ghDetailExtMap = ghDetailExts.stream().collect(Collectors.groupingBy(GhDetailExt::getGhDetailId));
            for (GhDetail ghDetail : ghDetails) {
                GhDetailVo ghDetailVo = new GhDetailVo();
                BeanUtils.copyProperties(ghDetail, ghDetailVo);
                ghDetailVo.setAccountId(ghDetail.getGhId());
                ghDetailVo.setAccountName(ghDetail.getGhName());
                ghDetailVo.setTypeName(GhTypeEnum.getTypeName(ghDetailVo.getType()));
                ghDetailVo.setCreateTime(DateUtil.getDateString(ghDetail.getCreateTime().getTime(), "yyyy-MM-dd HH:mm:ss"));
                ghDetailVo.setUpdateTime(DateUtil.getDateString(ghDetail.getUpdateTime().getTime(), "yyyy-MM-dd HH:mm:ss"));
                ghDetailVo.setChannel(ghDetail.getChannel());
                if (StringUtils.isNotEmpty(ghDetail.getVideoIds())) {
                    List<Long> videoIds = JSONObject.parseArray(ghDetail.getVideoIds(), Long.class);
                    ghDetailVo.setVideoIds(videoIds);
                    List<GhDetailExt> videoExts = ghDetailExtMap.get(ghDetail.getId());
                    if (!CollectionUtils.isEmpty(videoExts)) {
                        videoExts.sort(Comparator.comparing(GhDetailExt::getSort));
                        List<GhDetailVo.VideoDetail> videoList = new ArrayList<>();
                        for (GhDetailExt videoExt : videoExts) {
                            GhDetailVo.VideoDetail videoDetail = new GhDetailVo.VideoDetail();
                            videoDetail.setVideoId(videoExt.getVideoId());
                            videoDetail.setSort(videoExt.getSort());
                            videoDetail.setTitle(videoExt.getTitle());
                            videoDetail.setCover(videoExt.getCover());
                            videoList.add(videoDetail);
                        }
                        ghDetailVo.setVideoList(videoList);
                    }
                }
                ghDetailVo.setStrategyStatusName(StrategyStatusEnum.getStrategyStatusName(ghDetail.getStrategyStatus()));
                ghDetailVos.add(ghDetailVo);
            }
        }
        page.setObjs(ghDetailVos);
        return CommonResponse.success(page);
    }


    @Override
    public CommonResponse<Void> addGhDetail(GhDetailVo ghDetailVo, Map<Long, String> videoIdTestIdMap) {
        if (ghDetailVo == null
                || StringUtils.isEmpty(ghDetailVo.getAccountId())
                || StringUtils.isEmpty(ghDetailVo.getAccountName())
                || ghDetailVo.getType() == null
                || StringUtils.isEmpty(ghDetailVo.getCategory1())) {
            return CommonResponse.create(500, "参数错误");
        }

        CommonResponse<Void> checkParamRes = checkParam(ghDetailVo);
        if (checkParamRes != null) {
            return checkParamRes;
        }

        try {
            GhDetail ghDetail = new GhDetail();
            BeanUtils.copyProperties(ghDetailVo, ghDetail);
            if (StringUtils.isNotEmpty(ghDetailVo.getAccountId())) {
                ghDetail.setGhId(ghDetailVo.getAccountId().trim());
            }
            if (StringUtils.isNotEmpty(ghDetailVo.getAccountName())) {
                ghDetail.setGhName(ghDetailVo.getAccountName());
            }
            ghDetail.setGhId(ghDetailVo.getAccountId());
            ghDetail.setGhName(ghDetailVo.getAccountName());
            if (!CollectionUtils.isEmpty(ghDetailVo.getVideoIds())) {
                ghDetail.setVideoIds(JSONObject.toJSONString(ghDetailVo.getVideoIds()));
            }
            if (StringUtils.isEmpty(ghDetail.getContentDetail())) {
                ghDetail.setContentDetail(null);
            }
            ghDetailMapper.insertSelective(ghDetail);
            ghDetailMapperExt.deleteOldGhDetailExt(ghDetailVo.getAccountId(), ghDetailVo.getType());
            batchSaveGhDetailExt(ghDetailVo, videoIdTestIdMap);
            new Thread(() -> aigcApiService.refreshGzhAutoReplyMsgData(ghDetailVo.getAccountId())).start();
            return CommonResponse.success();
        } catch (Exception e) {
            log.error("addGhDetail error", e);
        }
        return CommonResponse.create(500, "插入失败");
    }

    private void batchSaveGhDetailExt(GhDetailVo ghDetailVo, Map<Long, String> videoIdTestIdMap) {
        if (CollectionUtils.isEmpty(ghDetailVo.getVideoList())) {
            return;
        }
        GhDetail ghDetail = getGhDetailByGhIdType(ghDetailVo.getAccountId(), ghDetailVo.getType());
        if (ghDetail == null) {
            return;
        }
        List<GhDetailExt> ghDetailExts = new ArrayList<>();
        for (GhDetailVo.VideoDetail videoDetail : ghDetailVo.getVideoList()) {
            GhDetailExt ghDetailExt = new GhDetailExt();
            ghDetailExt.setGhDetailId(ghDetail.getId());
            ghDetailExt.setVideoId(videoDetail.getVideoId());
            ghDetailExt.setPage(getVideoPageUrl(videoDetail.getVideoId(), ghDetailVo.getChannel(),
                    ghDetailVo.getAccountId(), videoDetail.getSort(), ghDetailVo.getType(), videoIdTestIdMap.get(videoDetail.getVideoId())));
            setCustomTitle(ghDetailExt, videoDetail);
            setCustomCover(ghDetailExt, videoDetail);
            ghDetailExt.setSort(videoDetail.getSort());
            ghDetailExt.setIsDelete(0);
            ghDetailExts.add(ghDetailExt);
        }
        ghDetailMapperExt.batchInsertGhDetailExt(ghDetailExts);
    }

    private void setCustomTitle(GhDetailExt ghDetailExt, GhDetailVo.VideoDetail videoDetail) {
        if (StringUtils.isNotEmpty(videoDetail.getTitle())) {
            boolean titleExist = false;
            List<VideoGrowthMultiTitle> list = videoMultiService.getMultiTitleByVideoId(videoDetail.getVideoId());
            for (VideoGrowthMultiTitle multiTitle : list) {
                if (multiTitle.getTitle().equals(videoDetail.getTitle())) {
                    ghDetailExt.setTitleId(multiTitle.getId());
                    titleExist = true;
                    break;
                }
            }
            if (!titleExist) {
                JSONArray multiTitleList = managerApiService.videoMultiTitleListV2(videoDetail.getVideoId());
                String source = "自定义";
                if (!CollectionUtils.isEmpty(multiTitleList)) {
                    for (int i = 0; i < multiTitleList.size(); i++) {
                        JSONObject item = multiTitleList.getJSONObject(i);
                        if (item.getString("title").equals(videoDetail.getTitle())) {
                            if (item.getInteger("source") == 0) {
                                source = "原始";
                                break;
                            }
                        }
                    }
                }
                Long titleId = videoMultiService.saveMultiTitle(videoDetail.getVideoId(), source, videoDetail.getTitle());
                ghDetailExt.setTitleId(titleId);
            }
            ghDetailExt.setTitle(videoDetail.getTitle());
        }
    }

    private void setCustomCover(GhDetailExt ghDetailExt, GhDetailVo.VideoDetail videoDetail) {
        if (StringUtils.isNotEmpty(videoDetail.getCover())) {
            boolean customCoverExist = false;
            List<VideoGrowthMultiCover> list = videoMultiService.getMultiCoverByVideoId(videoDetail.getVideoId());
            for (VideoGrowthMultiCover multiCover : list) {
                if (multiCover.getCover().equals(videoDetail.getCover())) {
                    ghDetailExt.setCoverId(multiCover.getId());
                    customCoverExist = true;
                    break;
                }
            }
            if (!customCoverExist) {
                JSONArray multiCoverList = managerApiService.videoMultiCoverListV2(videoDetail.getVideoId());
                String source = "自定义";
                if (!CollectionUtils.isEmpty(multiCoverList)) {
                    for (int i = 0; i < multiCoverList.size(); i++) {
                        JSONObject item = multiCoverList.getJSONObject(i);
                        if (item.getString("coverUrl").equals(videoDetail.getCover())) {
                            if (item.getInteger("source") == 0) {
                                source = "原始";
                                break;
                            }
                        }
                    }
                }
                Long coverId = videoMultiService.saveMultiCover(videoDetail.getVideoId(), source, videoDetail.getCover());
                ghDetailExt.setCoverId(coverId);
            }
            ghDetailExt.setCover(videoDetail.getCover());
        }
    }

    private String getVideoPageUrl(Long videoId, String channel, String ghId, Integer sort, Integer accountType, String experimentId) {
        // 查询库里是否存在，如果存在即复用
        try {
            CgiReplyBucketDataExample cgiReplyBucketDataExample = new CgiReplyBucketDataExample();
            cgiReplyBucketDataExample.createCriteria().andIsDeleteEqualTo(0).andMiniVideoIdEqualTo(videoId).andGhIdEqualTo(ghId);
            List<CgiReplyBucketData> cgiReplyBucketData = cgiReplyBucketDataMapper.selectByExample(cgiReplyBucketDataExample);
            if (!CollectionUtils.isEmpty(cgiReplyBucketData)) {
                return cgiReplyBucketData.get(0).getMiniPagePath().toString();
            }
            String response;
            if (accountType.equals(GhTypeEnum.GH.type)) {
                String putScene = "touliu";
                channel = "tencentgzh";
                JSONObject rootSourceConfigs = JSON.parseObject(rootSourceConfig);
                JSONObject jsonObject1 = rootSourceConfigs.getJSONObject(ghId);
                if (jsonObject1 != null) {
                    if (StringUtils.isNotEmpty(jsonObject1.getString("putScene"))) {
                        putScene = jsonObject1.getString("putScene");
                    }
                    if (StringUtils.isNotEmpty(jsonObject1.getString("channel"))) {
                        channel = jsonObject1.getString("channel");
                    }
                }
                response = touLiuHttpClient.sendAdFlowAddRequest(GET_SMALL_PAGE_URL, String.valueOf(videoId), putScene,
                        channel, "自动", "公众号", "自动回复小程序", "位置" + sort, ghId, experimentId);
            } else {
                response = touLiuHttpClient.sendAdFlowAddRequest(GET_SMALL_PAGE_URL, String.valueOf(videoId), "dyyjs",
                        channel, "自动", "公众号", "自动回复小程序", "位置" + sort, ghId, experimentId);
            }
            JSONObject jsonObject = JSON.parseObject(response);
            if (jsonObject != null && jsonObject.containsKey("data")) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null && data.containsKey("url")) {
                    return data.getString("url");
                }
            }
        } catch (Exception e) {
            log.error("getVideoPageUrl error", e);
        }
        return null;
    }

    @Override
    public CommonResponse<Void> updateDetail(GhDetailVo ghDetailVo, Map<Long, String> videoIdTestIdMap) {
        if (ghDetailVo == null || ghDetailVo.getId() == null) {
            return CommonResponse.create(500, "参数错误");
        }
        CommonResponse<Void> checkParamRes = checkParam(ghDetailVo);
        if (checkParamRes != null) {
            return checkParamRes;
        }
        try {
            GhDetail ghDetail = new GhDetail();
            BeanUtils.copyProperties(ghDetailVo, ghDetail);
            if (StringUtils.isNotEmpty(ghDetailVo.getAccountId())) {
                ghDetail.setGhId(ghDetailVo.getAccountId().trim());
            }
            if (StringUtils.isNotEmpty(ghDetailVo.getAccountName())) {
                ghDetail.setGhName(ghDetailVo.getAccountName());
            }
            if (StringUtils.isEmpty(ghDetail.getContentDetail())) {
                ghDetail.setContentDetail(null);
            }
            ghDetail.setGhId(ghDetailVo.getAccountId());
            ghDetail.setGhName(ghDetailVo.getAccountName());
            ghDetail.setVideoIds(JSONObject.toJSONString(ghDetailVo.getVideoIds()));
            ghDetailMapper.updateByPrimaryKeySelective(ghDetail);
            ghDetailMapperExt.deleteOldGhDetailExt(ghDetailVo.getAccountId(), ghDetailVo.getType());
            batchSaveGhDetailExt(ghDetailVo, videoIdTestIdMap);

            if (StringUtils.isEmpty(ghDetail.getContentDetail()) || StringUtils.isEmpty(ghDetail.getRate())) {
                GhDetail updateGhDetail = ghDetailMapper.selectByPrimaryKey(ghDetail.getId());
                if (StringUtils.isEmpty(ghDetail.getContentDetail())) {
                    updateGhDetail.setContentDetail(null);
                }
                if (StringUtils.isEmpty(ghDetail.getRate())) {
                    updateGhDetail.setRate(null);
                }
                updateGhDetail.setUpdateTime(new Date());
                ghDetailMapper.updateByPrimaryKey(updateGhDetail);
            }
            new Thread(() -> aigcApiService.refreshGzhAutoReplyMsgData(ghDetailVo.getAccountId())).start();
            return CommonResponse.success();
        } catch (Exception e) {
            log.error("updateDetail error", e);
        }
        return CommonResponse.create(500, "修改失败");
    }


    @Override
    public CommonResponse<Void> deleteDetail(Long id) {
        GhDetail ghDetail = new GhDetail();
        ghDetail.setId(id);
        ghDetail.setIsDelete(1);
        ghDetailMapper.updateByPrimaryKeySelective(ghDetail);
        return CommonResponse.success();
    }

    private CommonResponse<Void> checkParam(GhDetailVo ghDetailVo) {
        if (Objects.equals(ghDetailVo.getType(), GhTypeEnum.THIRD_PARTY_GH.type)) {
            if (StringUtils.isEmpty(ghDetailVo.getChannel())) {
                return CommonResponse.create(500, "渠道不能为空");
            }
        }
        if (StringUtils.isNotEmpty(ghDetailVo.getRate())) {
            if (!JSONArray.isValidArray(ghDetailVo.getRate())) {
                return CommonResponse.create(500, "保底比率格式错误");
            }
            List<Integer> list = JSONArray.parseArray(ghDetailVo.getRate(), Integer.class);
            if (!CollectionUtils.isEmpty(list)) {
                for (Integer i : list) {
                    if (i < 0 || i > 9) {
                        return CommonResponse.create(500, "保底比率需要再0-9之间");
                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(ghDetailVo.getVideoList())) {
            for (GhDetailVo.VideoDetail videoDetail : ghDetailVo.getVideoList()) {
                if (StringUtils.isEmpty(videoDetail.getTitle())) {
                    return CommonResponse.create(500, "视频标题不能为空");
                }
                if (StringUtils.isEmpty(videoDetail.getCover())) {
                    return CommonResponse.create(500, "视频封面不能为空");
                }
            }
        }

        if (StringUtils.isNotEmpty(ghDetailVo.getContentDetail())) {
            ghDetailVo.setContentDetail(ghDetailVo.getContentDetail().trim());
            if (!JSONObject.isValidObject(ghDetailVo.getContentDetail())) {
                return CommonResponse.create(500, "文章内容格式错误");
            }
            JSONObject contentDetail = JSONObject.parseObject(ghDetailVo.getContentDetail());
            if (StringUtils.isEmpty(contentDetail.getString("coverUrl"))) {
                return CommonResponse.create(500, "文章封面信息错误");
            }
            if (StringUtils.isEmpty(contentDetail.getString("newsDescription"))) {
                return CommonResponse.create(500, "文章内容错误");
            }
            if (StringUtils.isEmpty(contentDetail.getString("newsUrl"))) {
                return CommonResponse.create(500, "文章路径错误");
            }
            if (StringUtils.isEmpty(contentDetail.getString("title"))) {
                return CommonResponse.create(500, "文章标题错误");
            }
        }
        return null;
    }

    @Override
    public GhDetail getGhDetailByGhIdType(String ghId, Integer type) {
        GhDetailExample example = new GhDetailExample();
        example.createCriteria().andGhIdEqualTo(ghId).andTypeEqualTo(type).andIsDeleteEqualTo(0);
        List<GhDetail> ghDetails = ghDetailMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(ghDetails)) {
            return ghDetails.get(0);
        }
        return null;
    }

    @Override
    public GhDetail getGhDetailByGhId(String ghId) {
        GhDetailExample example = new GhDetailExample();
        example.createCriteria().andGhIdEqualTo(ghId).andIsDeleteEqualTo(0);
        example.setOrderByClause("id desc");
        List<GhDetail> ghDetails = ghDetailMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(ghDetails)) {
            return ghDetails.get(0);
        }
        return null;
    }

    @Override
    public List<GhDetail> getByChannel(String channel) {
        GhDetailExample ghDetailExample = new GhDetailExample();
        ghDetailExample.createCriteria().andChannelEqualTo(channel).andIsDeleteEqualTo(0);
        return ghDetailMapper.selectByExample(ghDetailExample);
    }

    @Override
    public List<GhDetail> getGhdetailByNames(List<String> nameList) {
        GhDetailExample ghDetailExample = new GhDetailExample();
        ghDetailExample.createCriteria().andGhNameIn(nameList).andIsDeleteEqualTo(0);
        return ghDetailMapper.selectByExample(ghDetailExample);
    }

    @Override
    public List<GhDetailExt> getGhDetailExtList(String ghId, Integer type) {
        return ghDetailMapperExt.getGhDetailExtList(ghId, type);
    }


}
