<?php
namespace App\Distributor\Actions;

use App\Distributor\Forms\ImportProduct;
use App\Services\SmmService;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Grid\Tools\AbstractTool;
use Dcat\Admin\Widgets\Modal;
use App\Distributor\Forms\SmmAddAccount as SmmAddAccountForm;
use Illuminate\Http\Request;

class SmmAddAccount extends RowAction
{
    protected $title = null;
    //媒体名称
    protected $mediaName = null;
    /**
     * 返回字段标题
     *
     * @return string
     */
    public function title()
    {
        if ($this->title) {
            return $this->title;
        }
        return admin_trans_label('add_platform_account');
    }

    public function setData($title,$mediaName)
    {
        $this->title = $title;
        $this->mediaName = $mediaName;
    }

    /**
     * 处理请求
     *
     */
    public function handle(Request $request)
    {
        // 获取 parameters 方法传递的参数
        $name = $request->get('name');
        if ($name) {
            //跳转到媒体受权页面
            $ssmService = new SmmService($name);
            $result = $ssmService->login();
            if ($result['status']) {
                // 返回 JS 代码触发新窗口打开
                $url = $result['data']['url'];

                return $this->response()->script(
                    "window.open('{$url}', '_blank')"
                );
            }
            return $this
                ->response()
                ->error('获取授权失败，请检查媒体名称是否正确!');
        } else {
            return $this
                ->response()
                ->error('媒体名称不能为空');
        }
    }

    public function parameters()
    {
        if ($this->mediaName) {
            return [
                'name' => $this->mediaName,
            ];
        } else {
            return [
                // 发送当前行 username 字段数据到接口
                'name' => $this->row->name,
            ];
        }
    }

}
