<?php

namespace app\admin\controller\embed;

use app\admin\model\Config as ConfigModel;
use app\admin\model\Game;
use app\admin\model\Provider;
use app\common\service\JK8Services;
use think\facade\Db;
use app\common\controller\Backend;
use Throwable;

class Embed extends Backend
{
    /**
     * @var object
     * @phpstan-var Embed
     */
    protected object $model;
    protected $jk8Services;

    // 排除字段
    protected string|array $preExcludeFields = ['create_time'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new Game();
        $this->jk8Services = app(JK8Services::class);
    }

    public function gameRtp()
    {
        $provider = $this->request->param('provider');
        $gameName = $this->request->param('game_name');
        $limit = request()->param('limit/d') ?? 15;

        $where = [];
        if (!empty($provider)) {
            $where[] = ['provider_site', '=', $provider];
        }
        if (!empty($gameName)) {
            $where[] = ['game_name', 'LIKE', '%'. $gameName . '%'];
        }
        $rtpSetting = Db::name('game_rtp_setting')->order('id', 'desc')->find();
        $res = $this->model->where($where)
            ->order('id', 'desc')
            ->paginate($limit);

        $this->success('', [
            'rtp_setting' => $rtpSetting,
            'provider' => Provider::column('site'),
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function saveGameRtp()
    {
        $params = $this->request->post();

        if (!is_array($params['auto_rtp_amount'])) {
            $autoRtpAmount = '{"max":"90","min":"30"}';
        } else {
            $autoRtpAmount = json_encode($params['auto_rtp_amount']);
        }

        if (!is_array($params['provider_display'])) {
            $providerDisplay = '';
        } else {
            $providerDisplay = json_encode($params['provider_display']);
        }
        if (!is_array($params['custom_config'])) {
            $customConfig = '';
        } else {
            if (is_array($params['custom_config']['customGameRTP'])) {
                foreach ($params['custom_config']['customGameRTP'] as $v) {
                    $min = isset($v['min']) ? intval($v['min']) : 30;
                    $max = isset($v['max']) ? intval($v['max']) : 90;
                    $individualRtp = mt_rand($min, $max);
                    if ($v['gameId']) {
                        Db::name('game')->where('id', $v['gameId'])->update([
                            'rtp' => $individualRtp,
                            'update_time' => time()
                        ]);
                    }
                }
            }
            if (is_array($params['custom_config']['providerNameMapping'])) {
                foreach ($params['custom_config']['providerNameMapping'] as $k => $v) {
                    Db::name('game')->where('provider_site', $k)->update([
                        'provider_name' => $v,
                        'update_time' => time()
                    ]);

                }
            }
            $customConfig = json_encode($params['custom_config']);
        }

        // 组装需要存储的数据
        $data = [
            'auto_game_rtp'         => $params['auto_game_rtp'] ?? 'OFF',
            'auto_rtp_amount'       => $autoRtpAmount,
            'auto_frequency'        => intval($params['auto_frequency'] ?? 10),
            'provider_display'      => $providerDisplay,
            'custom_config'         => $customConfig,
            'header_image_url'      => $params['header_image_url'] ?? '',
            'text_color'            => $params['text_color'] ?? '',
            'button_text_color'     => $params['button_text_color'] ?? '',
            'base_color'            => $params['base_color'] ?? '',
            'button_bg_color'       => $params['button_bg_color'] ?? '',
            'outline_color'         => $params['outline_color'] ?? '',
            'progress_bar_bg_color' => $params['progress_bar_bg_color'] ?? '',
            'update_time'           => time(),
            'last_execute_time'     => null,
        ];

        // 查找是否存在配置，存在则更新，不存在则写入第一条
        $info = Db::name('game_rtp_setting')->order('id', 'desc')->find();
        if ($info) {
            Db::name('game_rtp_setting')->where('id', $info['id'])->update($data);
        } else {
            Db::name('game_rtp_setting')->insert($data);
        }

        $this->success(__('Added successfully'));
    }

    public function addGame()
    {
        $params = $this->request->post();
        $data['provider_site'] = $params['provider_site'];
        $data['game_name'] = $params['game_name'];
        $data['game_code'] = '';
        $data['image_url'] = $params['image_url'];
        $data['rtp'] = $params['rtp'];
        $data['status'] = $params['status'];
        $data['create_time'] = time();

        $result = $this->model->save($data);

        if ($result !== false) {
            $this->success(__('Added successfully'));
        } else {
            $this->error(__('No rows were added'));
        }
    }

    public function editGame(): void
    {
        $id  = $this->request->param('id');
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $data = $this->request->post();
        if (!$data) {
            $this->error(__('Parameter %s can not be empty', ['']));
        }

        $result = false;
        $this->model->startTrans();
        try {
            $result = $row->save($data);
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $this->success(__('Update successful'));
        } else {
            $this->error(__('No rows updated'));
        }
    }

    public function domainStatus()
    {
        $this->success('', [
            'domain'   => Db::name('domain_status_setting')->order('id', 'desc')->find(),
            'domain_list' => ConfigModel::where('group', 'basics')->where('name', 'website_domain')->value('value'),
        ]);
    }

    public function saveDomain()
    {
        $params = $this->request->post();

        if (!is_array($params['custom_config'])) {
            $customConfig = '';
        } else {
            $customConfig = json_encode($params['custom_config']);
        }
        // 组装需要存储的数据
        $data = [
            'header_image_url'      => $params['header_image_url'] ?? '',
            'custom_config'         => $customConfig,
            'base_color'            => $params['base_color'] ?? '',
            'border_color'          => $params['border_color'] ?? '',
            'online_color'          => $params['online_color'] ?? '',
            'offline_color'         => $params['offline_color'] ?? '',
            'title_color'           => $params['title_color'] ?? '',
            'text_color'            => $params['text_color'] ?? '',
            'tag_color'             => $params['tag_color'] ?? '',
            'update_time'           => time()
        ];

        // 查找是否存在配置，存在则更新，不存在则写入第一条
        $info = Db::name('domain_status_setting')->order('id', 'desc')->find();
        if ($info) {
            Db::name('domain_status_setting')->where('id', $info['id'])->update($data);
        } else {
            Db::name('domain_status_setting')->insert($data);
        }

        $this->success(__('Added successfully'));
    }

    public function partnership()
    {
        $this->success('', [
            'partnership_setting'   => Db::name('partnership_setting')->order('id', 'desc')->find(),
            'partner_data' => [],
        ]);
    }

    public function savePartnershipSet()
    {
        $params = $this->request->post();

        if (!is_array($params['footer_config'])) {
            $footerConfig = '';
        } else {
            $footerConfig = json_encode($params['footer_config']);
        }
        if (!is_array($params['custom_config'])) {
            $customConfig = '';
        } else {
            $customConfig = json_encode($params['custom_config']);
        }

        // 组装需要存储的数据
        $data = [
            'header_image_url'      => $params['header_image_url'] ?? '',
            'footer_config'         => $footerConfig,
            'custom_config'         => $customConfig,
            'base_color_1'          => $params['base_color_1'] ?? '',
            'base_color_2'          => $params['base_color_2'] ?? '',
            'border_color'          => $params['border_color'] ?? '',
            'highlight_color'       => $params['highlight_color'] ?? '',
            'title_color'           => $params['title_color'] ?? '',
            'text_color'            => $params['text_color'] ?? '',
            'update_time'           => time()
        ];

        // 查找是否存在配置，存在则更新，不存在则写入第一条
        $info = Db::name('partnership_setting')->order('id', 'desc')->find();
        if ($info) {
            Db::name('partnership_setting')->where('id', $info['id'])->update($data);
        } else {
            Db::name('partnership_setting')->insert($data);
        }

        $this->success(__('Added successfully'));
    }
}