<?php

namespace App\Distributor\Controllers;

use App\Distributor\Actions\SmmAddAccount;
use App\Distributor\Repositories\SmmPostLog;
use App\Distributor\Repositories\SmmUserAccount;
use App\Services\SmmService;
use Carbon\Carbon;
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;
use Illuminate\Support\Facades\Session;

class SmmUserAccountController extends AdminDistController
{
    /**
     * page index
     */
    public function index(Content $content)
    {
//        $imgPath = storage_path('app/ssm/1/fc15428f68ea8157bb0c4ea80cfb38d0.png');
//        $ssmService = new SmmService('facebook');
//        $result = $ssmService->postImage('This is a test image', $imgPath);
//
//        exit;
        return $content
            ->header(admin_trans_label('account_management'))
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new SmmUserAccount(), function (Grid $grid) {
            //指定视图，去掉删除按钮
            $grid->view('admin.grid.table');
            $grid->disableRowSelector(); // 关键代码
            $grid->column('id')->width(80);
            $grid->column('name')->tree()->display(function ($name) {
                $num = SmmUserAccount::returnChildCount($this->id,getDistributorId());
                if ($this->parent_id == 0) {
                    if ($num > 0) {
                        return $name . '<span class="badge" style="background:#21b978;margin-left:5px">'. $num. '</span>';
                    }
                }
                return $name;
            });
            $grid->column('account_id');
            $grid->column('expires_at');
            $grid->column('created_at')->sortable();


            $grid->column('status')->display(function ($name) {
                if ($this->parent_id > 0) {
                    //如果当前时间大于过期时间，则显示过期
                    if (Carbon::now() > $this->expires_at) {
                        return '<span  class="label" style="background-color:#f56c6c;color:#fff">过期</span>';
                    } else {
                        return '<span class="label" style="background-color:#21b978;color:#fff">正常</span>';
                    }
                }
            });

            $grid->column('quota_explanation', admin_trans_label('quota_explanation'))->display(function ($name) {
                if ($this->parent_id == 0) {
                    $quota = SmmPostLog::getPostQuota($this->name);
                    if ($this->name == 'Twitter') {
                        return admin_trans_label('twitter_quota_explanation',['quota'=>$quota]);
                    } else if ($this->name == 'YouTube'){
                        return admin_trans_label('youtube_quota_explanation',['quota'=>$quota]);
                    } else if ($this->name == 'Facebook') {
                        return admin_trans_label('facebook_quota_explanation',['quota'=>$quota]);
                    } else if ($this->name == 'Instagram') {
                        return admin_trans_label('instagram_quota_explanation',['quota'=>$quota]);
                    } else {
                        return admin_trans_label('-');
                    }
                }
            })->width('30%');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('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();
                } else {
                    if (Carbon::now() > $actions->row->expires_at) {
                        $parentAccount = SmmUserAccount::getAccountById($actions->row->parent_id);
                        $smmAddAccount = new SmmAddAccount();
                        $smmAddAccount->setData(admin_trans_label('reauthorization'),$parentAccount->name);
                        $actions->append($smmAddAccount);
                    }
                }
            });
            $grid->disableBatchDelete();
            $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);
            if ($result['status']) {
                $accessToken = $result['data']['accessToken'];
                $expiresAt = $result['data']['accessToken_expiresAt'];
                $userName = $result['data']['userName'];
                $userId = $result['data']['userId'];
                $refreshToken = isset($result['data']['refreshToken']) ? $result['data']['refreshToken'] : '';
                $backupField1 = isset($result['data']['backupField1']) ? $result['data']['backupField1'] : '';
                SmmUserAccount::createAccountIfMediaExists($mediaName, $userId,$userName, $accessToken,$expiresAt,$refreshToken,$backupField1);
                //return response()->json(['code' => 1, 'msg' => 'success']);
                $data = [
                    'status' => 'success',
                    'message' => 'Success',
                ];
            } else {
               //return response()->json(['code' => 0,'msg' => $result['data']]);
                $data = [
                    'status' => 'error',
                    'message' => $result['data'],
                ];
            }
        } catch (\Exception $e) {
            //return response()->json(['code' => 0,'msg' => 'error:'.$e->getMessage()]);
            $data = [
                'status' => 'error',
                'message' => $e->getMessage(),
            ];
        }

        return view('distributor.pages-custom.callback', $data);
    }


    //删除帐号
    public function destroy($id)
    {
        if ($this->distFindCountByID($id) === 0) {
            abort(404);
        }
        $ssmUserAccount = new SmmUserAccount();
        $ssmUserAccount->deleteAccount($id,getDistributorId());
        header('Content-Type: application/json');
        echo json_encode(['status' => true, 'data' => ['alert' => true,'message' => '删除成功 !']]);
        exit;
    }

}
