package com.xiang.xservice.application.script.fwd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xiang.xservice.basic.common.req.BaseRequest;
import com.xiang.xservice.basic.utils.HttpUtils;
import com.xiang.xservice.basic.utils.JsonUtils;
import com.xiang.xservice.application.script.fwd.constants.CodeConstants;
import com.xiang.xservice.application.script.fwd.constants.UrlConstants;
import com.xiang.xservice.application.script.fwd.entity.req.ProjectOrderCreateReq;
import com.xiang.xservice.application.script.fwd.entity.resp.http.audience.AudienceMemberInfo;
import com.xiang.xservice.application.script.fwd.entity.resp.http.perform.Perform;
import com.xiang.xservice.application.script.fwd.entity.resp.http.perform.ProjectInfoResp;
import com.xiang.xservice.application.script.fwd.entity.resp.http.perform.ProjectOrderCreateResp;
import com.xiang.xservice.application.script.fwd.entity.resp.http.perform.ProjectsResp;
import com.xiang.xservice.application.script.fwd.entity.resp.http.perform.SeatPlanStatus;
import com.xiang.xservice.application.script.fwd.service.IPerformServiceHttp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

@Service
@Slf4j
@RequiredArgsConstructor
public class PerformServiceHttpServiceImpl implements IPerformServiceHttp {

    @Override
    public ProjectsResp getShowProjectsFromHttp(BaseRequest request) {
        Map<String, String> params = Maps.newHashMap();
        params.put("projectModuleId", "7");
        if (Objects.isNull(request.getCurrent())) {
            params.put("pageNum", String.valueOf(1));
        } else {
            params.put("pageNum", String.valueOf(request.getCurrent()));
        }
        if (Objects.isNull(request.getPageSize())) {
            params.put("pageSize", String.valueOf(10));
        } else {
            params.put("pageSize", String.valueOf(request.getPageSize()));
        }
        String respStr = HttpUtils.doGet(UrlConstants.PROJECTS_URL, buildFWDHeaders(null), params);
        if (StringUtils.isBlank(respStr)) {
            return null;
        }
        log.info("【Http请求】 http请求查询演出列表结果:{}", respStr);
        JSONObject resp = JSON.parseObject(respStr);
        Integer code = (Integer) resp.get("code");
        if (Objects.nonNull(code) && Objects.equals(code, CodeConstants.SUCCESS)) {
            ProjectsResp projectsResp = JSON.parseObject(resp.get("data").toString(), ProjectsResp.class);
            if (Objects.isNull(projectsResp)) {
                return null;
            }
            return projectsResp;
        }
        return null;
    }

    @Override
    public ProjectInfoResp getProjectInfoFromHttp(Long projectId, String token) {
        Map<String, String> params = Maps.newHashMap();
        params.put("project_id", String.valueOf(projectId));
        params.put("v", String.valueOf(Instant.now().getEpochSecond()));
        String respStr = HttpUtils.doGet(UrlConstants.PROJECTS_INFO_URL, buildFWDHeaders(token), params);
        if (StringUtils.isBlank(respStr)) {
            return null;
        }
        log.info("【Http请求】 根据projectId:{},http请求查询演出信息结果:{}", projectId, respStr);
        JSONObject resp = JSON.parseObject(respStr);
        Integer code = (Integer) resp.get("code");
        if (Objects.nonNull(code) && Objects.equals(code, CodeConstants.SUCCESS)) {
            ProjectInfoResp projectInfoResp = JSON.parseObject(resp.get("data").toString(), ProjectInfoResp.class);
            if (Objects.isNull(projectInfoResp)) {
                return null;
            }
            return projectInfoResp;
        }
        return null;
    }

    @Override
    public ProjectOrderCreateResp createProjectOrder(ProjectOrderCreateReq req, String token) {
        String respStr = HttpUtils.doPost(UrlConstants.PROJECT_ORDER_CREATE_URL, buildFWDOrderHeaders(token), JsonUtils.toJsonString(req));
        if (StringUtils.isBlank(respStr)) {
            return null;
        }
        log.info("【Http请求】 http请求创建订单结果:{}", respStr);
        JSONObject resp = JSON.parseObject(respStr);
        Integer code = (Integer) resp.get("code");
        if (Objects.nonNull(code) && Objects.equals(code, CodeConstants.SUCCESS)) {
            ProjectOrderCreateResp projectOrderCreateResp = JSON.parseObject(resp.get("data").toString(), ProjectOrderCreateResp.class);
            if (Objects.isNull(projectOrderCreateResp)) {
                return null;
            }
            return projectOrderCreateResp;
        }
        if (Objects.nonNull(code) && Objects.equals(code, CodeConstants.LIMIT)) {
            int waitTime = new Random().nextInt(3);
            if (Objects.equals(waitTime, 0)) {
                waitTime = 3;
            }
            try {
                log.info("触发FWD限流机制，等待:{}秒后重新发送。", waitTime);
                Thread.sleep((long) waitTime * 1000);
            } catch (InterruptedException e) {
                log.error("线程暂停失败！");
            }
            return null;
        }
        return null;
    }
    @Override
    public Perform getPerformsByProjectIdFromHttp(Long projectId, String token) {
        Map<String, String> params = Maps.newHashMap();
        params.put("project_id", String.valueOf(projectId));
        params.put("v", String.valueOf(Instant.now().getEpochSecond()));
        String respStr = HttpUtils.doGet(UrlConstants.PERFORMS_URL, buildFWDHeaders(token), params);
        if (StringUtils.isBlank(respStr)) {
            return null;
        }
        log.info("【Http请求】 根据projectId:{}http请求查询演出票务信息结果:{}", projectId, respStr);
        JSONObject resp = JSON.parseObject(respStr);
        Integer code = (Integer) resp.get("code");
        if (Objects.nonNull(code) && Objects.equals(code, CodeConstants.SUCCESS)) {
            Perform projectInfoResp = JSON.parseObject(resp.get("data").toString(), Perform.class);
            if (Objects.isNull(projectInfoResp)) {
                return null;
            }
            return projectInfoResp;
        }
        return null;
    }

