package com.zanxiang.game.platform.serve.service.platform;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zanxiang.game.platform.serve.enums.GamePlatformEnum;
import com.zanxiang.game.platform.serve.pojo.dto.PlatformDeYangOrderDTO;
import com.zanxiang.game.platform.serve.pojo.dto.PlatformDeYangUserDTO;
import com.zanxiang.game.platform.serve.pojo.entity.GamePlatform;
import com.zanxiang.game.platform.serve.pojo.entity.GamePlatformAccount;
import com.zanxiang.game.platform.serve.pojo.entity.PlatformDeYangOrder;
import com.zanxiang.game.platform.serve.pojo.entity.PlatformDeYangUser;
import com.zanxiang.game.platform.serve.pojo.res.PlatformDeYangOrderRes;
import com.zanxiang.game.platform.serve.pojo.res.PlatformDeYangUserRes;
import com.zanxiang.game.platform.serve.service.IPlatformDeYangOrderService;
import com.zanxiang.game.platform.serve.service.IPlatformDeYangUserService;
import com.zanxiang.module.util.DateUtil;
import com.zanxiang.module.util.JsonUtil;
import com.zanxiang.module.util.URIUtil;
import com.zanxiang.module.util.encryption.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : lingfeng
 * @time : 2023-05-24
 * @description : 德扬数据同步
 */
