package com.tzld.piaoquan.offline.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tzld.piaoquan.growth.common.common.enums.FieshuTableColumnDataTypeEnum;
import com.tzld.piaoquan.growth.common.common.enums.GhTypeEnum;
import com.tzld.piaoquan.growth.common.common.enums.StrategyStatusEnum;
import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
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.bo.FeishuTableDTO;
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.LarkRobotUtil;
import com.tzld.piaoquan.growth.common.utils.MessageUtil;
import com.tzld.piaoquan.growth.common.utils.page.Page;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

@Slf4j
@Component
public class AutoReplyVideoDataJob {

    private static final List<String> auditGhIds = new ArrayList<String>() {{
        add("gh_b63b9dde3f4b");
        add("gh_330ef0db846d");
        add("gh_330ef0db846d");
        add("gh_e2318164f869");
        add("gh_620af8e24fb9");
        add("gh_620af8e24fb9");
        add("gh_133c36b99b14");
        add("gh_133c36b99b14");
        add("gh_5ac72e2b9130");
        add("gh_ef8ade0fad92");
        add("gh_1e03b6de22bf");
        add("gh_5538fe297e59");
        add("gh_8c6fffcbaac1");
        add("gh_8c6fffcbaac1");
        add("gh_d0e830b7547e");
        add("gh_fb234f4e32a5");
        add("gh_84c5d01a61e7");
        add("gh_87c4b8ae885e");
        add("gh_29d8a63d5e5e");
        add("gh_b144210318e5");
        add("gh_b144210318e5");
        add("gh_1f9bf4cfa788");
        add("gh_4f47d12bbe04");
        add("gh_8c6af276df98");
        add("gh_1f16bc6ac60d");
        add("gh_4920bc4c5720");
        add("gh_5177a8c57917");
        add("gh_5177a8c57917");
        add("gh_5e3e6cd5e35c");
        add("gh_5e3e6cd5e35c");
        add("gh_d2c72bcc05c9");
        add("gh_d2c72bcc05c9");
        add("gh_5f2400da935c");
        add("gh_5f2400da935c");
        add("gh_669555ebea28");
        add("gh_28ce883486c3");
        add("gh_28ce883486c3");
        add("gh_7057ef30222b");
        add("gh_7057ef30222b");
        add("gh_b0048adc0b46");
        add("gh_6e61a2d5db85");
        add("gh_01cd19465b39");
        add("gh_01cd19465b39");
        add("gh_126c99b39cea");
        add("gh_4a1174e36ceb");
        add("gh_f81c27eb8c48");
        add("gh_f81c27eb8c48");
        add("gh_3170dc15e246");
        add("gh_1ccfb5620605");
        add("gh_315be76a746d");
        add("gh_4f47d12bbe04");
        add("gh_4f47d12bbe04");
        add("gh_4f47d12bbe04");
    }};

    private static final String VIDEO_DETAIL_URL = "https://longvideoapi.piaoquantv.com/longvideoapi/openapi/video/batchSelectVideoInfo";

    private static final String REFRESH_GZH_URL = "http://aigc-api.cybertogether.net/aigc/publish/api/refreshGzhAutoReplyMsgData";


    @Autowired
    private CgiReplyBucketDataMapper cgiReplyBucketDataMapper;

    @Autowired
    private HttpPoolClient httpPoolClient;

    @Autowired
    private GhDetailMapper ghDetailMapper;


