<?php

namespace Modules\Callback\Http\Controllers;

use Catch\Base\CatchController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Callback\Services\TiktokEventReportService;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;

class CallbackLogController extends CatchController
{
    use ValidatesRequests;

    /**
     * 回传日志列表
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Support\Collection
     */
    public function list(Request $request) {
        $advertiserId = $request->input('advertiser_id');
        $uid = $request->input('uid');
        $advPromotionId = $request->input('adv_promotion_id');
        $userRanseStartAtBeginTime = $request->input('user_ranse_start_at_begin_time');
        $userRanseStartAtEndTime = $request->input('user_ranse_start_at_end_time');
        $orderCreatedAtBeginTime = $request->input('order_created_at_begin_time');
        $orderCreatedAtEndTime = $request->input('order_created_at_end_time');
        $miniprogramId = $request->input('miniprogram_id');
        $isExport = $request->input('is_export', false);

        $sql = DB::table('callback_report_charge_record')
            ->where([
                'optimizer_uid' => $this->getLoginUserId()
            ])->when($advertiserId, function ($query, $advertiserId) {
                return $query->where('advertiser_id', $advertiserId);
            })->when($uid, function ($query, $uid) {
                return $query->where('uid', $uid);
            })->when($advPromotionId, function ($query, $advPromotionId){
                return $query->where('adv_promotion_id', $advPromotionId);
            })->when($userRanseStartAtBeginTime, function ($query, $userRanseStartAtBeginTime){
                return $query->where('user_ranse_start_at', '>=', $userRanseStartAtBeginTime);
            })->when($userRanseStartAtEndTime, function ($query, $userRanseStartAtEndTime){
                return $query->where('user_ranse_start_at', '<=', $userRanseStartAtEndTime . ' 23:59:59');
            })->when($orderCreatedAtBeginTime, function ($query, $orderCreatedAtBeginTime){
                return $query->where('order_created_at', '>=', $orderCreatedAtBeginTime);
            })->when($miniprogramId, function ($query, $miniprogramId){
                return $query->where('miniprogram_id', $miniprogramId);
            })
            ->when($orderCreatedAtEndTime, function ($query, $orderCreatedAtEndTime) {
                return $query->where('order_created_at', '<=', $orderCreatedAtEndTime. ' 23:59:59');
            })->orderBy('created_at', 'desc');
   
        if($isExport) {
            $result = $sql->get();
        } else {
            $result = $sql->paginate($request->integer('limit', 15));
        }
        $advertisers = DB::table('juliang_account_callback_config')
            ->where('company_uid', $this->getLoginUserId())
            ->select('adv_account_id', 'adv_account_name')
            ->get()->keyBy('adv_account_id');
        $reportSuccessStr = [
            0 => '回传失败',
            1 => '回传成功',
            2 => '补传成功',
        ];
        foreach ($result as $item) {
            $item->advertiser_name = $advertisers->get($item->advertiser_id ?? -1)->adv_account_name ?? '';
            if('ok' == $item->filter_type ) {
                $item->filter_reason .= '-'. $reportSuccessStr[$item->report_success] ?? '';
            }

            if('ok' == $item->filter_type && (0 != $item->report_success)) {
                $item->filter_type_str = '成功';
            } else {
                $item->filter_type_str = '失败';
            }
        }

        return $result;
    }

    /**
     * 补传
     * @param Request $request
     * @return string
     * @throws \Illuminate\Validation\ValidationException
     */
    public function callbackAgain(Request $request) {
        $this->validate($request, ['log_id' => 'required']);
        $logId = $request->integer('log_id');

        $record = DB::table('callback_report_charge_record')
            ->where('id', $logId)
            ->select('report_param')
            ->first();
        if(!$record || !$record->report_param) {
            CommonBusinessException::throwError(Errors::CALLBACK_RECORD_NOT_EXISTS);
        }

        $requestInfo = \json_decode($record->report_param);
        if(!$requestInfo) {
            CommonBusinessException::throwError(Errors::CALLBACK_RECORD_LOG_ERROR);
        }

        $reportService = new TiktokEventReportService();
        $result = $reportService->reportCharge($requestInfo);
        $reportSuccess = 0;
        if($result['result']) {
            $resultContent = \json_decode($result['content'], true);
            if(0 == $resultContent['code']) {
                $reportSuccess = 2;
            }
        }
        DB::table('callback_report_charge_record')
            ->where('id', $logId)
            ->update([
                'report_result' => \json_encode($result),
                'report_success' => $reportSuccess,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

        return 2 == $reportSuccess ? '补传成功' : '补传失败';
    }
}
