<?php

namespace App\Admin\Controllers;

use App\Jobs\CheckCouponByLog;
use App\Jobs\CheckCouponLog;
use App\Models\Coupon;
use App\Models\Log;
use Carbon\Carbon;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use XuanChen\Coupon\Action\pingan\Verification;

class TestController
{

    public function index(Request $request)
    {
        $str  = Str::uuid();
        $date = $request->date ?? date('Y-m-d');
        $time = Carbon::parse($date);

        $all    = Coupon::where('status', 2)
            ->whereBetween('created_at', [
                $time->startOfDay()->toDateTimeString(),
                $time->endOfDay()->toDateTimeString(),
            ])
            ->count();
        $self   = Coupon::where('status', 2)
            ->where('type', Coupon::TYPE_YSD)
            ->whereBetween('created_at', [
                $time->startOfDay()->toDateTimeString(),
                $time->endOfDay()->toDateTimeString(),
            ])
            ->count();
        $pingan = Coupon::where('status', 2)
            ->where('type', Coupon::TYPE_PINGAN)
            ->whereBetween('created_at', [
                $time->startOfDay()->toDateTimeString(),
                $time->endOfDay()->toDateTimeString(),
            ])
            ->count();

        $error = Coupon::where('status', 3)
            ->whereBetween('created_at', [
                $time->startOfDay()->toDateTimeString(),
                $time->endOfDay()->toDateTimeString(),
            ])
            ->count();

        $lists = DB::table('coupons')
            ->where('status', 2)
            ->whereBetween('created_at', [
                $time->startOfDay()->toDateTimeString(),
                $time->endOfDay()->toDateTimeString(),
            ])
            ->select('redemptionCode', DB::raw('COUNT(*) as code_count'))
            ->groupBy('redemptionCode')
            ->having('code_count', '>', 1)
            ->get();

        $data = [
            ' 日期为：'.$time->format('Y-m-d'),
            ' 核销总数为：'.$all,
            ' 自有卡券总数为：'.$self,
            ' 平安卡券总数为：'.$pingan,
            ' 核销错误总数为：'.$error,
            ' 核销重复数据数为：'.$lists->count(),
        ];

        foreach ($data as $info) {
            dump($info);
        }

    }

    /**
     * Notes: 设置日志关联
     *
     * @Author: 玄尘
     * @Date: 2022/1/19 11:12
     * @param  \Illuminate\Http\Request  $request
     */
    public function coupon(Request $request)
    {
        $type = $request->type ?? '';
        $date = $request->date ?? '';

        if (! $type) {
            dd('type 错误');
        }

        if (! $date) {
            dd('date 错误');
        }

        $name = 'api_log_'.$date;//表名
        if (! Schema::hasTable($name)) {
            dd('数据表不存在');
        }

        if (! Schema::hasColumn($name, 'coupon_no')) {
            Schema::table($name, function (Blueprint $table) {
                $table->string('coupon_no')->after('out_source')->nullable();
            });
        }

        /**
         * 设置日志
         */
        if ($type == 'log') {

            (new Log())->setTable($name)
                ->whereNull('coupon_no')
                ->where('path', 'http://api.pingan.com.cn/open/vassPartner/appsvr/property/api/new/partner/redemption')
                ->where('out_source->code', 200)
                ->chunkById(1000, function ($logs) use ($name) {
                    foreach ($logs as $log) {
                        $data = (new Verification())->decrypt($log->in_source['json']['data']);
                        $data = json_decode($data, true);
                        $log->update([
                            'coupon_no' => $data['couponNo']
                        ]);

                    }
                });

            dd($name.' 表日志设置完成');

        }

        if ($type == 'coupon') {
            (new Log())->setTable($name)
                ->whereHas('coupon', function ($q) {
                    $q->whereNull('pa_order_id');
                })
                ->where('path', 'http://api.pingan.com.cn/open/vassPartner/appsvr/property/api/new/partner/redemption')
                ->where('out_source->code', 200)
                ->chunkById(1000, function ($logs) use ($name) {
                    foreach ($logs as $log) {
                        $log->coupon->update([
                            'pa_order_id'     => $log->out_source['data']['orderId'],
                            'pa_sub_order_id' => $log->out_source['data']['subOrderId'],
                        ]);
                    }
                });

            dd($name.' 表关联的优惠券设置完成');
        }


        dd(1);
    }

    /**
     * Notes: 设置数据
     *
     * @Author: 玄尘
     * @Date: 2022/1/19 13:29
     */
    public function checkCouponLog(Request $request)
    {
        $type = $request->type ?? '';

        if (! $type) {
            dd('type 错误');
        }

        $tables = DB::connection()->getDoctrineSchemaManager()->listTableNames();

        foreach ($tables as $table) {

            if (Str::contains($table, 'api_log_')) {
                echo " 开始处理 ".$table."  <br>";

                if (! Schema::hasColumn($table, 'coupon_no')) {
                    Schema::table($table, function (Blueprint $table) {
                        $table->string('coupon_no')->after('out_source')->nullable();
                    });
                }

                if ($type == 'log') {
                    CheckCouponLog::dispatch($table);
                }

                if ($type == 'coupon') {
                    CheckCouponByLog::dispatch($table);
                }


            }
        }
    }

}
