<?php

namespace BYDAuto\Commands;

use BYDAuto\Foundation\AlipayEasySDKFactory;
use BYDAuto\Models\PromotePage;
use BYDAuto\Models\Testdrive;
use Carbon\Carbon;
use Illuminate\Console\Command;

/**
 * 支付宝自建推广页留资数据查询.
 */
class AliPromotepageCommand extends Command
{
    protected $signature = 'bydauto:promotepage';

    protected $description = '查询自建推广页列表';

    public function handle()
    {
        $this->sync();
    }

    public function sync()
    {
        $this->info('===== 开始同步推广页列表');
        info('===== 开始同步推广页列表');
        $this->batchquery();
        $pages = PromotePage::query()->get();
        foreach ($pages as $page) {
            $this->download($page->page_id);
        }
        return Command::SUCCESS;
    }

    /**
     * 自建推广页留资数据查询
     * https://opendocs.alipay.com/open/1df3222a_alipay.data.dataservice.ad.promotepage.download?scene=common&pathHash=734c25f8.
     * @param mixed $promote_page_id
     */
    public function download($promote_page_id)
    {
        $textParams = [];
        $bizParams['principal_tag'] = config('bydauto.adops.principal_tag');
        $bizParams['biz_token'] = config('bydauto.adops.biz_token');
        $bizParams['page_no'] = 1;
        $bizParams['page_size'] = 1000;
        $bizParams['promote_page_id'] = $promote_page_id;
        $bizParams['start_date'] = Carbon::now()->subDays(2)->format('Y-m-d');
        $bizParams['end_date'] = Carbon::now()->format('Y-m-d');

        $message = sprintf('===== 开始同步推广页留资数据：[页面ID] %s [开始日期] %s [结束日期] %s', $promote_page_id, $bizParams['start_date'], $bizParams['end_date']);
        $this->info($message);
        info($message);

        try {
            $this->info('===== 正在查询第 1 页');
            info('===== 正在查询第 1 页');
            $result = (new AlipayEasySDKFactory())->execute('alipay.data.dataservice.ad.promotepage.download', $textParams, $bizParams);
            if ($result->code === '10000') {
                $body = json_decode($result->httpBody, true);
                $resp = $body['alipay_data_dataservice_ad_promotepage_download_response'] ?? [];

                $respTotal = $resp['total'] ?? 0;
                $respList = $resp['list'] ?? [];
                if ($respTotal > 0) {
                    $items = collect($respList);
                    $items->each(fn ($item) => Testdrive::syncFromAliPromote($item, $promote_page_id));
                    $this->info('===== 同步完成, 共 ' . $items->count() . ' 条数据');
                    info('===== 同步完成, 共 ' . $items->count() . ' 条数据');
                }

                // Check if there are more pages to query
                $respTotal = $body['alipay_data_dataservice_ad_promotepage_download_response']['total'];
                $totalPages = ceil($respTotal / $bizParams['page_size']);
                if ($totalPages > 1) {
                    for ($page = 2; $page <= $totalPages; ++$page) {
                        $this->info('===== 正在查询第 ' . $page . ' 页');
                        info('===== 正在查询第 ' . $page . ' 页');
                        $bizParams['page_no'] = $page;
                        $result = (new AlipayEasySDKFactory())->execute('alipay.data.dataservice.ad.promotepage.download', $textParams, $bizParams);
                        if ($result->code === '10000') {
                            $body = json_decode($result->httpBody, true);
                            $items = collect($body['alipay_data_dataservice_ad_promotepage_download_response']['list']);
                            $items->each(fn ($item) => Testdrive::syncFromAliPromote($item, $promote_page_id));
                            $this->info('===== 同步完成, 共 ' . $items->count() . ' 条数据');
                            info('===== 同步完成, 共 ' . $items->count() . ' 条数据');
                        }
                    }
                }
            }
        } catch (\Throwable $th) {
            info('===== 自建推广页留资数据查询失败：');
            info($th->getMessage());
            $this->error($th->getMessage());
        }
    }

    /**
     * 自建推广页查询
     * https://opendocs.alipay.com/open/e060c7d1_alipay.data.dataservice.ad.promotepage.batchquery?scene=common&pathHash=ecc1df2f.
     */
    public function batchquery()
    {
        $textParams = [];
        $bizParams['principal_tag'] = config('bydauto.adops.principal_tag');
        $bizParams['biz_token'] = config('bydauto.adops.biz_token');
        $bizParams['page_no'] = 1;
        $bizParams['type'] = "COLLECT_INFO";
        $bizParams['page_size'] = 100;

        try {
            $result = (new AlipayEasySDKFactory())->execute('alipay.data.dataservice.ad.promotepage.batchquery', $textParams, $bizParams);
            if ($result->code === '10000') {
                $body = json_decode($result->httpBody, true);
                $pages = collect($body['alipay_data_dataservice_ad_promotepage_batchquery_response']['list']);
                $pages->map(function ($page) {
                    PromotePage::query()->updateOrCreate(['page_id' => $page['id']], [
                        'name' => $page['name'],
                        'type' => $page['type'],
                        'property_list' => json_encode($page['property_list'], JSON_UNESCAPED_UNICODE),
                    ]);
                });
                $this->table(['id', 'name', 'type'], $pages->map(function ($page) {
                    return ['id' => $page['id'], 'name' => $page['name'], 'type' => $page['type']];
                }));
            }
        } catch (\Exception $e) {
            // ...
            $this->error($e->getMessage());
        }
    }
}
