package tkio.service.impl;

import com.amazonaws.services.dynamodbv2.xspec.B;
import common.model.*;
import common.repository.*;
import dic.RoleEnum;
import dic.RoleTypeEnum;
import org.apache.commons.collections.map.AbstractMapDecorator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tkio.model.Account;
import tkio.model.SalesManLeader;
import tkio.repository.*;
import tkio.service.AccountFlowRestrictService;
import tkio.service.TkioAccountService;
import util.Constant;
import util.DateUtil;
import util.HttpClientUtil;
import util.ValidateUtil;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * Created by mxq on 2017/12/26.
 */
@Service
public class TkioAccountServiceImpl implements TkioAccountService {

    //查询URI
    private final static String URI_REPORT_BY_SQL = "/api/trackingio/bysql";

    @Autowired
    Account4WebRepository account4WebRepository;
    @Autowired
    SalesManLeaderRepository salesManLeaderRepository;
    @Autowired
    AccountRepository accountRepository;
    @Autowired
    BackVisitRepository backVisitRepository;
    @Autowired
    PaymentRepository paymentRepository;
    @Autowired
    ReminderRepository reminderRepository;
    @Autowired
    CampaignRepository campaignRepository;
    @Autowired
    ChannelRepository channelRepository;
    @Autowired
    AppRepository appRepository;
    @Autowired
    AccountFlowRestrictService accountFlowRestrictService;
    @Autowired
    UserRepository userRepository;

    @Override
    public List<Account4Web> findAll(User user) {
        List<Account4Web> result = new ArrayList<>();
        List<Account4Web> account4WebList = null;
        if(user.getRole().equals(RoleEnum.MANAGER.getKey())){
            account4WebList = account4WebRepository.findAll();
        } else{
            List<Integer> idList = new ArrayList<>();
            if(user.getRoleType().equals(RoleTypeEnum.MANAGER.getKey())){
                List<SalesManLeader> salesManLeaderList = salesManLeaderRepository.findByEmail(user.getEmail());
                if (ValidateUtil.isValid(salesManLeaderList)){
                    for(SalesManLeader sml : salesManLeaderList){
                        idList.add(sml.getId());
                    }
                }
            }else{
                SalesManLeader salesManLeader = salesManLeaderRepository.findOneByEmail(user.getEmail());
                idList.add(salesManLeader.getId());
            }
            if(ValidateUtil.isValid(idList)){
                List<Account> accountList = accountRepository.findBussnissMan(idList);
                List<String> emails = new ArrayList<>();
                if(ValidateUtil.isValid(accountList)){
                    for(Account ac : accountList){
                        emails.add(ac.getEmail());
                    }
                    account4WebList = account4WebRepository.findByEmails(emails);
                }
            }
        }
        if(ValidateUtil.isValid(account4WebList)){
            Map<String, Integer> backTimeMap = getBackTime();
            Map<String, Long> payMap = getPayment();
            for(Account4Web aw : account4WebList){
                if(backTimeMap.containsKey(aw.getEmail())){
                    aw.setBackTime(backTimeMap.get(aw.getEmail()));
                } else{
                    aw.setBackTime(0);
                }
                if(payMap.containsKey(aw.getEmail())){
                    aw.setMoney(payMap.get(aw.getEmail()));
                } else{
                    aw.setMoney(0L);
                }
                result.add(aw);
            }
        }
        return result;
    }

    @Override
    public Reminder forbiden(User user, Reminder resource) {
        resource.setUser(user.getId());
        resource.setModifyTime(new Date());
        resource.setPlatform("tkio");
        resource.setRemindStatus(false);
        resource.setDs(DateUtil.getBeforeDays(0));
        return reminderRepository.save(resource);
    }

    @Override
    public Reminder enable(User user, Reminder resource) {
        resource.setUser(user.getId());
        resource.setModifyTime(new Date());
        resource.setPlatform("tkio");
        resource.setRemindStatus(true);
        resource.setDs(DateUtil.getBeforeDays(0));
        return reminderRepository.save(resource);
    }

    @Override
    public Payment pay(User user, Payment resource) {
        resource.setUser(user.getId());
        resource.setPayDate(new Date());
        resource.setDs(DateUtil.getBeforeDays(0));
        return paymentRepository.save(resource);
    }

    @Override
    public BackVisit visit(User user, BackVisit resource) {
        resource.setUser(user.getId());
        resource.setVisitDate(new Date());
        resource.setDs(DateUtil.getBeforeDays(0));
        return backVisitRepository.save(resource);
    }

    @Override
    public Map<String, Integer> findFunTimes(Long account, String startDate, String endDate) {
        Map<String, Integer> result = new HashMap<>();
        List<Account> accountList = accountRepository.findByRootParent(account);
        List<Long> idList = new ArrayList<>();
        for(Account ac : accountList){
            idList.add(ac.getId());
        }
        List<String> appkeys = appRepository.findAppkeys(idList);
        String appkeyStr = String.join("','", appkeys);

        BigInteger numAccount = accountRepository.countByRootParent(account, startDate, endDate);
        BigInteger numApp = appRepository.countByAccount(idList, startDate, endDate);
        BigInteger numCampaign = campaignRepository.countByAccount(idList, startDate, endDate);
        BigInteger numChannel = channelRepository.countByAccount(idList, startDate, endDate);

        BigInteger event_sum = accountFlowRestrictService.getTotalNum(startDate, endDate, "'" + appkeyStr + "'", "account_io_flow_restrict", "event_sum");
        BigInteger click_sum =accountFlowRestrictService.getTotalNum(startDate, endDate, "'" + appkeyStr + "'","account_track_flow_restrict","click_sum");
        result.put("numAccount", numAccount.intValue());
        result.put("numApp", numApp.intValue());
        result.put("numCampaign", numCampaign.intValue());
        result.put("numChannel", numChannel.intValue());
        result.put("event_sum", event_sum.intValue());
        result.put("click_sum", click_sum.intValue());
        return result;
    }

