<?php
/**
 *  广告修改书籍获取接口
 * @file:AdReplaceBookController.php
 * @Created by gnitif
 * @Date: 2022/9/27
 * @Time: 10:44
 */


namespace App\Http\Controllers\QuickApp\SendOrder;

use App\Http\Controllers\QuickApp\BaseController;
use App\Modules\Book\Models\Chapter;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Channel\Services\QappSendOrderContentShieldConfigService;
use App\Modules\SendOrder\Models\QappSendOrder;
use App\Modules\SendOrder\Services\SendOrderService;
use Illuminate\Http\Request;
use Cookie;
use Illuminate\Support\Facades\DB;
use Redis;

class AdReplaceBookController extends BaseController
{

    private $send_order_id;
    private $package;

    public function getAdvReplaceBookInfo(Request $request)
    {
        $book = [];
        try {
            $package = $request->header('x-package', '');
            // 暂时关闭浩瀚书籍替换
            if (!in_array($package,  [ "com.beidao.kuaiying.haohannew" , "com.beidao.kuaiying.haohan"])) {
                $send_order_id = $request->input('send_order_id', 0);
                $book = $this->sendOrderBookReplace($send_order_id);
                if ($book) $book['bid'] = str_encode($book['bid']);
            }
        } catch (\Exception $exception) {
            $book = [];

        }
        return response()->success($book);
    }

    /**
     * ip屏蔽书籍替换
     * name: advShield
     * @param Request $request
     * @return mixed
     * date 2023/02/15 14:52
     */
    public function advShield(Request $request)
    {
        try {
            $this->send_order_id = $request->input('send_order_id', 0);
            $this->package = $request->input('package');
            $checkout_tx = strtolower($request->input('checkout_tx', '')); // 腾讯非广告
            $platform = strtolower($request->input('platform', '')); // 投放平台小写
            $send_order = SendOrderService::getSendOrderStatic($this->send_order_id);
            $this->sendOrderStatistic($send_order); // 统计
            $doShied = $this->getRealBookInfo($checkout_tx, $platform);

            if ($doShied) {
                $doShied['bid'] = str_encode($doShied['bid']);
            }else{
                $doShied = [];
            }


        } catch (\Exception $exception) {
            $doShied = [];
        }
        return response()->success($doShied);
    }

    /***
     *  派单统计
     * name: sendOrderStatistic
     * @param $send_order
     * date 2023/02/15 11:13
     */
    private function sendOrderStatistic($send_order)
    {
        $key = date('Y-m-d');
        $send_order_flag = Cookie::get('send_order_flag');
        $send_orders = explode(',', trim($send_order_flag, ','));

        //uv
        if (!Cookie::get('send_order_flag_' . $this->send_order_id) && !in_array($this->send_order_id, $send_orders)) {
            Redis::hincrby('send_order_uv_' . $this->send_order_id, $key, 1);
            Redis::hincrby('send_order_uv_' . $this->send_order_id, 'total', 1);
            array_push($send_orders, $this->send_order_id);
            $str = implode(',', $send_orders);
            Cookie::queue('send_order_flag', $str, env('U_COOKIE_EXPIRE'), null, null, false, false);
        }

        if (Cookie::get('send_order_flag_' . $this->send_order_id)) {
            array_push($send_orders, $this->send_order_id);
            $str = implode(',', $send_orders);
            Cookie::queue('send_order_flag', $str, env('U_COOKIE_EXPIRE'), null, null, false, false);
            Cookie::queue('send_order_flag_' . $this->send_order_id, null, -1);
        }
        //pv
        Redis::hincrby('send_order_pv_' . $this->send_order_id, $key, 1); //每天
        Redis::hincrby('send_order_pv_' . $this->send_order_id, 'total', 1); //汇总
        Redis::sadd('send_order' . $key, $this->send_order_id);
        if (isset($send_order->send_time) && $send_order->send_time) {
        } else {
            $uv = Redis::hget('send_order_uv_' . $this->send_order_id, $key);
            if ($uv && $uv > 20) {
                SendOrderService::updateSendOrderTime($this->send_order_id);
            }
        }
    }

