<?php

namespace Modules\Linker\Models;

use App\Models\Model;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\SoftDeletes;

class Linker extends Model
{

    use Cachable,
        SoftDeletes;

    protected $table = 'linkers';

    protected $casts = [
        'params' => 'json',
    ];

    const TYPE_WEB               = 'web';
    const TYPE_MINI              = 'mini';
    const TYPE_APP_NAVIGATE_TO   = 'navigateTo';
    const TYPE_APP_REDIRECT_TO   = 'redirectTo';
    const TYPE_APP_RE_LAUNCH     = 'reLaunch';
    const TYPE_APP_SWITCH_TAB    = 'switchTab';
    const TYPE_APP_NAVIGATE_BACK = 'navigateBack';

    const TYPES = [
        self::TYPE_WEB               => '网页连接(web)',
        self::TYPE_MINI              => '小程序中跳转',
        self::TYPE_APP_NAVIGATE_TO   => 'APP内部页面转跳',
        self::TYPE_APP_REDIRECT_TO   => '跳转内部页面(关闭当前页)',
        self::TYPE_APP_RE_LAUNCH     => '跳转内部页面(关闭所有页面)',
        self::TYPE_APP_SWITCH_TAB    => 'TAB跳转(关闭所有非TAB页面)',
        self::TYPE_APP_NAVIGATE_BACK => 'APP页面返回',
    ];

    const MODE_APPEND   = 'append';
    const MODE_REPLACE  = 'replace';
    const MODE_OVERRIDE = 'override';

    const MODES = [
        self::MODE_APPEND   => '追加',
        self::MODE_REPLACE  => '替换',
        self::MODE_OVERRIDE => '覆盖',
    ];

    /**
     * Notes   : 转换链接到实际输出
     * @Date   : 2021/6/21 4:03 下午
     * @Author : < Jason.C >
     * @param  \Modules\Linker\Models\LinkerRelation  $relation
     * @return array
     */
    public function getResource(LinkerRelation $relation): array
    {
        $params = '';

        if (is_array($this->params)) {
            if ($relation->params) {
                switch ($relation->mode) {
                    case self::MODE_APPEND:
                        $this->params = array_merge($this->params, $relation->params);
                        break;
                    case self::MODE_REPLACE:
                        $this->params = array_replace($this->params, $relation->params);
                        break;
                    case self::MODE_OVERRIDE;
                        $this->params = $relation->params;
                        break;
                }
            }
            $params = http_build_query($this->params);
        }

        $data = [
            'path'     => $this->url,
            'openType' => $this->type,
            'url'      => $this->url,
            'params'   => $params,
        ];
        switch ($data['openType']) {
            case self::TYPE_WEB:
                $data['path']   = '';
                $data['url']    .= '?' . $data['params'];
                $data['params'] = '';
                break;
            case self::TYPE_APP_NAVIGATE_BACK:
                $data['path']   = '';
                $data['url']    = '';
                $data['params'] = '';
                break;
            default:
                $data['url'] = '';
                break;
        }

        return $data;
    }

}