<?php

namespace app\controllers\api;

use app\common\PaginationHelper;
use app\models\Clue;
use app\models\Oauth;
use app\models\OauthAccount;
use app\models\OauthAccountLocal;
use app\models\User;
use app\models\UserAdvertiser;
use app\models\Xiansuo;
use http\Url;
use Yii;
use yii\base\DynamicModel;
use yii\data\Pagination;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\validators\Validator;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use yii\web\UrlManager;

class UserController extends Controller
{
    public function beforeAction($action)
    {
        parent::beforeAction($action);

        if (Yii::$app->user->isGuest) {
            return $this->redirect('/login');
        }

        return true;
    }



    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error'   => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class'           => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        $query = User::find();
        $provider = PaginationHelper::createDataProvider($query);

        $models = $provider->getModels();
        foreach ($models as &$item) {
            $item = $item->toArray();
            $item['created_at'] = date('Y-m-d H:i:s', $item['updated_at']);
            $localAccountList = ArrayHelper::getColumn(UserAdvertiser::find()->where(['is_delete' => 0, 'user_id' => $item])->asArray()->all(), 'advertiser_name');
            $item['advertiser_status'] = implode(',', $localAccountList);
        }

        return $this->asJson([
            'count'   => $provider->totalCount,
            'code'    => 0,
            'data'    => $models,
            'message' => 'ok',
        ]);
    }

    public function actionCreate()
    {
        $model = DynamicModel::validateData(Yii::$app->request->post(), [
            // ===== 用户名 =====
            [['username'], 'required'],
            [['username'], 'trim'],
            [['username'], 'string', 'min' => 4, 'max' => 20],
            [['username'], 'match', 'pattern' => '/^[a-zA-Z0-9_]+$/', 'message' => '账号只能包含字母、数字和下划线'],
            [['username'], 'unique', 'targetClass' => User::class, 'message' => '该账号已存在'],

            // ===== 密码 =====
            [['password'], 'required'],
            [['password'], 'string', 'min' => 6, 'max' => 32],
            [['password'], 'match',
                'pattern' => '/^(?=.*[A-Za-z])(?=.*\d).+$/',
                'message' => '密码必须包含字母和数字'
            ],
        ]);

        if ($model->hasErrors()) {
            return $this->asJson([
                'code' => 1,
                'msg' => current($model->getFirstErrors())
            ]);
        }
        $username = Yii::$app->request->post('username');
        $password = Yii::$app->request->post('password');
        $model = new User();
        $model->username = $username;
        $model->auth_key = \Yii::$app->security->generateRandomString();
        $model->password_hash = \Yii::$app->security->generatePasswordHash($password);
        $model->email = "{$username}.com";
        $model->role = 'USER';
        $model->created_at = time();
        $model->updated_at = time();
        $model->save();
//        var_dump($model->errors);
        return $this->asJson([
            'code' => 0,
            'message' => 'ok'
        ]);
    }

    public function actionUpdate()
    {

    }

    public function actionDelete()
    {

    }

    /**
     *
     *
     * @return Response
     */
    public function actionXiansuo()
    {
        $query = Clue::find()->filterWhere(
            ['like', 'telephone', Yii::$app->request->get('phone')],
        )->andFilterWhere(
            ['like', 'name', Yii::$app->request->get('name')]
        )->andFilterWhere(
            ['like', 'note', Yii::$app->request->get('note')]
        )->orderBy('id DESC');
        $provider = PaginationHelper::createDataProvider($query, limit: Yii::$app->request->get('limit'));

        return $this->asJson([
            'count'   => $provider->totalCount,
            'code'    => 0,
            'data'    => $provider->models,
            'message' => 'ok',
        ]);
    }


    /**
     *
     * @url api/oauth-manage
     * @return Response
     */
    public function actionOauthManage()
    {
        $query = Oauth::find();
        $provider = PaginationHelper::createDataProvider($query);

        foreach ($provider->getModels() as &$item) {
            $item['updated_at'] = date('Y-m-d H:i:s', $item['updated_at']);
        }
        return $this->asJson([
            'count'   => $provider->totalCount,
            'code'    => 0,
            'data'    => $provider->models,
            'message' => 'ok',
        ]);
    }

    /**
     * @url api/oauth-manage-config
     */
    public function actionOauthManageConfig()
    {

    }

    /**
     * @url api/init-oauth-admin
     */
    public function actionInitOauthAdmin()
    {
        $uid = Yii::$app->request->post('uid');
        $tr = Yii::$app->db->beginTransaction();
//        Yii::$app->oceanengine->
        // 取出授权的account
        $oauthAdmin = Oauth::find()->where(['uid' => $uid])->one();
        $oauthAdmin->is_init = 1;
        $oauthAdmin->save();
//        $accounts = json_decode($oauthAdmin->advertiser_ids, true);

        // 清理之前所有授权的账户
        OauthAccount::updateAll(['admin_uid' => $uid], ['is_delete' => 1]);
        $accountList = Yii::$app->oceanengine->getAdminChildAccount($uid);

        // 本地推账户
        OauthAccountLocal::updateAll(['is_delete' => 1], ['admin_uid' => $uid]);

        // 更新account 数据
        foreach ($accountList['data']['list'] ?? [] as $account) {
            $accountQuery = OauthAccount::find()->where(['account_id' => $account['account_id']])->one() ?: new OauthAccount();
            $accountQuery->is_delete = 0;
            $accountQuery->admin_uid = $uid;
            $accountQuery->account_name = $account['account_name'];
            $accountQuery->account_id = strval($account['account_id']);
            $accountQuery->save();

            $accountLocalList = Yii::$app->oceanengine->getAccountLocal($uid);
            foreach ($accountLocalList['data']['list'] ?? [] as $accountLocal) {
                $query = OauthAccountLocal::find()->where(['advertiser_id' => $accountLocal['advertiser_id']])->one() ?: new OauthAccountLocal();
                $query->is_delete = 0;
                $query->admin_uid = $uid;
                $query->account_id = strval($account['account_id']);
                $query->advertiser_name = strval($accountLocal['advertiser_name']);
                $query->advertiser_id = strval($accountLocal['advertiser_id']);
                $query->save();
            }
        }


        $tr->commit();
        return $this->asJson([
            'code'    => 0,
            'data'    => [],
            'message' => 'ok',
        ]);
    }


    public function actionUpdateClue()
    {
        $clueId = Yii::$app->request->post('clue_id');
        $note = Yii::$app->request->post('note');
        $name = Yii::$app->request->post('name');

        $query = Clue::find()->where(['clue_id' => $clueId])->one();
        $query->note = $note;
        $query->name = $name;
        $query->save();

        return $this->asJson([
            'code'    => 0,
            'data'    => [],
            'message' => 'ok',
        ]);
    }

    public function actionOauthAccountLocalUpdate()
    {
        $advIds = Yii::$app->request->post('advertiser_ids');

        $isDelete = [];
        foreach ($advIds as $advVal) {
            list($id, $accountId) = explode('|', $advVal);
            if (!isset($isDelete[$accountId])) {
                OauthAccountLocal::updateAll(['is_active' => 0], ['account_id' => $accountId]);
                $isDelete[$accountId] = true;
            }

            $query = OauthAccountLocal::find()->where(['id' => $id])->one();
            $query->is_active = 1;
            $query->save();
        }

        return $this->asJson([
            'code'    => 0,
            'data'    => [],
            'message' => 'ok',
        ]);
    }

    public function actionResetPassword()
    {
        $password = Yii::$app->request->post('password');
        $id = Yii::$app->request->post('id');
        $model = User::find()->where(['id' => $id])->one();
        $model->auth_key = \Yii::$app->security->generateRandomString();
        $model->password_hash = \Yii::$app->security->generatePasswordHash($password);

        return $this->asJson([
            'code'    => 0,
            'data'    => [],
            'message' => $model->save() ? '修改成功' : '修改失败',
        ]);
    }

