<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/1
 * Time: 下午7:57
 */

namespace App\Modules\Finance\Services;

use App\Modules\Channel\Services\ChannelService;
use App\Modules\Finance\Models\FinancialStat;
use App\Modules\Finance\Models\Payment;
use App\Modules\Finance\Models\WithdrawCash;
use App\Modules\Trade\Services\OrderService;

class FinanceService
{

    /**
     * 昨天，结算、清算 任务数据生成
     */
    public static function makeDayDataStatistics() {
        $yesterdayStart = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"))." 00:00:00";
        $yesterdayEnd = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"))." 23:59:59";

        /*$yesterdayStart = date('Y-m-d')." 00:00:00";
        $yesterdayEnd = date('Y-m-d')." 23:59:59";*/
        //$yesterdayEnd = date('Y-m-d', strtotime(date("Y-m-d")))." 00:00:00";

        $not_in_pay_merchant_idStr = env('not_in_pay_merchant_id');
        $not_in_pay_merchant_id = [];
        if($not_in_pay_merchant_idStr) {
            $not_in_pay_merchant_id = explode(',', $not_in_pay_merchant_idStr);
        }

        $channels = ChannelService::getAllChannels();
        foreach ($channels as $channel) {
//            print_r($channel->id."=".$channel->name."\n");
            $channelId = $channel->id;

            $params = [
                'distribution_channel_id'=>$channelId,
                'begin_time'=>$yesterdayStart,
                'end_time'=>$yesterdayEnd,
                'not_in_pay_merchant_id'=>$not_in_pay_merchant_id
            ];
            $rechargeAmount = OrderService::getAmount($params);

            //前天充值总额对比，若有多出的部分，算到今天
            $dayBeforeYesRecharge = BillService::getOne($channelId,date('Y-m-d',strtotime('-2 day')));
            //$dayBeforeYesRecharge = BillService::getOne($channelId,date('Y-m-d',strtotime('-1 day')));
            if($dayBeforeYesRecharge){
                $dayBeforeYesRecharge = $dayBeforeYesRecharge->recharge_amount;
                $params2 = [
                    'distribution_channel_id'=>$channelId,
                    'begin_time'=>date('Y-m-d',strtotime('-2 day')),
                    'end_time'=>date('Y-m-d 23:59:59',strtotime('-2 day')),
                    'not_in_pay_merchant_id'=>$not_in_pay_merchant_id
                ];
                $dayBeforeYesRealRecharge = OrderService::getAmount($params2);
                $diff = $dayBeforeYesRealRecharge-$dayBeforeYesRecharge;
                if($diff>0){
                    $rechargeAmount = $rechargeAmount+$diff;
                    \Log::info('distribution_channel_recharge_regards_as_next_day:distribution:'.$channelId.':today:'.date('Y-m-d').':diff:'.$diff);
                    try{
                        $changes_data = [
                            'amount_changes'=>$diff,
                            'distribution_channel_id'=>$channelId,
                            'date'=>date('Y-m-d',strtotime('-1 day')),
                            'created_at'=>date('Y-m-d H:i:s')
                        ];
                        DB::table('bills_changes')->insert($changes_data);
                    }catch (\Exception $e){

                    }
                }
            }

            //dd($rechargeAmount);
            //生成结算总额结算单
            BillService::addBill($channelId, $rechargeAmount);

//            print_r($channelId."=结算总额=".$rechargeAmount."\n");

            $rate = BillService::getRate($channelId);

            //生成每日清算明细 Liquidation
            $orderByChannels = OrderService::getPayMerchantSourceAmount($params);
//            print_r($orderByChannels);

            foreach ($orderByChannels as $k=>$item) {
                //总金额 - (总金额 * 结算比例) = 清算金额
                $amountTmp = $item - ($item * $rate);
                //添加清算记录
                if($k == config('common.tonglianpay') || $k == config('common.officialpay')) {
                    //官方，通联，每天自动结算，不用清算数据
                } else {
                    LiquidationService::addLiquidation($channelId, $k, $amountTmp, 0, "每日结算");
                }

//                //更新清算汇总表数据 LiquidatedStat
                LiquidatedStatService::createOrUpdate($k, $amountTmp);
//                //更新 支付通道可提现总额 FinanceMerchantStat
                FinanceMerchantStatService::createOrUpdate($channelId, $k, $amountTmp);
//                print_r($channelId."= 支付渠道=".$k."= 结算=".$item."= 清算=".$amountTmp."\n");
            }
//            print_r($channelId."=".$channelName."=".$rechargeAmount."\n");
        }
    }