    @Override
    public List<Map<String, Object>> findPv(Long account, String startDate, String endDate) {
        List<Map<String, Object>>  result = new ArrayList<>();
        List<Account> accountList = accountRepository.findByRootParent(account);
        List<Long> idList = new ArrayList<>();
        for(Account ac : accountList){
            idList.add(ac.getId());
        }
        List<String> appkeys = appRepository.findAppkeys(idList);
        String appkeyStr = String.join("','", appkeys);

        String querySql = "select menu, count(*) as pv, count(distinct(xwho)) as uv, count(*)/count(distinct(xwho)) as puv " +
                "from tkio_bigtable_view.event_f0f251af10e66a0c94d2e923d8863105 where user_appkey in ('" + appkeyStr + "') " +
                "AND ds >= '" + startDate + "' AND ds <= '" + endDate + "'  group by menu;";
        String url = Constant.reportUrl + URI_REPORT_BY_SQL;

        Map<String, String> conditions = new HashMap<>();
        conditions.put("sql", querySql);
        conditions.put("dbtype", "presto");
        conditions.put("datatype", "list");
        conditions.put("iscache", "0");

        String responseJson = HttpClientUtil.doHttpPostRequest(url, "trackingio", conditions);
        if(responseJson.contains("val")){
            try {
                JSONObject jsonObject = new JSONObject(responseJson);
                JSONArray valArr = jsonObject.getJSONArray("val");
                if(null != valArr && valArr.length() > 0){
                    for(int i = 0; i < valArr.length(); i++){
                        JSONObject val = valArr.getJSONObject(i);
                        Map<String, Object> map = new HashMap<>();
                        map.put("menu", val.getString("menu"));
                        map.put("pv", val.getInt("pv"));
                        map.put("uv", val.getInt("uv"));
                        map.put("puv", val.getInt("puv"));

                        result.add(map);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public List<Reminder> findRed(Long account, String startDate, String endDate) {
        List<Reminder> result = new ArrayList<>();
        List<User> userList = userRepository.findAll();
        Map<Long, String> userMap = new HashMap<>();
        for(User u : userList){
            userMap.put(u.getId(), u.getName());
        }
        List<Reminder> list = reminderRepository.findAll(account, startDate, endDate, "tkio");
        if (ValidateUtil.isValid(list)) {
            for(Reminder re : list){
                re.setUserName(userMap.get(re.getUser()));
                result.add(re);
            }
        }
        return result;
    }

    @Override
    public List<BackVisit> findVisit(Long account, String startDate, String endDate) {
        List<BackVisit> result = new ArrayList<>();
        List<User> userList = userRepository.findAll();
        Map<Long, String> userMap = new HashMap<>();
        for(User u : userList){
            userMap.put(u.getId(), u.getName());
        }
        List<BackVisit> list = backVisitRepository.findAll(account, startDate, endDate, "tkio");
        if (ValidateUtil.isValid(list)) {
            for(BackVisit re : list){
                re.setUserName(userMap.get(re.getUser()));
                result.add(re);
            }
        }
        return result;
    }

    @Override
    public List<Payment> findPay(Long account, String startDate, String endDate) {
        List<Payment> result = new ArrayList<>();
        List<User> userList = userRepository.findAll();
        Map<Long, String> userMap = new HashMap<>();
        for(User u : userList){
            userMap.put(u.getId(), u.getName());
        }
        List<Payment> list = paymentRepository.findAll(account, startDate, endDate, "tkio");
        if (ValidateUtil.isValid(list)) {
            for(Payment re : list){
                re.setUserName(userMap.get(re.getUser()));
                result.add(re);
            }
        }
        return result;
    }


    public Map<String, Integer> getBackTime(){
        Map<String, Integer> map = new HashMap<>();
        List<BackVisit> all = backVisitRepository.findAll();
        if (ValidateUtil.isValid(all)){
            for(BackVisit bv : all){
                if(map.containsKey(bv.getEmail())){
                    map.put(bv.getEmail(), map.get(bv.getEmail()) + 1);
                } else{
                    map.put(bv.getEmail(), 1);
                }
            }
        }
        return map;
    }

    public Map<String, Long> getPayment(){
        Map<String, Long> map = new HashMap<>();
        List<Payment> all = paymentRepository.findAll();
        if (ValidateUtil.isValid(all)){
            for(Payment pa : all){
                if(map.containsKey(pa.getEmail())){
                    map.put(pa.getEmail(), map.get(pa.getEmail()) + pa.getMoney());
                } else{
                    map.put(pa.getEmail(), pa.getMoney());
                }
            }
        }
        return map;
    }
}