    /***
     *  获取替换书籍 优级为 系统屏蔽展示书籍-> 腾讯adq非广告用户展示书籍 ->展现备用书籍q
     * name: getRealBookInfo
     * @param mixed $checkout_tx 是否是腾讯adq非广告用户
     * @param mixed $platform 投放平台
     * date 2023/02/15 11:13
     */
    private function getRealBookInfo($checkout_tx = '', $platform = "")
    {

        // 系统ip和城市屏蔽
        $info = QappSendOrderContentShieldConfigService::doShied($this->send_order_id, _getIp());  // 系统书籍屏蔽
        if ($info) {
            return $this->checkoutBookInfo($info);
        }

        // 腾讯非广告用户替换检测
        if ($checkout_tx) {
            $tx_info = $this->getNoAdvBookInfo();
            if ($tx_info) {
                return $this->checkoutBookInfo($tx_info);
            }
        }

        if (!in_array($platform, ['tx_adq', 'tx_adq_new'])) {
            // 派单书籍替换针对非腾讯投放平台
            $send_order_replace_info = $this->sendOrderBookReplace($this->send_order_id);  // 派单替换书籍
            if ($send_order_replace_info) {
                return $this->checkoutBookInfo($send_order_replace_info);
            }
        }

        return [];

    }

    /**
     * 腾讯广告新版,非点击广告访问链接的用户将看到配置的非广告书籍
     * - 如果是通过腾讯adq广告投放的hap链接中,会有腾讯广告那边添加的参数,形如:hap://app/com.beidao.kuaiying.zsy/views/Reader?send_order_id=3402324&bid=5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY&chapter_id=1252&platform=tx_adq_new&back_name=%E5%BE%AE%E8%A7%86&back_pkg=com.tencent.weishi&back_url=weishi%3A%2F%2F
     * - 否则,形如:hap://app/com.beidao.kuaiying.zsy/views/Reader?send_order_id=3521701&bid=PGZq37EQ1brwdgpeyaR8Voa42OXNk6Ap&chapter_id=23655059&platform=huawei_fyp
     */
    private function getNoAdvBookInfo(): array
    {
        $extraConfig = QappSendOrder::where('send_order_id', $this->send_order_id)
            ->where('platform', 'tx_adq_new')
            ->value('extra_config');
        if ($extraConfig) {
            $extraConfigDecode = json_decode($extraConfig, true);
            $bid = str_decode($extraConfigDecode['txAdqNoAdvBid'] ?? '');
            $cid = $extraConfigDecode['txAdqNoAdvCid'] ?? 0;
            if ($bid) {
                return ['bid' => $bid, 'cid' => $cid];
            }
        }
        return [];
    }

    /**
     *  派单书籍替换
     * name: sendOrderBookReplace
     * @param mixed $send_order_id
     * @return array
     * date 2023/02/15 11:08
     */
    private function sendOrderBookReplace($send_order_id = 0): array
    {
        $book = [];
        if ($send_order_id > 0) {
            $extra_config = QappSendOrder::where(['send_order_id' => $send_order_id])->value('extra_config');
            $extra_config = empty($extra_config) ? [] : json_decode($extra_config, true);
            $status = $extra_config['replace_book_status'] ?? 0;
            $bid = $extra_config['replace_book_bid'] ?? "";
            $cid = $extra_config['replace_chapter_cid'] ?? 0;
            if ($status == 1) {
                if (!empty($bid) && !empty($cid)) {
                    $book = ['bid' => str_decode($bid), 'cid' => $cid];
                } else {
                    myLog("SendOrderReplaceBookError")->info(['send_order_id' => $send_order_id, 'extra_config' => $extra_config]);
                }
            }
        }
        return $book;
    }

    private function checkoutBookInfo($info)
    {
        $bid = $info['bid'] ?? 0;
        // 检查书籍是否可用
        if (!BookConfigService::getAvailableBIdsbyBids([$bid], $this->distribution_channel_id)) {
            $info = $this->getAvailableBookInfoByBid($bid); // 获取可用书籍
        }

        return $info;
    }

    /**
     *  获取同频道其他可用书籍,默认女频书(外部上架)
     * name: getAvailableBookInfoByBid
     * @param $bid
     * @return array
     * date 2023/02/15 14:22
     */
    private function getAvailableBookInfoByBid($bid)
    {
        $channel = DB::table('book_categories')->join('books', 'books.category_id', '=', 'book_categories.id')->where('books.id', $bid)->value('book_categories.pid');
        $channel = $channel ?: 2;
        $bids = BookConfigService::getRecommendBids($this->package, $channel, [], 1);
        if ($bids) {
            $bid = $bids[0];
        }
        $cid = Chapter::where('bid', $bid)->orderBy('sequence', 'asc')->value('id');

        return compact('bid', 'cid');
    }


}