    /**
     * 获取渠道账户余额(可提现金额)
     * @param $channelId
     * @return int
     */
    public static function getChannelAccountBalance($channelId) {
        $accountBalance = FinancialStat::getEnableWithdrawalAmount($channelId);
        return $accountBalance;
    }

    /**
     * 获取所有渠道账户余额总额(可提现金额总额)
     */
    public static function getChannelAccountBalanceAll() {
        $accountBalance = FinancialStat::getEnableWithdrawalAmount();
        return $accountBalance;
    }


    /**
     * @return mixed
     * {Number}  yesterday_amount_audit_success 昨日已审核金额
     * {Number}  all_amount_audit_success 所有已审核金额
     * {Number}  yesterday_amount_apply 昨日申请提现金额
     * {Number}  all_amount_apply 所有申请提现金额
     * {Number}  yesterday_amount_audit_fail 昨日审核不通过
     * {Number}  all_amount_audit_fail 所有审核不通过
     * {Number}  yesterday_amount_wait 昨日待打款金额
     * {Number}  all_amount_wait 所有待打款金额
     * {Number}  yesterday_amount_apply_success 昨日成功提现金额
     * {Number}  all_amount_apply_success 所有成功提现金额
     * {Number}  yesterday_amount_apply_person_success 昨日对私成功提现金额
     * {Number}  all_amount_apply_person_success 所有对私成功提现金额
     * {Number}  yesterday_amount_apply_company_success 昨日对公成功提现金额
     * {Number}  all_amount_apply_company_success 所有对公成功提现金额
     * {Number}  yesterday_amount_apply_success 昨日成功提现金额
     * {Number}  all_amount_apply_success 所有成功提现金额
     * {Number}  yesterday_apply_num 昨日累积提现笔数
     * {Number}  all_apply_num 所有累积提现笔数
     * {Number}  yesterday_tallage_count 昨日累积提现手续费
     * {Number}  all_stallage_count 所有累积提现手续费
     */
    public static function getDataStatisticsWithdrawCash() {
        $startDay = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"))." 00:00:00";
        $endDay = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"))." 23:59:59";

        //昨日已审核金额
        $yesterday_amount_audit_success = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrSuccessFailCheckedSuccessList())
            ->where('distribution_channel_id', '>', 0)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        $data['yesterday_amount_audit_success'] = $yesterday_amount_audit_success;

