package com.tzld.piaoquan.api.component;

import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.common.exception.CommonException;
import com.tzld.piaoquan.api.model.bo.GoogleLLMResult;
import com.tzld.piaoquan.api.model.vo.WxAccountDatastatVO;
import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
import com.tzld.piaoquan.growth.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class AigcApiService {

    @Autowired
    private HttpPoolClient httpPoolClient;

    @Value("${aigc.api.host:http://aigc-testapi.cybertogether.net/aigc}")
    private String aigcApiHost;

    @Value("${aigc.prod.api.host:http://aigc-api.cybertogether.net/aigc}")
    private String aigcProdApiHost;

    @Value("${aigc.api.token:9ebfcb397e954c41986971f183eb1707}")
    private String aigcApiToken;

    @Value("${spring.profiles.active:dev}")
    private String env;

    private String getAigcPostParam(JSONObject params) {
        JSONObject baseInfo = JSONObject.parseObject("{\n" +
                "    \"token\": \"" + aigcApiToken + "\",\n" +
                "    \"appType\": 9,\n" +
                "    \"platform\": \"pc\",\n" +
                "    \"appVersionCode\": 1000,\n" +
                "    \"clientTimestamp\": 1,\n" +
                "    \"fid\": 1,\n" +
                "    \"loginUid\": 1,\n" +
                "    \"pageSource\": 1,\n" +
                "    \"requestId\": 1,\n" +
                "    \"rid\": 1,\n" +
                "    \"uid\": 1\n" +
                "}");
        JSONObject param = new JSONObject();
        param.put("params", params);
        param.put("baseInfo", baseInfo);
        return param.toJSONString();
    }

    public String generateQrcode(String uuid) {
        String url = aigcApiHost + "/publish/account/generateQrcode";
        JSONObject params = new JSONObject();
        params.put("uuid", uuid);
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            JSONObject res = JSONObject.parseObject(post);
            JSONObject data = res.getJSONObject("data");
            return data.getString("qrcodeStr");
        } catch (Exception e) {
            log.error("generateQrcode error", e);
        }
        return null;
    }

    public String getAuthResult(String uuid) {
        String url = aigcApiHost + "/publish/account/authResult";
        JSONObject params = new JSONObject();
        params.put("uuid", uuid);
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            JSONObject res = JSONObject.parseObject(post);
            if (Objects.isNull(res) || res.getInteger("code") != 0) {
                return null;
            }
            JSONObject data = res.getJSONObject("data");
            return data.getString("id");
        } catch (Exception e) {
            log.error("getAuthResult error", e);
        }
        return null;
    }

    public JSONObject getAccountDetail(String publishAccountId) {
        String url = aigcApiHost + "/publish/account/detail";
        JSONObject params = new JSONObject();
        params.put("id", publishAccountId);
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            JSONObject res = JSONObject.parseObject(post);
            return res.getJSONObject("data");
        } catch (Exception e) {
            log.error("getAccountDetail error", e);
        }
        return null;
    }

    public String getDetailByGhId(String ghId) {
        String url = aigcApiHost + "/publish/account/getDetailByGhId";
        JSONObject params = new JSONObject();
        params.put("id", ghId);
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            JSONObject res = JSONObject.parseObject(post);
            JSONObject data = res.getJSONObject("data");
            if (Objects.nonNull(data)) {
                return data.getString("id");
            }
        } catch (Exception e) {
            log.error("getDetailByGhId error", e);
        }
        return null;
    }

    public String createPublishPlan(String publishAccountId, String name, String channel) {
        String url = aigcApiHost + "/publish/plan/save";
        JSONObject params = getPublishPlanAddParam(publishAccountId, name, channel);
        JSONObject res = null;
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("createPublishPlan error", e);
        }
        if (Objects.isNull(res)) {
            throw new CommonException(3000, "创建计划失败，请稍后重试");
        }
        Integer code = res.getInteger("code");
        if (code != 0) {
            throw new CommonException(3000, res.getString("msg"));
        }
        JSONObject data = res.getJSONObject("data");
        return data.getString("id");
    }

    private JSONObject getPublishPlanAddParam(String publishAccountId, String name, String channel) {
        String dateStr = DateUtil.getCurrentDateStr("yyyyMMdd");
        JSONObject params = JSONObject.parseObject("{\n" +
                "    \"accountIds\": [\n" +
                "        \"" + publishAccountId + "\"\n" +
                "    ],\n" +
                "    \"activeManualReview\": 0,\n" +
                "    \"channel\": 5,\n" +
                "    \"contentAllocationRules\": 0,\n" +
                "    \"contentModal\": 7,\n" +
                "    \"douyinPublishAccoutSetting\": [],\n" +
                "    \"filterMatchMode\": 1,\n" +
                "    \"name\": \"自动回复-" + dateStr + "-" + name + "-" + channel + "\",\n" +
                "    \"publishAccoutJson\": \"\",\n" +
                "    \"publishBgmType\": 0,\n" +
                "    \"publishDate\": \"\",\n" +
                "    \"publishLocation\": [],\n" +
                "    \"publishNum\": \"\",\n" +
                "    \"publishPushTime\": \"\",\n" +
                "    \"publishRate\": 0,\n" +
                "    \"publishTimeInterval\": 240,\n" +
                "    \"wxContentInsert\": [\n" +
                "        {\n" +
                "            \"accountId\": \"" + publishAccountId + "\",\n" +
                "            \"name\": \"" + name + "\",\n" +
                "            \"bottomInsertFlag\": 0,\n" +
                "            \"topInsertFlag\": 0,\n" +
                "            \"miniprogramInsertFlag\": 0,\n" +
                "            \"gzhArticleSortFlag\": 0,\n" +
                "            \"publishOpenFlag\": 1\n" +
                "        }\n" +
                "    ],\n" +
                "    \"wxVideoPublishAccountSetting\": [],\n" +
                "    \"scoreJudgeFlag\": 0,\n" +
                "    \"scoreJudgeTasks\": [],\n" +
                "    \"inputGroups\": [],\n" +
                "    \"machineReviewMatchMode\": 1,\n" +
                "    \"gzhOnlyMiniprogramFlag\": 0,\n" +
                "    \"planType\": 1,\n" +
                "    \"pushType\": 6,\n" +
                "    \"inputFilters\": [],\n" +
                "    \"inputSources\": [],\n" +
                "    \"triggerEvent\": 1,\n" +
                "    \"gzhTriggerSyncFrequency\": 1,\n" +
                "    \"gzhTriggerSendContentType\": 1,\n" +
                "    \"gzhAutoReplyDelayFlag\": 1,\n" +
                "    \"gzhAutoReplyDelayMillisecond\": 1000,\n" +
                "    \"pushContentSortingRules\": 1\n" +
                "}");
        return params;
    }

    public void changePublishPlanStatus(String externalId, Integer status) {
        String url = aigcApiHost + "/publish/plan/updatePlanStatus";
        JSONObject params = new JSONObject();
        params.put("id", externalId);
        params.put("status", status);
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            JSONObject res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("changePublishPlanStatus error", e);
        }
    }

    public void changePublishPlanAccountStatus(String planId, String accountId, Integer status) {
        String url = aigcApiHost + "/publish/plan/updatePlanAccountStatus";
        JSONObject params = new JSONObject();
        params.put("planId", planId);
        params.put("accountId", accountId);
        params.put("status", status);
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            JSONObject res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("changePublishPlanAccountStatus error", e);
        }
    }

    public void refreshGzhAutoReplyMsgData(String ghId) {
        if (!"prod".equals(env)) {
            return;
        }
        String url = aigcApiHost + "/publish/api/refreshGzhAutoReplyMsgData?ghId=" + ghId;
        try {
            httpPoolClient.get(url);
        } catch (Exception e) {
            log.error("refreshGzhAutoReplyMsgData error", e);
        }
    }

    public List<WxAccountDatastatVO> getWxAccountDatastat(String dateStr, List<String> accountIds) {
        String url = aigcApiHost + "/dataStat/getWxAccountDatastat";
        JSONObject params = new JSONObject();
        params.put("dateStr", dateStr);
        params.put("accountIds", accountIds);
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            JSONObject res = JSONObject.parseObject(post);
            return res.getJSONArray("data").toJavaList(WxAccountDatastatVO.class);
        } catch (Exception e) {
            log.error("getWxAccountDatastat error", e);
        }
        return null;
    }

    public void closeAccountMessagePublishPlan(String publishAccountId) {
        String url = aigcApiHost + "/publish/plan/closeAccountMessagePublishPlan";
        JSONObject params = new JSONObject();
        params.put("id", publishAccountId);
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            JSONObject res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("closeAccountMessagePublishPlan error", e);
        }
    }

    public boolean checkContainMessagePlan(String publishAccountId) {
        String url = aigcApiHost + "/publish/plan/list";
        JSONObject params = JSONObject.parseObject("{\n" +
                "    \"filterItems\": [\n" +
                "        {\n" +
                "            \"itemName\": \"planType\",\n" +
                "            \"selectValues\": [\n" +
                "                1\n" +
                "            ]\n" +
                "        },\n" +
                "        {\n" +
                "            \"itemName\": \"publishAccounts\",\n" +
                "            \"selectValues\": [\n" +
                "                \"" + publishAccountId + "\"\n" +
                "            ]\n" +
                "        },\n" +
                "        {\n" +
                "            \"itemName\": \"planStatus\",\n" +
                "            \"selectValues\": [\n" +
                "                1\n" +
                "            ]\n" +
                "        }\n" +
                "    ],\n" +
                "    \"listFieldFormula\": [],\n" +
                "    \"pageNum\": 1,\n" +
                "    \"pageSize\": 50,\n" +
                "    \"channel\": 5,\n" +
                "    \"contentModal\": 7\n" +
                "}");
        try {
            String post = httpPoolClient.post(url, getAigcPostParam(params));
            JSONObject res = JSONObject.parseObject(post);
            Integer totalCount = res.getJSONObject("data").getInteger("totalCount");
            return totalCount > 0;
        } catch (Exception e) {
            log.error("closeAccountMessagePublishPlan error", e);
        }
        return false;
    }

    public String gpt(String model, String prompt, JSONObject responseFormat, List<String> imageList) {
        if (StringUtils.isEmpty(model) || StringUtils.isEmpty(prompt)) {
            return null;
        }
        String url = aigcProdApiHost + "/dev/test/gpt";
        JSONObject params = new JSONObject();
        params.put("model", model);
        params.put("prompt", prompt);
        if (Objects.nonNull(responseFormat)) {
            params.put("responseFormat", responseFormat);
        }
        if (CollectionUtils.isNotEmpty(imageList)) {
            params.put("imageList", imageList);
        }

        try {
            String post = httpPoolClient.post(url, params.toJSONString());
            JSONObject res = JSONObject.parseObject(post);
            return res.getString("data");
        } catch (Exception e) {
            log.error("gpt error", e);
        }
        return null;
    }

    public GoogleLLMResult gemini(String model, String prompt, List<String> imageList) {
        if (StringUtils.isEmpty(model) || StringUtils.isEmpty(prompt)) {
            return null;
        }
        String url = aigcProdApiHost + "/infrastructure/gemini/requestWithMedia?model=" + model;
        JSONObject params = new JSONObject();
        params.put("prompt", prompt);
        if (CollectionUtils.isNotEmpty(imageList)) {
            params.put("mediaList", imageList);
        }

        try {
            String post = httpPoolClient.post(url, params.toJSONString());
            return JSONObject.parseObject(post, GoogleLLMResult.class);
        } catch (Exception e) {
            log.error("gemini error", e);
        }
        return null;
    }


    public String getCreativeIdByRootSourceIdAndGhId(String rootSourceId, String ghId) {
        try {
            String url = aigcApiHost + "/publish/content/replyMsg/getCreativeIdByRootSourceIdAndGhId?ghId=" + ghId + "&rootSourceId=" + rootSourceId;
            String response = httpPoolClient.get(url);
            JSONObject res = JSONObject.parseObject(response);
            if (res.getInteger("code") == 0 && res.getString("data") != null) {
                return res.getString("data");
            }
        } catch (Exception e) {
            log.error("获取创意ID失败, rootSourceId={}, ghId={}", rootSourceId, ghId, e);
        }
        return null;
    }

    /**
     * 根据ghId获取账号分组来源名称
     * 用于判断公众号是"买号"还是"代运营"
     * @param ghId 公众号ID
     * @return 账号分组来源名称，如"公众号买号"、"公众号代运营"等，失败返回null
     */
    public String getAccountGroupSourceName(String ghId) {
        try {
            String url = "http://aigc-api.cybertogether.net/aigc/dataStatGroup/getAccountGroupSourceName?ghId=" + ghId;
            String response = httpPoolClient.get(url);
            JSONObject res = JSONObject.parseObject(response);
            if (res != null && res.getInteger("code") == 0) {
                return res.getString("data");
            }
        } catch (Exception e) {
            log.error("获取账号分组来源名称失败, ghId={}", ghId, e);
        }
        return null;
    }
}
