package com.example.repurchase.calculation;

import com.example.repurchase.configuration.ElasticSearchPoolUtil;
import com.example.repurchase.utils.DateUtils;
import com.example.repurchase.utils.SqlUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;

/**
 * @author 黄树文
 * @date 2020/4/3 16:43
 */
public class CalculationRepurchaseInfo {

    @Resource(name = "clickhouseDruidDataSourceMaster")
    private DataSource clickhouseDruidDataSourceMaster;

    /**
     * 计算本月订单金额，订单总数，会员数，复购金额，复购订单数，复购会员数
     * @param yearAndMonth
     * @throws Exception
     */
    public void calculationRepurchaseInfoThisMonth(String yearAndMonth) throws Exception {
        String lastYearAndMonth = DateUtils.getOffsetMonth(yearAndMonth, -1);
        yearAndMonth = yearAndMonth.replaceAll("-", "");

        RestHighLevelClient restHighLevelClient = ElasticSearchPoolUtil.getClient();

        Connection clickhouseClient = clickhouseDruidDataSourceMaster.getConnection();
        Statement clickhouseStatement = clickhouseClient.createStatement();

        // 计算本月订单金额，订单总数，会员数，复购金额，复购订单数，复购会员数
        // 计算本月订单金额，订单总数，会员数
        ResultSet resultSet = clickhouseStatement.executeQuery("SELECT sum(Sum) as orderMoney, count(1) as orderCounts, COUNT(DISTINCT AConsigneePhone2) as orderMember FROM Orders where OrderStatus in(50,70,150) and IsReturn=0 AND OrdersCode not like '%BF' and toYYYYMM(CreationDate) = " + yearAndMonth);
        HashMap<String, Object> resultSetHashMap = SqlUtils.convertSqlRresultToHashMap(resultSet).get(0);
        // 计算复购金额，复购订单数，复购会员数（本月以前有购买记录）
        ResultSet resultSetRepurchaseBefore = clickhouseStatement.executeQuery("SELECT COUNT(1) as repurchaseOrderCounts, sum(Sum) as repurchaseOrderMoney, count(DISTINCT AConsigneePhone2) as repurchaseOrderMember from Orders where toYYYYMM(CreationDate) = " + yearAndMonth + " and OrderStatus in(50,70,150) and IsReturn=0 AND OrdersCode not like '%BF' and AConsigneePhone2 GLOBAL in (SELECT AConsigneePhone2 FROM Orders where toYYYYMM(CreationDate) < " + yearAndMonth + " and OrderStatus in(50,70,150) and IsReturn=0 AND OrdersCode not like '%BF');");
        HashMap<String, Object> resultSetRepurchaseBeforeHashMap = SqlUtils.convertSqlRresultToHashMap(resultSetRepurchaseBefore).get(0);
        // 计算复购金额，复购订单数，复购会员数（上月有购买记录）
        ResultSet resultSetRepurchaseLastMonth = clickhouseStatement.executeQuery("SELECT COUNT(1) as repurchaseOrderCountsLastMonth, sum(Sum) as repurchaseOrderMoneyLastMonth, count(DISTINCT AConsigneePhone2) as repurchaseOrderMemberLastMonth from Orders where toYYYYMM(CreationDate) = " + yearAndMonth + " and OrderStatus in(50,70,150) and IsReturn=0 AND OrdersCode not like '%BF' and AConsigneePhone2 GLOBAL in (SELECT AConsigneePhone2 FROM Orders where toYYYYMM(CreationDate) = " + lastYearAndMonth + " and OrderStatus in(50,70,150) and IsReturn=0 AND OrdersCode not like '%BF');");
        HashMap<String, Object> resultSetRepurchaseLastMonthHashMap = SqlUtils.convertSqlRresultToHashMap(resultSetRepurchaseLastMonth).get(0);

        resultSetRepurchaseBeforeHashMap.forEach((key, value) -> resultSetHashMap.put(key, value));
        resultSetRepurchaseLastMonthHashMap.forEach((key, value) -> resultSetHashMap.put(key, value));
        resultSetHashMap.put("repurchaseRate", (Integer.parseInt(resultSetHashMap.get("").toString()) + 0.0 )/Integer.parseInt(resultSetHashMap.get("").toString()));

        IndexRequest indexRequest = new IndexRequest("repurchaseinfo").id(yearAndMonth).source(resultSetHashMap);
        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

    }

    /**
     * 计算总的订单数，订单金额，复购订单数，复购金额数
     * @throws Exception
     */
    public void calculationRepurchaseInfo() throws Exception {
        RestHighLevelClient restHighLevelClient = ElasticSearchPoolUtil.getClient();

        Connection clickhouseClient = clickhouseDruidDataSourceMaster.getConnection();
        Statement clickhouseStatement = clickhouseClient.createStatement();


    }
}