    @XxlJob("validateAutoReplyVideoAuditStatusJob")
    public ReturnT<String> validateAutoReplyVideoAuditStatus(String param) throws IOException {
        Long beforeDayStart = DateUtil.getBeforeDayStart(7);
        List<Long> videoIds = cgiReplyBucketDataMapper.selectVideoId(new Date(beforeDayStart));
        if (CollectionUtils.isEmpty(videoIds)) {
            return ReturnT.SUCCESS;
        }
        List<Long> auditFailedVideoIds = new ArrayList<>();
        List<List<Long>> partition = Lists.partition(videoIds, 20);
        for (List<Long> videoIdList : partition) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("videoIdList", videoIdList);
            String res = httpPoolClient.post(VIDEO_DETAIL_URL, jsonObject.toJSONString());
            if (StringUtils.isEmpty(res)) {
                continue;
            }
            JSONObject result = JSONObject.parseObject(res);
            Integer code = result.getInteger("code");
            if (code != 0) {
                continue;
            }
            JSONArray jsonArray = result.getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject videoDetail = jsonArray.getJSONObject(i);
                Integer auditStatus = videoDetail.getInteger("auditStatus");
                Integer appAuditStatus = videoDetail.getInteger("appAuditStatus");
                if (auditStatus != 5 || appAuditStatus != 5) {
                    auditFailedVideoIds.add(videoDetail.getLong("id"));
                }
            }
        }
        if (CollectionUtils.isEmpty(auditFailedVideoIds)) {
            return ReturnT.SUCCESS;
        }

        List<FeishuTableDTO.Column> columns = buildCheckPublishPlanAccountColumns();
        List<JSONObject> rows = new ArrayList<>();

        for (Long videoId : auditFailedVideoIds) {
            CgiReplyBucketDataExample example = new CgiReplyBucketDataExample();
            example.createCriteria().andMiniVideoIdEqualTo(videoId).andIsDeleteEqualTo(0)
                    .andCreateTimeGreaterThan(new Date(beforeDayStart));
            List<CgiReplyBucketData> cgiReplyBucketDataList = cgiReplyBucketDataMapper.selectByExample(example);
//            List<String> ghIds = new ArrayList<>();
//            List<String> manualGhIds = new ArrayList<>();
            for (CgiReplyBucketData cgiReplyBucketData : cgiReplyBucketDataList) {
                String ghId = cgiReplyBucketData.getGhId();
                GhDetailExample ghDetailExample = new GhDetailExample();
                ghDetailExample.createCriteria().andGhIdEqualTo(ghId);
                List<GhDetail> ghDetails = ghDetailMapper.selectByExample(ghDetailExample);
                if (CollectionUtils.isEmpty(ghDetails)) {
                    continue;
                }
                GhDetail ghDetail = ghDetails.get(0);

//                if (Objects.equals(cgiReplyBucketData.getStrategy(), "manual")) {
//                    ghDetail1.setStrategyStatus(StrategyStatusEnum.STRATEGY.status);
//                    ghDetailMapper.updateByPrimaryKeySelective(ghDetail1);
//                    manualGhIds.add(cgiReplyBucketData.getGhId());
//                }

//                ghIds.add(cgiReplyBucketData.getGhId());
                JSONObject row = new JSONObject();
                row.put("name", ghDetail.getGhName());
                row.put("channel", ghDetail.getChannel());
                row.put("video", videoId);
                row.put("ghId", ghDetail.getGhId());
                rows.add(row);
                try {
                    if (auditGhIds.contains(ghId)) {
                        String url = REFRESH_GZH_URL + "?ghId=" + cgiReplyBucketData.getGhId();
                        String res = httpPoolClient.get(url);
                        log.info("refresh ghId={}, res={}", cgiReplyBucketData.getGhId(), res);
                    }
                } catch (Exception e) {
                    log.error("refresh error", e);
                }

            }
        }

        Map<String, JSONObject> collect = rows.stream()
                .collect(Collectors.toMap(
                        row -> row.getString("ghId") + "-" + row.getString("video"),
                        row -> row,
                        (existing, replacement) -> existing
                ));
        rows = new ArrayList<>(collect.values());


        FeishuTableDTO tableDTO = FeishuTableDTO.createTable("自动回复视频审核失败报警", columns, rows, false);
        JSONObject content = JSONObject.parseObject(JSONObject.toJSONString(tableDTO));
        JSONObject bodyParam = new JSONObject();
        bodyParam.put("msg_type", "interactive");
        bodyParam.put("card", content);
        LarkRobotUtil.sendAutoReplyVideoMessage(bodyParam);
        return ReturnT.SUCCESS;
    }


    private List<FeishuTableDTO.Column> buildCheckPublishPlanAccountColumns() {
        List<FeishuTableDTO.Column> columns = new ArrayList<>();
        FeishuTableDTO.Column nameColumn = FeishuTableDTO.createFeishuColumns(
                FieshuTableColumnDataTypeEnum.TEXT.getType(), "name", "账号名称", null);
        columns.add(nameColumn);
        FeishuTableDTO.Column channelColumn = FeishuTableDTO.createFeishuColumns(
                FieshuTableColumnDataTypeEnum.TEXT.getType(), "channel", "渠道id", null);
        columns.add(channelColumn);
        FeishuTableDTO.Column videoColumn = FeishuTableDTO.createFeishuColumns(
                FieshuTableColumnDataTypeEnum.TEXT.getType(), "video", "审核不通过的视频id", null);
        columns.add(videoColumn);
        FeishuTableDTO.Column ghIdColumn = FeishuTableDTO.createFeishuColumns(
                FieshuTableColumnDataTypeEnum.TEXT.getType(), "ghId", "ghId", null);
        columns.add(ghIdColumn);
        return columns;
    }

    @XxlJob("updateRootSourceIdJob")
    public ReturnT<String> updateRootSourceId(String param) {
        CgiReplyBucketDataExample example = new CgiReplyBucketDataExample();
        example.createCriteria().andRootSourceIdIsNull();
        List<CgiReplyBucketData> cgiReplyBucketData = cgiReplyBucketDataMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(cgiReplyBucketData)) {
            for (CgiReplyBucketData replyBucketData : cgiReplyBucketData) {
                String rootSourceId = MessageUtil.getRootSourceId(replyBucketData.getMiniPagePath());
                if(StringUtils.isEmpty(rootSourceId)){
                    continue;
                }
                CgiReplyBucketData updateReplyBucketData = new CgiReplyBucketData();
                updateReplyBucketData.setId(replyBucketData.getId());
                updateReplyBucketData.setRootSourceId(rootSourceId);
                cgiReplyBucketDataMapper.updateByPrimaryKeySelective(updateReplyBucketData);
            }
        }
        return ReturnT.SUCCESS;
    }


}
