<?php

namespace App\Distributor\Controllers;

use App\Distributor\Actions\SmmAddAccount;
use App\Distributor\Repositories\SmmUserAccount;
use App\Services\SmmService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;
use Illuminate\Http\Request;

class SmmUserAccountController extends AdminDistController
{
    /**
     * page index
     */
    public function index(Content $content)
    {
        return $content
            ->header('帐号管理')
            ->description('全部')
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new SmmUserAccount(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('name')->tree();
            $grid->column('access_token');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('user_name')->width(2);
            });
            // 传入数组
            $grid->rightTools([
            //    new SmmAddAccount(),
            ]);

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableQuickEdit();
                $actions->disableView();
                $dist_id = $actions->row->dist_id;
                if ($dist_id == 0) {
                    $actions->append(new SmmAddAccount());
                    $actions->disableDelete();
                }
            });

            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->disableViewButton();
            $grid->model()->whereIn('dist_id', [0,getDistributorId()])->orderBy('name', 'asc')->orderBy('id', 'desc');
        });
    }


    /*
     * 社媒回调接口
     */
    public function callback($mediaName,Request $request)
    {
        try {
            $ssmService = new SmmService($mediaName);
            $result = $ssmService->loginCallback($request);
           // dd($result);
            if ($result['status']) {
                $accessToken = $result['data']['access_token'];
                $userName = $result['data']['user_name'];
                $userId = $result['data']['user_id'];
                SmmUserAccount::createAccountIfMediaExists($mediaName, $userId,$userName, $accessToken);
                return response()->json(['code' => 1, 'msg' => 'success']);
            } else {
                return response()->json(['code' => 0,'msg' => $result['data']]);
            }
        } catch (\Exception $e) {
            return response()->json(['code' => 0,'msg' => 'error'.$e->getMessage()]);
        }
    }



}