    @Override
    public List<SeatPlanStatus> getSeatPlanStatusFromHttp(List<Long> seatPlanIds, String token) {
        StringBuilder seatIds = new StringBuilder();
        for (Long seatPlanId : seatPlanIds) {
            seatIds.append(seatPlanId).append(",");
        }
        Map<String, String> params = Maps.newHashMap();
        params.put("seatPlanIds", seatIds.substring(0, seatIds.length() - 2));
        params.put("type", "3");
        String respStr = HttpUtils.doGet(UrlConstants.PROJECT_SEAT_STATUS_URL, buildFWDHeaders(token), params);
        if (StringUtils.isBlank(respStr)) {
            return Lists.newArrayList();
        }
        log.info("【Http请求】 根据seatPlanIds:{}http请求查询演出座位信息结果:{}", seatPlanIds, respStr);
        JSONObject resp = JSON.parseObject(respStr);
        Integer code = (Integer) resp.get("code");
        if (Objects.nonNull(code) && Objects.equals(code, CodeConstants.SUCCESS)) {
            List<SeatPlanStatus> data = JSON.parseArray(resp.get("data").toString(), SeatPlanStatus.class);
            if (CollectionUtils.isEmpty(data)) {
                return Lists.newArrayList();
            }
            return data;
        }
        return Lists.newArrayList();
    }

    @Override
    public List<AudienceMemberInfo> getAudienceMemberInfo(String token) {
        Map<String, String> params = Maps.newHashMap();
        String respStr = HttpUtils.doGet(UrlConstants.PROJECT_AUDIENCE_MEMBER_INFO, buildFWDHeaders(token), params);
        if (StringUtils.isBlank(respStr)) {
            return Lists.newArrayList();
        }
        log.info("【Http请求】 根据token:{}http请求查询观影人信息结果:{}", token, respStr);
        JSONObject resp = JSON.parseObject(respStr);
        Integer code = (Integer) resp.get("code");
        if (Objects.nonNull(code) && Objects.equals(code, CodeConstants.SUCCESS)) {
            List<AudienceMemberInfo> data = JSON.parseArray(resp.get("data").toString(), AudienceMemberInfo.class);
            if (CollectionUtils.isEmpty(data)) {
                return Lists.newArrayList();
            }
            return data;
        }
        return Lists.newArrayList();
    }

    @Override
    public Long getServerTimeStamp() {
        String respStr = HttpUtils.doGet(UrlConstants.PERFORMANCE_SERVER_TIME, buildFWDHeaders(null), null);
        if (StringUtils.isBlank(respStr)) {
            return -1L;
        }
        JSONObject jsonObject = JSON.parseObject(respStr);
        if (Objects.nonNull(jsonObject)) {
            Integer code = (Integer) jsonObject.get("code");
            if (Objects.equals(code, CodeConstants.SUCCESS)) {
                Long timestamp = (Long) jsonObject.get("data");
                return timestamp;
            }
        }
        return -1L;
    }

    private Map<String, String> buildFWDHeaders(String token) {
        Map<String, String> headers = Maps.newHashMap();
        headers.put("Host", "api.livelab.com.cn");
        headers.put("x-fwd-anonymousId", "ocXac5C25MY5O3UM_EfL0oTgm7Jw");
        headers.put("platform-type", "%E7%BA%B7%E7%8E%A9%E5%B2%9B%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F");
        headers.put("xweb_xhr", "1");
        headers.put("content-type", "application/json");
        headers.put("Accept", "*/*");
        headers.put("platform-version", "3.17.1");
        if (StringUtils.isNotBlank(token)) {
            headers.put("Authorization", token);
        }
        headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Mac MacWechat/WMPF MacWechat/3.8.7(0x13080712) UnifiedPCMacWechat(0xf2641110) XWEB/16730");
        headers.put("Referer", "https://servicewechat.com/wx5a8f481d967649eb/123/page-frame.html");
        headers.put("Sec-Fetch-Site", "cross-site");
        headers.put("Sec-Fetch-Mode", "cors");
        headers.put("Sec-Fetch-Dest", "empty");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        return headers;
    }

    private Map<String, String> buildFWDOrderHeaders(String token) {
        Map<String, String> headers = Maps.newHashMap();
        headers.put("Host", "api.livelab.com.cn");
        headers.put("x-fwd-anonymousId", "ocXac5C25MY5O3UM_EfL0oTgm7Jw");
        headers.put("platform-type", "%E7%BA%B7%E7%8E%A9%E5%B2%9B%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F");
        headers.put("Authorization", token);
        headers.put("platform-version", "3.17.1");
        headers.put("xweb_xhr", "1");
        headers.put("Content-Type", "application/json");
        headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Mac MacWechat/WMPF MacWechat/3.8.7(0x13080712) UnifiedPCMacWechat(0xf2641110) XWEB/16730");
        headers.put("Accept", "*/*");
        headers.put("Sec-Fetch-Site", "cross-site");
        headers.put("Sec-Fetch-Mode", "cors");
        headers.put("Sec-Fetch-Dest", "empty");
        headers.put("Referer", "https://servicewechat.com/wx5a8f481d967649eb/123/page-frame.html");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        return headers;
    }
}