        //所有已审核金额
        $all_amount_audit_success = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrSuccessFailCheckedSuccessList())
            ->where('distribution_channel_id', '>', 0)
            ->sum('amount');
        $data['all_amount_audit_success'] = $all_amount_audit_success;

        //昨日申请提现金额
        $yesterday_amount_apply = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(0))
            ->where('distribution_channel_id', '>', 0)
            ->where('created_at','>=',$startDay)
            ->where('created_at','<=',$endDay)
            ->sum('amount');
        $data['yesterday_amount_apply'] = $yesterday_amount_apply;

        //所有申请提现金额 待审核
        $all_amount_apply = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(0))
            ->where('distribution_channel_id', '>', 0)
            ->sum('amount');
        $data['all_amount_apply'] = $all_amount_apply;

        //昨日审核不通过
        $yesterday_amount_audit_fail = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(9))
            ->where('distribution_channel_id', '>', 0)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        $data['yesterday_amount_audit_fail'] = $yesterday_amount_audit_fail;

        //所有审核不通过
        $all_amount_audit_fail = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(9))
            ->where('distribution_channel_id', '>', 0)
            ->sum('amount');
        $data['all_amount_audit_fail'] = $all_amount_audit_fail;

        //昨日待打款金额 待打款
        $yesterday_amount_wait = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(10))
            ->where('distribution_channel_id', '>', 0)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        $data['yesterday_amount_wait'] = $yesterday_amount_wait;
        //所有待打款金额 待打款
        $all_amount_wait = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(10))
            ->where('distribution_channel_id', '>', 0)
            ->sum('amount');
        $data['all_amount_wait'] = $all_amount_wait;
        //所有待打款金额 待打款 笔数
        $all_amount_wait_num = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(10))
            ->where('distribution_channel_id', '>', 0)
            ->count('amount');
        $data['all_amount_wait_num'] = $all_amount_wait_num;


        //昨日对私打款成功
        $yesterday_amount_apply_person_success = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', '>', 0)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->where('is_company', 0)
            ->sum('amount');
        $data['yesterday_amount_apply_person_success'] = $yesterday_amount_apply_person_success;
        //所有对私打款成功
        $all_amount_apply_person_success = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', '>', 0)
            ->where('is_company', 0)
            ->sum('amount');
        $data['all_amount_apply_person_success'] = $all_amount_apply_person_success;
        //昨日对公打款成功
        $yesterday_amount_apply_company_success = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', '>', 0)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->where('is_company', 1)
            ->sum('amount');
        $data['yesterday_amount_apply_company_success'] = $yesterday_amount_apply_company_success;
        //所有对公打款成功
        $all_amount_apply_company_success = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', '>', 0)
            ->where('is_company', 1)
            ->sum('amount');
        $data['all_amount_apply_company_success'] = $all_amount_apply_company_success;


        //昨日成功提现金额
        $yesterday_amount_apply_success = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', '>', 0)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        $data['yesterday_amount_apply_success'] = $yesterday_amount_apply_success;

        //所有成功提现金额
        $all_amount_apply_success = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', '>', 0)
            ->sum('amount');
        $data['all_amount_apply_success'] = $all_amount_apply_success;

        //昨日累积提现笔数
        $yesterday_apply_num = WithdrawCash::where('created_at','>=',$startDay)
            ->where('distribution_channel_id', '>', 0)
            ->where('created_at','<=',$endDay)
            ->count('amount');
        $data['yesterday_apply_num'] = $yesterday_apply_num;

        //所有累积提现笔数
        $all_apply_num = WithdrawCash::where('distribution_channel_id', '>', 0)->count('id');
        $data['all_apply_num'] = $all_apply_num;

        //昨日累积提现手续费
        $yesterday_tallage_count = WithdrawCash::
           where('distribution_channel_id', '>', 0)
            ->where('created_at','>=',$startDay)
            ->where('created_at','<=',$endDay)
            ->sum('tallage');
        $data['yesterday_tallage_count'] = $yesterday_tallage_count;

        //所有累积提现手续费
        $all_stallage_count = WithdrawCash::where('distribution_channel_id', '>', 0)->sum('tallage');
        $data['all_stallage_count'] = $all_stallage_count;

        return $data;
    }

    /**
     * @return mixed
     * {Number}  yesterday_payment_count 昨日累积打款金额
     * {Number}  all_payment_count 所有累积打款金额
     */
    public static function getDataStatisticsPayment() {
        $startDay = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"))." 00:00:00";
        $endDay = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"))." 23:59:59";

        //昨日累积打款金额
        $yesterday_payment_count = Payment::
            whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        //所有累积打款金额
        $all_payment_count = Payment::
            whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->sum('amount');

        $data['yesterday_payment_count'] = $yesterday_payment_count;
        $data['all_payment_count'] = $all_payment_count;

        return $data;
    }

    /**
     * @return mixed
     * {Number}  all_amount_apply_success_count 所有累积已提现金额
     * {Number}  all_amount_apply_count 所有累积可提现金额
     */
    public static function getDataStatisticsFinancialStat() {
        $startDay = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"))." 00:00:00";
        $endDay = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"))." 23:59:59";

        //所有累积已提现金额
        //$all_amount_apply_success_count = FinancialStat::sum('accumulative_withdrawal_amount');
        $all_amount_apply_success_count = WithdrawCash::where('distribution_channel_id', '>', 0)->sum('amount');
        //所有累积可提现金额
        $all_amount_apply_count = FinancialStat::sum('enable_withdrawal_amount');

        $data['all_amount_apply_success_count'] = $all_amount_apply_success_count;
        $data['all_amount_apply_count'] = $all_amount_apply_count;

        return $data;
    }


    /**
     * 生成昨日打款，审核报表
     * @param $channelId
     */
    public static function makeYesterdayWithdrawCashStatistics($channelId) {
        $startDay = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"))." 00:00:00";
        $endDay = date('Y-m-d', strtotime(date("Y-m-d")))." 00:00:00";

        if(!is_numeric($channelId)) {
            return;
        }

        print_r($channelId."\n");

        $channelName = ChannelService::getChannelNicknameById($channelId);

        //["已打款", "手动已打款"]
        $yesterday_amount = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', $channelId)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        //["已打款", "手动已打款"]
        $yesterday_amount_num = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', $channelId)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->count('amount');
        $yesterday_amount_person = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', $channelId)
            ->where('is_company', 0)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        //["已打款", "手动已打款"]
        $yesterday_amount_person_num = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', $channelId)
            ->where('is_company', 0)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->count('amount');
        $yesterday_amount_company = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', $channelId)
            ->where('is_company', 1)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        //["已打款", "手动已打款"]
        $yesterday_amount_company_num = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', $channelId)
            ->where('is_company', 1)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->count('amount');
        //["已打款", "手动已打款"]
        $yesterday_tallage = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(30))
            ->where('distribution_channel_id', $channelId)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('tallage');

        //["审核不通过"]
        $yesterday_amount_audit_fail = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(9))
            ->where('distribution_channel_id', $channelId)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        //["审核不通过"]
        $yesterday_amount_audit_fail_num = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(9))
            ->where('distribution_channel_id', $channelId)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->count('amount');

        //["打款失败"]
        $yesterday_amount_fail = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(40))
            ->where('distribution_channel_id', $channelId)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->sum('amount');
        //["打款失败"]
        $yesterday_amount_fail_num = WithdrawCash::whereIn('status', WithdrawCashService::getWithdrawCashStatusStrList(40))
            ->where('distribution_channel_id', $channelId)
            ->where('updated_at','>=',$startDay)
            ->where('updated_at','<=',$endDay)
            ->count('amount');

        $date = date('Y-m-d', strtotime(date("Y-m-d")." -1 day"));

        $data['distribution_channel_id'] = $channelId;
        $data['distribution_channel_name'] = $channelName;
        $data['amount'] = $yesterday_amount;
        $data['amount_num'] = $yesterday_amount_num;
        $data['amount_person'] = $yesterday_amount_person;
        $data['amount_person_num'] = $yesterday_amount_person_num;
        $data['amount_company'] = $yesterday_amount_company;
        $data['amount_company_num'] = $yesterday_amount_company_num;
        $data['amount_audit_fail'] = $yesterday_amount_audit_fail;
        $data['amount_audit_fail_num'] = $yesterday_amount_audit_fail_num;
        $data['amount_fail'] = $yesterday_amount_fail;
        $data['amount_fail_num'] = $yesterday_amount_fail_num;
        $data['tallage'] = $yesterday_tallage;

        $data['date'] = $date;

//        print_r($channelId."=".$channelName."=".$yesterday_amount."\n");
        $dataDB = PaymentStatisticService::addPaymentStatistics($data);
    }











    /**
     *  用户提现手续费
     * @param $channelId
     * @param $amount
     * @return int
     */
    public static function getWithdrawCashTallage($channelId, $amount) {
        //TODO 根据条件算出提现扣税金额
        $tallage = 0;
        return $tallage;
    }
}