//    public function actionEdit()
//    {
//        $password = Yii::$app->request->post('password');
//        $id = Yii::$app->request->post('id');
//        $model = User::find()->where(['id' => $id])->one();
//        $model->auth_key = \Yii::$app->security->generateRandomString();
//        $model->password_hash = \Yii::$app->security->generatePasswordHash($password);
//
//        return $this->asJson([
//            'code'    => 0,
//            'data'    => [],
//            'message' => $model->save() ? '修改成功' : '修改失败',
//        ]);
//    }

    public function actionUpdateUser()
    {
        $userId = Yii::$app->request->post('user_id');
        $select = Yii::$app->request->post('select', '');
        UserAdvertiser::updateAll(['is_delete' => 1], ['user_id' => $userId]);

        try {
            $select = explode(',', $select);
        } catch (\Throwable $exception) {
            $select = [];
        }

        foreach ($select as $item) {
            $query = UserAdvertiser::find()->where(['user_id' => $userId, 'local_id' => $item])->one();
            if ($query) {
                $query->is_delete = 0;
            } else {
                $model = OauthAccountLocal::find()->where(['id' => $item])->one();
                $query = new UserAdvertiser();
                $query->advertiser_id = $model->advertiser_id;
                $query->user_id = $userId;
                $query->local_id = $userId;
                $query->advertiser_name = $model->advertiser_name;
            }

            $query->save();
        }

        return $this->asJson([
            'code'    => 0,
            'data'    => [],
            'message' => 'ok',
        ]);
    }
}
