package com.reyun.service.impl;

import com.reyun.model.Account;
import com.reyun.repository.AccountRepository;
import com.reyun.repository.AppRepository;
import com.reyun.util.Constant;
import com.reyun.util.DynamoDBUtil;
import com.reyun.util.HttpClientUtil;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class Top5FlowUsers {


    @Autowired
    AccountRepository accountRepository;

    @Autowired
    AppRepository appRepository;


    /**
     * 使用套餐用户流量top5
     */
    @Test
    public void top5userFlow() {

        List<Account> superUers = accountRepository.findShiYongUser("2018-01-01", "2019-12-31");

        List<AppAccount> appAccounts = new ArrayList<>();

        for (Account superUer : superUers) {
            List<String> appkeys = appRepository.findAllAppByAccount(superUer.getId());

            if (!appkeys.isEmpty()) {
                AppAccount appAccount = new AppAccount();
                appAccount.setAccount(superUer);
                appAccount.setAppkeys("'" + appkeys.stream().collect(Collectors.joining("','")) + "'");
                appAccounts.add(appAccount);
            }

        }


        List<AppAccount> flows = new ArrayList<>();

        for (AppAccount appAccount : appAccounts) {
            //获取流量
            Map<String, String> conditions = new HashMap<>();
            conditions.put("appids", appAccount.getAppkeys());
            Account account = appAccount.getAccount();
            conditions.put("startdate", new DateTime(account.getPubDate()).toString("yyyy-MM-dd"));
            conditions.put("enddate", account.getPastDate());
            BigInteger value = this.getTotalNum(conditions, "account_track_flow_restrict", "click_sum");

            if (value.doubleValue() > 0) {
                appAccount.setFlow(value);
                flows.add(appAccount);
            }

        }


        flows = flows.stream().sorted(Comparator.comparing(AppAccount::getFlow).reversed())
                .collect(Collectors.toList());


        StringBuffer text = new StringBuffer();
        for (AppAccount flow : flows) {
            Account account = flow.getAccount();
            text.append(account.getEmail()).append(",")
                    .append(account.getPastDate()).append(",")
                    .append(flow.getFlow().longValue()).append(",")
                    .append(account.getPricelevel()).append("\t\n");

        }

        try {
            Files.write(Paths.get("d:/awsdf.txt"),text.toString().getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(text.toString());

    }


    public BigInteger getTotalNum(Map<String, String> conditions, String reportName, String sumType) {
        Long appId = 1218L;
        conditions.put("datatype", "list");
        conditions.put("iscache", Constant.iscache);
        String url = Constant.reportUrl + "/api/trackingio/" + reportName + "/" + appId;
        String responseJson = HttpClientUtil.doHttpPostRequest(url, "trackingio", conditions);
        HashMap<String, String> resultValMap = new HashMap<>();
        String click_sum = "";
        String s = "0";
        if (responseJson != null) {
            try {
                JSONObject jsonObject = new JSONObject(responseJson);
                Iterator keys = jsonObject.keys();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    String value = jsonObject.getString(key);
                    resultValMap.put(key, value);
                }
                String val = resultValMap.get("val");
                JSONArray jsonArray = new JSONArray(val);
                JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                click_sum = jsonObject1.getString(sumType);
                if (StringUtils.isEmpty(click_sum) || "0".equals(click_sum)) {
                    click_sum = "0";
                }
                Double aDouble = Double.valueOf(click_sum);
                BigDecimal bigDecimal = new BigDecimal(aDouble);
                s = bigDecimal.toPlainString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return new BigInteger(s);
    }


    class AppAccount {
        String appkeys;
        Account account;
        BigInteger flow;

        public String getAppkeys() {
            return appkeys;
        }

        public void setAppkeys(String appkeys) {
            this.appkeys = appkeys;
        }

        public Account getAccount() {
            return account;
        }

        public void setAccount(Account account) {
            this.account = account;
        }

        public BigInteger getFlow() {
            return flow;
        }

        public void setFlow(BigInteger flow) {
            this.flow = flow;
        }
    }
}