<?php

namespace App\Console\Commands\Jiesuan;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Modules\Jiesuan\Services\CompanyUserMoneyService;
use Modules\Jiesuan\Services\ConstService;

class CompanyChargeDayJiesuan extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Jiesuan:CompanyChargeDayJiesuan {--date= : 结算日期}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '投放公司每日充值结算';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $date = $this->option('date');
        $chargeInfos = DB::table('orders')
            ->where('created_at', '>=', $date)
            ->where('created_at', '<=', $date . ' 23:59:59')
            ->where('status', '<>', 'UNPAID')
            ->where('puser_id', '<>', 0)
            ->select(
                'puser_id',
                DB::raw('sum(price) as charge_money')
            )->groupBy('puser_id')
            ->get()->keyBy('puser_id');
        $tuikuanInfos = $this->getTuikuanInfo($date);


        $puserIds = $chargeInfos->pluck('puser_id')->merge($tuikuanInfos->pluck('puser_id'))->unique();

        if($puserIds->isNotEmpty()) {
            $jiesuanInfo = collect();
            foreach ($puserIds as $puserId) {
                $jiesuanInfo->put($puserId, (object)[
                    'charge_money' => $chargeInfos->get($puserId)->charge_money ?? 0,
                    'tuikuan_money' => $tuikuanInfos->get($puserId)->tuikuan_money ?? 0,
                ]);
            }
            $defaultShareRate = DB::table('company_share_rates')->where('company_uid', 0)->value('share_rate') ?? '89.1';
            $now = date('Y-m-d H:i:s');
            $puserIds->chunk(2)->map(function ($item) use ($jiesuanInfo, $defaultShareRate, $date, $now){
                    $rates = DB::table('company_share_rates')->whereIn('company_uid', $item)
                        ->select('company_uid', 'share_rate')
                        ->get()->keyBy('company_uid');
                    $insertData = [];
                    foreach ($item as $i) {
                        $share_rate = $rates->get($i)->share_rate ?? $defaultShareRate;
                        $jiesuanInfo->get($i)->share_rate = $share_rate;
                        $jiesuanInfo->get($i)->jiesuan_money =
                            intval(($jiesuanInfo->get($i)->charge_money - $jiesuanInfo->get($i)->tuikuan_money) * $share_rate) / 100;
                        $jiesuanInfo->get($i)->tuikuan_money = intval($jiesuanInfo->get($i)->tuikuan_money * $share_rate) / 100;

                        $insertData[] = [
                            'company_uid' => $i,
                            'jiesuan_date' => $date,
                            'charge_money' => $jiesuanInfo->get($i)->charge_money,
                            'tuikuan_money' => $jiesuanInfo->get($i)->tuikuan_money,
                            'share_rate' => $jiesuanInfo->get($i)->share_rate,
                            'jiesuan_money' => $jiesuanInfo->get($i)->jiesuan_money,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];
                    }

                DB::transaction(function () use ($insertData, $now){
                       DB::table('jiesuan_records')->insert($insertData);
                       foreach ($insertData as $item) {
                           $beforeUserMoneyInfo = CompanyUserMoneyService::userMoneyInfo($item['company_uid']);
                           $companyUserMoney = DB::table('company_user_money')
                               ->where('company_uid', $item['company_uid'])->first();
                           if($companyUserMoney) {
                               $afterTotalIncome = bcadd($companyUserMoney->total_income, $item['charge_money'], 2);
                               DB::table('company_user_money')
                                   ->where(['company_uid' => $item['company_uid']])
                                   ->update([
                                       'total_income' => $afterTotalIncome,
                                       'total_tuikuan' => bcadd($companyUserMoney->total_tuikuan, $item['tuikuan_money'], 2),
                                       'updated_at' => $now
                                   ]);
                           } else {
                               $afterTotalIncome = $item['charge_money'];
                               DB::table('company_user_money')
                                   ->insert([
                                       'company_uid' => $item['company_uid'],
                                       'total_income' => $afterTotalIncome,
                                       'total_tuikuan' => $item['tuikuan_money'],
                                       'created_at' => $now, 'updated_at' => $now,
                                   ]);
                           }
                           $currentUserMoneyInfo = CompanyUserMoneyService::userMoneyInfo($item['company_uid']);
                           CompanyUserMoneyService::log($item['company_uid'], ConstService::MONEY_CHANGE_TYPE_DAY_JIESUAN,
                               $beforeUserMoneyInfo, $currentUserMoneyInfo);
                       }
                   });
            });


        }

    }

    private function getTuikuanInfo($date) {
        return DB::table('orders_refund_verify')
            ->where(['refund_status' => 1])
            ->where('pay_at', '>=', $date)
            ->where('pay_at', '<=', $date. ' 23:59:59')
            ->where('puser_id', '<>', 0)
            ->select(
                'puser_id',
                DB::raw('sum(refund_price) as tuikuan_money')
            )->groupBy('puser_id')
            ->get()->keyBy('puser_id');
    }
}
