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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.tzld.piaoquan.api.common.enums.ReplyStrategyServiceEnum;
import com.tzld.piaoquan.api.dao.mapper.GzhAutoreplyBehaviorUvTotalMapper;
import com.tzld.piaoquan.api.model.bo.*;
import com.tzld.piaoquan.api.model.po.GzhAutoreplyBehaviorUvTotal;
import com.tzld.piaoquan.api.model.po.GzhAutoreplyBehaviorUvTotalExample;
import com.tzld.piaoquan.api.model.po.contentplatform.ContentPlatformAccount;
import com.tzld.piaoquan.api.model.param.PushMessageParam;
import com.tzld.piaoquan.api.model.vo.PushMessageVo;
import com.tzld.piaoquan.api.model.vo.ReportUvVo;
import com.tzld.piaoquan.api.service.GhAccessTokenService;
import com.tzld.piaoquan.api.service.strategy.ReplyStrategyService;
import com.tzld.piaoquan.api.service.wecom.ThirdPartyService;
import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
import com.tzld.piaoquan.growth.common.common.constant.TimeConstant;
import com.tzld.piaoquan.growth.common.common.enums.ExceptionCodeEnum;
import com.tzld.piaoquan.growth.common.common.enums.GhTypeEnum;
import com.tzld.piaoquan.growth.common.component.ODPSManager;
import com.tzld.piaoquan.growth.common.dao.mapper.GhDetailMapper;
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 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.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class ThirdPartyServiceImpl implements ThirdPartyService {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private GhAccessTokenService ghAccessTokenService;

    @Autowired
    private ODPSManager odpsManager;

    @Autowired
    private GhDetailMapper ghDetailMapper;

    @Autowired
    private GzhAutoreplyBehaviorUvTotalMapper gzhAutoreplyBehaviorUvTotalMapper;

    private static final String canViewReportDate = "2024-10-31";

    private Map<String, ReplyStrategyService> strategyServiceMap;

    @PostConstruct
    public void init() {
        strategyServiceMap = applicationContext.getBeansOfType(ReplyStrategyService.class);
    }


    @Override
    public CommonResponse<List<PushMessageVo>> getPushMessage(PushMessageParam param) {
        if (param == null || StringUtils.isEmpty(param.getGhId()) || StringUtils.isEmpty(param.getAccessToken())) {
            return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "参数错误");
        }
        if (!ghAccessTokenService.validateAccessToken(param.getAccessToken())) {
            return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "accessToken错误或者已失效");
        }
        ContentPlatformAccount account = ghAccessTokenService.getAccountByAccessToken(param.getAccessToken());
        if (account == null) {
            return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "获取secret失败");
        }
        log.info("getPushMessage param={} secretEnum desc={}", param, account.getName());
        GhDetailExample example = new GhDetailExample();
        example.createCriteria().andTypeEqualTo(GhTypeEnum.THIRD_PARTY_GH.type).andGhIdEqualTo(param.getGhId())
                .andIsDeleteEqualTo(0);
        List<GhDetail> ghDetails = ghDetailMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(ghDetails)) {
            return CommonResponse.create(404, "ghId不存在，请联系管理员配置");
        }
        GhDetail ghDetail = ghDetails.get(0);
        String channel = ghDetail.getChannel();
        if (channel == null) {
            LarkRobotUtil.sendMessage("channel不存在，请查看详情 ghId=" + param.getGhId());
            return CommonResponse.create(404, "ghId异常，请联系管理员检查");
        }
        if (!Objects.equals(account.getChannel(), channel)) {
//            LarkRobotUtil.sendMessage(String.format("channel异常 secretEnum.channel=%s ghDetail.channel=%s ghId=%s",
//                    secretEnum.channel, channel, param.getGhId()));
            return CommonResponse.create(404, "ghId异常，请联系管理员检查");
        }
        List<PushMessageVo> pushMessageVoList = new ArrayList<>();
        ReplyBucketData replyBucketData = getPushMessageData(ghDetail);
        log.info("replyBucketData={}", JSON.toJSONString(replyBucketData));
        if (replyBucketData == null) {
            log.error("获取推送策略数据失败");
            return CommonResponse.create(500, "系统异常，获取失败");
        }
        List<GroupData> groupList = replyBucketData.getGroupList();
        for (GroupData groupData : groupList) {
            if (CollectionUtils.isEmpty(groupData.getMsgDataList())) {
                continue;
            }
            PushMessageVo pushMessageVo = new PushMessageVo();
            List<MiniData> components = new ArrayList<>();
            for (MsgData msgData : groupData.getMsgDataList()) {
                MiniData miniData = new MiniData();
                BeanUtils.copyProperties(msgData, miniData);
                components.add(miniData);
                if (StringUtils.isBlank(miniData.getTitle())) {
                    return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "视频不可用，请更换视频后重试");
                }
            }
            pushMessageVo.setGroupIdx(groupData.getGroupIndex());
            pushMessageVo.setComponents(components);
            pushMessageVoList.add(pushMessageVo);
        }
        return CommonResponse.success(pushMessageVoList);
    }

    @Override
    public CommonResponse<List<ReportUvVo>> getReportUv(String date, String accessToken) {
        if (StringUtils.isEmpty(date) || !DateUtil.isValidDate(date) || StringUtils.isEmpty(accessToken)) {
            return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "参数错误");
        }
        if (!ghAccessTokenService.validateAccessToken(accessToken)) {
            return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "accessToken错误或者已失效");
        }
        ContentPlatformAccount account = ghAccessTokenService.getAccountByAccessToken(accessToken);
        if (account == null) {
            return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "获取secret失败");
        }
        if (!DateUtil.isValidDate(canViewReportDate)) {
            return CommonResponse.create(ExceptionCodeEnum.PARAMS_ERROR, "系统异常");
        }
        //10点后可查询前一天数据
        long nowTimestamp = System.currentTimeMillis() / 1000;
        long limitTime = nowTimestamp - 34L * TimeConstant.HOUR;
        long targetTime = DateUtil.dateStrToTimestamp(date, "yyyy-MM-dd");
        String desc = account.getName();
        if (targetTime > limitTime) {
            return CommonResponse.create(500, "数据不存在");
        }
        List<ReportUvVo> res = new ArrayList<>();
        String dt = date.replace("-", "").substring(0, 8);
        GzhAutoreplyBehaviorUvTotalExample example = new GzhAutoreplyBehaviorUvTotalExample();
        example.createCriteria().andDtEqualTo(dt).andChannelEqualTo(desc);
        List<GzhAutoreplyBehaviorUvTotal> list = gzhAutoreplyBehaviorUvTotalMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return CommonResponse.success(res);
        }
        for (GzhAutoreplyBehaviorUvTotal record : list) {
            ReportUvVo reportUvVo = new ReportUvVo();
            reportUvVo.setGhId(record.getGhId());
            reportUvVo.setUv(Long.valueOf(record.getFirstLevel()));
            res.add(reportUvVo);
        }
        return CommonResponse.success(res);
    }

    private ReplyBucketData getPushMessageData(GhDetail ghDetail) {
        log.info("strategyServiceMap={}", JSON.toJSONString(strategyServiceMap));
        for (Map.Entry<String, ReplyStrategyService> stringReplyStrategyServiceEntry : strategyServiceMap.entrySet()) {
            ReplyStrategyService replyStrategyService = stringReplyStrategyServiceEntry.getValue();
            // 使用策略层
            if (replyStrategyService.support(ReplyStrategyServiceEnum.THIRD_PARTY_PUSH_MESSAGE_STRATEGY_V1)) {
                BucketDataParam bucketDataParam = new BucketDataParam();
                bucketDataParam.setGhId(ghDetail.getGhId());
                bucketDataParam.setAccountName(ghDetail.getGhName());
                bucketDataParam.setChannel(ghDetail.getChannel());
                bucketDataParam.setStrategyStatus(ghDetail.getStrategyStatus());
                if (StringUtils.isNotEmpty(ghDetail.getVideoIds())) {
                    bucketDataParam.setVideos(JSONArray.parseArray(ghDetail.getVideoIds(), Long.class));
                }
                return replyStrategyService.getResult(bucketDataParam);
            }
        }
        // 无执行策略 不会走到这里
        return null;
    }

    public static long dateStrToTimestamp(String dateStr, String format) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);

        // 解析输入的日期字符串为LocalDate对象
        LocalDate date = LocalDate.parse(dateStr, formatter);

        // 将LocalDate转换为LocalDateTime，时间部分设为00:00:00
        LocalDateTime dateTime = date.atStartOfDay();

        // 定义北京时区
        ZoneId zone = ZoneId.of("Asia/Shanghai");

        // 将LocalDateTime转换为时间戳（秒数），使用北京时区
        return dateTime.toEpochSecond(zone.getRules().getOffset(dateTime));
    }
}