@Slf4j
@Service
public class PlatformDeYangService extends PlatformBaseService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IPlatformDeYangOrderService platformDeYangOrderService;

    @Autowired
    private IPlatformDeYangUserService platformDeYangUserService;

    @Override
    public GamePlatformEnum getGamePlatformEnum() {
        return GamePlatformEnum.DE_YANG;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncOrderByAccount(GamePlatform gamePlatform, GamePlatformAccount account, LocalDateTime startDate, LocalDateTime endDate) {
        Map<String, String> platformParam = JsonUtil.toMap(gamePlatform.getConfigParam(), Map.class, String.class);
        Map<String, String> accountParam = JsonUtil.toMap(account.getConfigParam(), Map.class, String.class);
        startDate = startDate == null ? LocalDateTime.of(gamePlatform.getBeginTime(), LocalTime.MIDNIGHT) : startDate;
        endDate = endDate == null ? LocalDateTime.now() : endDate;

        String appSecret = accountParam.get("secret");
        String host = platformParam.get("host");
        String agentId = accountParam.get("agent_id2");
        Map<String, String> params = new HashMap<>(6);
        params.put("name", account.getAccount());
        params.put("agent_id2", agentId);

        LocalDate searchDate = startDate.toLocalDate();
        do {
            int page = 1, totalPage = 0;
            params.put("seach_date", searchDate.toString());
            do {
                params.put("p", String.valueOf(page));
                params.put("time", String.valueOf(System.currentTimeMillis() / 1000));
                params.remove("sign");
                params.put("sign", sign(appSecret, params));
                String url = host + "/qc_order_list/";
                url = URIUtil.fillUrlParams(url, params, true);
                PlatformDeYangOrderRes res;
                try {
                    String result = restTemplate.getForObject(url, String.class);
                    res = JsonUtil.toObj(result, PlatformDeYangOrderRes.class);
                } catch (Exception e) {
                    log.error("同步德扬订单信息异常, accountId: {}, message: {}", account.getId(), e.getMessage());
                    break;
                }
                if (res == null || CollectionUtils.isEmpty(res.getList())) {
                    log.error("同步德扬订单信息,返回结果为空, accountId: {}, searchDate : {}, res : {}", account.getId(),
                            searchDate, JsonUtil.toString(res));
                    break;
                }
                //总页数赋值
                if (res.getAllpage() != null) {
                    totalPage = res.getAllpage();
                }
                //数据处理
                if (CollectionUtils.isNotEmpty(res.getList())) {
                    platformDeYangOrderService.saveOrUpdate(this.transformOrder(gamePlatform.getPlatformKey(), res.getList()));
                }
            } while (page++ <= totalPage);
            //日期递增
            searchDate = searchDate.plusDays(1);
        } while (!searchDate.isAfter(endDate.toLocalDate()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncUserByAccount(GamePlatform gamePlatform, GamePlatformAccount account, LocalDateTime startDate, LocalDateTime endDate) {
        startDate = startDate == null ? LocalDateTime.of(gamePlatform.getBeginTime(), LocalTime.MIDNIGHT) : startDate;
        endDate = endDate == null ? LocalDateTime.now() : endDate;
        Map<String, String> accountParam = JsonUtil.toMap(account.getConfigParam(), Map.class, String.class);
        Map<String, String> platformParam = JsonUtil.toMap(gamePlatform.getConfigParam(), Map.class, String.class);

        String host = platformParam.get("host");
        String appSecret = accountParam.get("secret");
        String agentId = accountParam.get("agent_id2");
        Map<String, String> params = new HashMap<>(7);
        params.put("name", account.getAccount());
        params.put("agent_id2", agentId);

        LocalDate searchDate = startDate.toLocalDate();
        do {
            int page = 1, totalPage = 0;
            params.put("seach_date", searchDate.toString());
            do {
                params.put("p", String.valueOf(page));
                params.put("time", String.valueOf(System.currentTimeMillis() / 1000));
                params.remove("sign");
                params.put("sign", sign(appSecret, params));
                String url = host + "/qc_user_list/";
                url = URIUtil.fillUrlParams(url, params, true);
                PlatformDeYangUserRes res;
                try {
                    String result = restTemplate.getForObject(url, String.class);
                    res = JsonUtil.toObj(result, PlatformDeYangUserRes.class);
                } catch (Exception e) {
                    log.error("同步德扬订单信息异常, accountId: {}, message: {}", account.getId(), e.getMessage());
                    break;
                }
                if (res == null || CollectionUtils.isEmpty(res.getList())) {
                    log.error("同步德扬用户信息,返回结果为空, accountId: {}, res : {}", account.getId(), JsonUtil.toString(res));
                    break;
                }
                //总页数赋值
                if (res.getAllpage() != null) {
                    totalPage = res.getAllpage();
                }
                //数据处理
                if (CollectionUtils.isNotEmpty(res.getList())) {
                    platformDeYangUserService.saveOrUpdate(this.transformUser(gamePlatform.getPlatformKey(), res.getList()));
                }
            } while (page++ <= totalPage);
            //日期递增
            searchDate = searchDate.plusDays(1);
        } while (!searchDate.isAfter(endDate.toLocalDate()));
    }

    private String sign(String secret, Map<String, String> params) {
        List<String> paramKeyList = new ArrayList<>(params.keySet());
        Collections.sort(paramKeyList);
        StringBuilder temp = new StringBuilder();
        for (String paramKey : paramKeyList) {
            if (Objects.equals(paramKey, "seach_date")) {
                continue;
            }
            temp.append(paramKey).append("=").append(params.get(paramKey)).append("&");
        }
        return Md5Util.encrypt32(temp.substring(0, temp.length() - 1) + secret);
    }

    private List<PlatformDeYangOrder> transformOrder(String platformKey, List<PlatformDeYangOrderDTO> orderList) {
        if (CollectionUtils.isEmpty(orderList)) {
            return Collections.emptyList();
        }
        return orderList.stream().map(order -> PlatformDeYangOrder.builder()
                .orderId(order.getOrderid())
                .platformKey(platformKey)
                .uid(order.getUid())
                .mpOpenId(order.getWecha_id())
                .gameName(order.getGame_name())
                .payStatus(order.getPay_status())
                .price(order.getPrice())
                .addTime(order.getAddtime() == null ? null : DateUtil.secondToLocalDateTime(order.getAddtime()))
                .payType(order.getPay_type())
                .payTime(Strings.isBlank(order.getPay_time()) ? null : DateUtil.parseLocalDateTime(order.getPay_time()))
                .roleName(order.getRole_name())
                .roleArea(order.getRole_area())
                .tunnelId(order.getTunnel_id())
                .productName(order.getProduct_name())
                .touFangBack(order.getToufang_back())
                .agentId(order.getAgent_id2())
                .bankOrderNo(order.getBankOrderNo())
                .build()).collect(Collectors.toList());
    }

    private List<PlatformDeYangUser> transformUser(String platformKey, List<PlatformDeYangUserDTO> userList) {
        if (CollectionUtils.isEmpty(userList)) {
            return Collections.emptyList();
        }
        return userList.stream().map(user -> PlatformDeYangUser.builder()
                .uid(user.getUid())
                .platformKey(platformKey)
                .mpOpenId(user.getWecha_id())
                .qcSign(user.getN_wecha_id())
                .time(Strings.isBlank(user.getTime()) ? null : DateUtil.parseLocalDateTime(user.getTime()))
                .tunnelId(user.getTunnel_id())
                .updateTime(Strings.isBlank(user.getUpdate_time()) ? null : DateUtil.parseLocalDateTime(user.getUpdate_time()))
                .allPrice(user.getAll_price())
                .gamePrice(user.getGame_price())
                .mobile(user.getMobile())
                .trueName(user.getTrue_name())
                .code(user.getCode())
                .gameName(user.getGame_name())
                .roleName(user.getRole_name())
                .roleArea(user.getRole_area())
                .ip(user.getIp())
                .appId(user.getAppid())
                .appName(user.getAppname())
                .userAgent(user.getUser_agent())
                .agentId(user.getAgent_id2())
                .build()).collect(Collectors.toList());
    }
}
