<?php

namespace App\Modules\CP\Services;

use App\Modules\CpSub\Models\CpSub;
use App\Modules\CpSub\Models\CpCalculate;
use App\Modules\Book\Models\BookConfig;
use App\Modules\CpUser\Services\CpUserService;

class GenerateCpBookStatService
{
  
    /**
     * 生成每日统计
     */
    public static function generateCpBookDailyStat($date) {
    	if(empty($date)) $data = date('Y-m-d');
    	$result = array();
    	$all_cp_list = BookConfig::getAllCps();
    	\Log::info($all_cp_list);
    	$special_cps = array('17k','wangyi');

    	$today = date('Y-m-d');
//     	$today = date('Y-m-01');
    	
    	$start_date = date('Y-m-01');
    	$end_date = $date;
    	$month = date('Y-m');
    	$calculate_date = date('Y-m-d');
    	
    	// 每个月1号算上个月的
    	if($today == $start_date){
    		$start_date = date('Y-m-01',strtotime(' -1 month'));
    		$month = date('Y-m',strtotime(' -1 month'));
    	}
    	\Log::info('generateCpBookDailyStat,start_date:'.$start_date.' end_date:'.$end_date.' month:'.$month.' calculate_date:'.$calculate_date);
    	$all_data_list = BookConfig::getAllCpBookConsume($start_date,$end_date,$all_cp_list);
    	
    	self::insert_daily_stat($all_data_list,$month,$calculate_date);
    	
        return $result;
    }
    
    /**
     * 生成指定月份数据
     */
    public static function generateCpBookBetweenStat($start_date,$end_date,$month,$calculate_date) {
    	\Log::info('generateCpBookBetweenStat_start,start_date:'.$start_date.' end_date:'.$end_date.' month:'.$month.' calculate_date:'.$calculate_date);
    	if(empty($start_date) || empty($end_date) || empty($month) || empty($calculate_date)) {
    		\Log::info('generateCpBookBetweenStat isnull,start_date:'.$start_date.' end_date:'.$end_date.' month:'.$month.' calculate_date:'.$calculate_date);
    		return false;
    	}
    	$result = array();
    	$all_cp_list = BookConfig::getAllCps();
    	\Log::info($all_cp_list);

    	$all_data_list = BookConfig::getAllCpBookConsume($start_date,$end_date,$all_cp_list);
    	 
    	self::insert_daily_stat($all_data_list,$month,$calculate_date);
    	 
    	return $result;
    }
    
    /**
     * 生成汇总数据
     */
    public static function insert_daily_stat($item_list,$month,$calculate_date) {
    	\Log::info('insert_daily_stat_start');
         foreach($item_list as $key=>$item){
         	try{
    			// 算当天
    			// 单本书指定date的充值数据
    			$insert_data = array();
    			$insert_data['month'] = empty($month)?date('Y-m'):$month;
    			$insert_data['calculate_date'] = empty($calculate_date)?date('Y-m-d'):$calculate_date;
    			$cp_user = CpUserService::getCpUser($item['cp_source']);
    			$insert_data['cp_user_id'] = isset($cp_user->id)?$cp_user->id:'0';
    			$insert_data['cp_source'] = $item['cp_source'];
    			$insert_data['bid'] = $item['bid'];
    			$insert_data['book_name'] = $item['book_name'];
    			
    			\Log::info('insert_daily_stat_cp_source:'.$insert_data['cp_source'].' cp_user_id:'.$insert_data['cp_user_id'].' calculate_date:'.$insert_data['calculate_date'].' bid:'.$insert_data['bid']);
    			 
    			//     			计算方式
    			//     			中文：可分成金额=（（充值币*（1-0.806））-（充值币*（1-0.806））*0.1）/100
    			//     			最终可分成金额=（（（充值币*（1-0.806））-（充值币*（1-0.806））*0.1）/100）/2
    			//     			总订阅数据=充值币*（1-0.806）
    			//     			网易：可分成金额=（（充值币*（1-0.556））-（充值币*（1-0.556））*0.35）/100
    			//     			最终分成金额=（（（充值币*（1-0.556））-（充值币*（1-0.556））*0.35）/100）/2
    			//     			总订阅金额=充值币*（1-0.556）
    			//     			其余CP：可分成金额=（充值币-（充值币*0.906））/100
    			//     			最终分成金额=（充值币-（充值币*0.906））/100/2
    			// 第二版
//     			CP	具体限制	具体公式
//     			中文在线	35W保底+分成	 (可显示)总订阅量=充值币*（1-0.806）=充值币*0.194
//     			（可显示CP）可分成金额=（充值币*0.194-充值币*0.1）/100
//     			（可显示CP）最终可分成金额=（充值币*0.194-充值币*0.1）/100/2
//     			网易云阅读	30W保底+分成	（可显示CP）总订阅量=充值币*（1-0.556）=充值币*0.444
//     			（可显示CP）可分成金额=（充值币*0.444-充值币*0.35）/100
//     			（可显示CP）最终可分成金额=（充值币*0.444-充值币*0.35）/100/2
//     			塔读	32W保底+分成	此CP默认与其他CP的结算公式一致
//     			其他小CP	去除渠道成本后，5:5分成	 
//     			其余CP：（CP后台显示的）本月订阅量=充值币*（1-0.906）                                                         
//     			（CP后台显示的）可分成金额=本月订阅量/100=充值币*0.094/100                                                 
//     			（CP后台显示的）最终分成金额=充值币*0.094/100/2
                 //  计算公式从数据库拿
                $cp_calculate = CpCalculate::getCpCalculate($item['cp_source']);
    			
    			\Log::info('cp_calculate:'.$item['cp_source'].' val:'.json_encode($cp_calculate));
    			$insert_data['available_amount'] = $item['charge_balance']*$cp_calculate['available_amount_ratio'];
    			$insert_data['last_amount'] = $item['charge_balance']*$cp_calculate['last_amount_ratio'];
    			$insert_data['total_amount'] = $item['charge_balance']*$cp_calculate['total_amount_ratio'];
    			$insert_data['current_month_book_num'] = $item['charge_balance'];// 书币数量
    			
//     			if($item['cp_source'] == '17k'){
//     				$insert_data['available_amount'] = $item['charge_balance']*(0.194-0.1)/100;
//     				$insert_data['last_amount'] = $item['charge_balance']*(0.194-0.1)/100/2;
//     				$insert_data['total_amount'] = $item['charge_balance']*0.194;
//     				$insert_data['current_month_book_num'] = $item['charge_balance'];// 书币数量
//     			}elseif($item['cp_source'] == 'wangyi'){
//     				$insert_data['available_amount'] = $item['charge_balance']*(0.444-0.35)/100;
//     				$insert_data['last_amount'] = $item['charge_balance']*(0.444-0.35)/100/2;
//     				$insert_data['total_amount'] = $item['charge_balance']*0.444;
//     				$insert_data['current_month_book_num'] = $item['charge_balance'];
//     			}else{
//     				$insert_data['available_amount'] = $item['charge_balance']*(1-0.906)/100;
//     				$insert_data['last_amount'] = $item['charge_balance']*(1-0.906)/100/2;
//     				$insert_data['total_amount'] = $item['charge_balance']*(1-0.906);
//     				$insert_data['current_month_book_num'] = $item['charge_balance'];
//     			}
    			
    			$current_cp_sub = CpSub::getCpSub($insert_data['cp_source'],$insert_data['calculate_date'],$insert_data['bid']);
    			\Log::info($current_cp_sub);
    			if(empty($current_cp_sub)){
    				\Log::info('insert');
    				CpSub::firstOrcreate($insert_data);
    			}else{
    				\Log::info('not_insert');
    			}
    			
         	}catch(\Exception $e){
         		\Log::info($e->getMessage());
         	}
    			
    	}
    }

    /**
     * 生成每日统计
     */
    public static function generateCpBookDailyStat2($date) {
        if(empty($date)) return '';
        //$result = array();
        $all_cp_list = BookConfig::getAllCps();

        $start_date = date('Y-m-01');
        $end_date = date('Y-m-d',time()-86400);
        $month = date('Y-m');
        //$calculate_date = date('Y-m-d');


        //\Log::info('generateCpBookDailyStat,start_date:'.$start_date.' end_date:'.$end_date.' month:'.$month.' calculate_date:'.$calculate_date);
        $all_data_list = BookConfig::getAllCpBookConsume($start_date,$end_date,$all_cp_list);

        self::insert_daily_stat($all_data_list,$month,$date);

        //return $result;
    }
}
