<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午12:48
 */

namespace frontendApi\modules\v1\controllers;

use backendApi\modules\v1\models\lists\shop\BaUserList;
use common\helpers\Cache;
use common\helpers\user\Info;
use common\models\BaUser;
use common\models\BaUserInfo;
use common\models\DeclarationLevel;
use common\models\EmployLevel;
use common\models\Period;
use common\models\StarCrownLevel;
use common\models\UserNetwork;
use common\models\UserRelation;
use Yii;
use common\models\User;
use yii\data\Pagination;
use yii\db\Query;

class AtlasController extends BaseController {
    public $modelClass = User::class;

    public function behaviors() {
        $behaviors = parent::behaviors();
        return $behaviors;
    }

    /**
     * 主点位信息
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionMainUserInfo() {
        $userName = Yii::$app->request->get('userName', '');
        $periodNum = Yii::$app->request->get('periodNum', null);

        if ($userName !== '') {
            if (!$userId = Info::getUserIdByUserName($userName)) {
                return static::notice('Member does not exist', 400); // 会员不存在
            }
            $topUid = \Yii::$app->user->id;
            $userNetInfo = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'PARENT_UIDS');
            $parentUidsArr = explode(',', $userNetInfo['PARENT_UIDS']);
            if(!in_array($topUid,$parentUidsArr)){
                return static::notice('The member is not in the same placement network as the current user', 400); // 会员与当前用户不再同一安置网络内
            }

        } else {
            $userId = \Yii::$app->user->id;
        }
        $baseInfo = Info::baseInfo($userId, $periodNum);
        $decLevelConfig = Cache::getDecLevelConfig();
        $empLevelConfig = Cache::getEmpLevelConfig();
        $crownLevelConfig = Cache::getStarCrownLevelConfig();
        return static::notice([
            [
                'TOP_RELATION_DEEP' => $baseInfo['RELATION_DEEP'],
                'TOP_NETWORK_DEEP' => $baseInfo['NETWORK_DEEP'],
                'USER_ID' => $userId,
                'USER_NAME' => $baseInfo['USER_NAME'],
                'REAL_NAME' => $baseInfo['REAL_NAME'],
                'PERIOD_AT' => $baseInfo['PERIOD_AT'],
                'DEC_LV_NAME' => $decLevelConfig[$baseInfo['DEC_LV']]['LEVEL_NAME'] ?? $decLevelConfig[DeclarationLevel::getDefaultLevelId()]['LEVEL_NAME'],
                'EMP_LV_NAME' => $empLevelConfig[$baseInfo['EMP_LV']]['LEVEL_NAME'] ?? $empLevelConfig[EmployLevel::getDefaultLevelId()]['LEVEL_NAME'],
                'CROWN_LV_NAME' => $crownLevelConfig[$baseInfo['CROWN_LV']]['LEVEL_NAME'] ?? $crownLevelConfig[StarCrownLevel::getDefaultLevelId()]['LEVEL_NAME'],
                'leaf' => false,
                'icon' => 'el-icon-user-solid',
                'children' => null,
                'isExpanded' => false,
                'displayNone' => 'display-none',
                'className' => 'first-node',
                'listPeriodNum' => $periodNum
            ],
        ]);
    }

    /**
     * 安置网络图
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionNetwork() {
        $userId = Yii::$app->request->get('id', \Yii::$app->user->id);
        $periodNum = Yii::$app->request->get('periodNum', null);
        $deep = Yii::$app->request->get('deep', 5);
        if ($deep > 20) {
            return static::notice('View the top 20 sub members of the member at most', 400); // 最多查看会员的前20层子会员
        }
        $allData = UserNetwork::getChildrenWithDeepAndLayer($userId, $deep, 1, $periodNum);
        return static::notice(['allData' => $allData, 'periodNum' => $periodNum]);
    }

    /**
     * 安置网络列表
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionNetworkList() {
        $userName = Yii::$app->request->get('userName');
        $deep = Yii::$app->request->get('deep', 5);
        $periodNum = Yii::$app->request->get('periodNum', null);
        if (!$userName) {
            $userId = \Yii::$app->user->id;
        } else {
            if (!$userId = Info::getUserIdByUserName($userName)) {
                return static::notice('Member does not exist', 400); //  会员不存在
            }
            $topUid = \Yii::$app->user->id;
            $userNetInfo = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'PARENT_UIDS');
            $parentUidsArr = explode(',', $userNetInfo['PARENT_UIDS']);
            if(!in_array($topUid,$parentUidsArr)){
                return static::notice('The member is not in the same placement network as the current user', 400); // 会员与当前用户不再同一安置网络内
            }
        }
        $period = Period::instance();
        $mainUserInfo = Info::baseInfo($userId, $periodNum);
        $decLevelConfig = Cache::getDecLevelConfig();
        $empLevelConfig = Cache::getEmpLevelConfig();
        $data = UserNetwork::getChildrenInDeepFromPeriodWithPage($userId, $deep, $periodNum, 1 ? ['pageSize' => 10] : []);
        foreach($data['list'] as $key=>$value){
            $userBaseInfo = Info::baseInfo($value['USER_ID'], $periodNum);
            $data['list'][$key]['LIST_PERIOD_NUM'] = $periodNum?$periodNum:$period->getNowPeriodNum();
            $data['list'][$key]['COUNT_DEEP'] = (int)($userBaseInfo['NETWORK_DEEP']);
            $data['list'][$key]['USER_NAME'] = $userBaseInfo['USER_NAME'];
            $data['list'][$key]['SEE_USER_NAME'] = $userBaseInfo['USER_NAME'];
            $data['list'][$key]['REAL_NAME'] = $userBaseInfo['REAL_NAME'];
            $data['list'][$key]['PERIOD_AT'] = $userBaseInfo['PERIOD_AT'];
            $data['list'][$key]['DEC_LV_NAME'] = $decLevelConfig[$userBaseInfo['DEC_LV']]['LEVEL_NAME'];
            $data['list'][$key]['EMP_LV_NAME'] = $empLevelConfig[$userBaseInfo['EMP_LV']]['LEVEL_NAME'];
        }
        $data['periodNum'] = $periodNum;
        $data['listTopDeep'] = $mainUserInfo['NETWORK_DEEP'];

        return static::notice($data);
    }

    /**
     * 获取期数
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function getPeriod(){
        $period = Period::instance();
        $periodNum = $period->getNowPeriodNum();
        return static::notice([
            'periodNum' => $periodNum,
        ]);
    }

    /**
     * 推荐网络图
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRelation() {
        $userId = Yii::$app->request->get('id', \Yii::$app->user->id);
        $periodNum = Yii::$app->request->get('periodNum', null);
        $deep = Yii::$app->request->get('deep', 5);
        if ($deep > 20) {
            return static::notice('View the top 20 sub members of the member at most', 400); // 最多查看会员的前20层子会员
        }
        $allData = UserRelation::getChildrenWithDeepAndLayer($userId, $deep, 1, $periodNum);
        return static::notice(['allData' => $allData, 'periodNum' => $periodNum]);
    }

    /**
     * 推荐网络列表
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionRelationList() {
        $userName = Yii::$app->request->get('userName');
        $deep = Yii::$app->request->get('deep', 5);
        $periodNum = Yii::$app->request->get('periodNum', null);
        if (!$userName) {
            $userId = \Yii::$app->user->id;
        } else {
            if (!$userId = Info::getUserIdByUserName($userName)) {
                return static::notice('Member does not exist', 400); //  会员不存在
            }
            $topUid = \Yii::$app->user->id;
            $userNetInfo = UserRelation::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'PARENT_UIDS');
            $parentUidsArr = explode(',', $userNetInfo['PARENT_UIDS']);
            if(!in_array($topUid,$parentUidsArr)){
                return static::notice('会员与当前用户不再同一安置网络内', 400);
            }
        }
        $period = Period::instance();
        $mainUserInfo = Info::baseInfo($userId, $periodNum);
        $decLevelConfig = Cache::getDecLevelConfig();
        $empLevelConfig = Cache::getEmpLevelConfig();
        $data = UserNetwork::getChildrenInDeepFromPeriodWithPage($userId, $deep, $periodNum, 1 ? ['pageSize' => 10] : []);
        foreach($data['list'] as $key=>$value){
            $userBaseInfo = Info::baseInfo($value['USER_ID'], $periodNum);
            $data['list'][$key]['LIST_PERIOD_NUM'] = $periodNum?$periodNum:$period->getNowPeriodNum();
            $data['list'][$key]['COUNT_DEEP'] = (int)($userBaseInfo['NETWORK_DEEP']);
            $data['list'][$key]['USER_NAME'] = $userBaseInfo['USER_NAME'];
            $data['list'][$key]['SEE_USER_NAME'] = $userBaseInfo['USER_NAME'];
            $data['list'][$key]['REAL_NAME'] = $userBaseInfo['REAL_NAME'];
            $data['list'][$key]['PERIOD_AT'] = $userBaseInfo['PERIOD_AT'];
            $data['list'][$key]['DEC_LV_NAME'] = $decLevelConfig[$userBaseInfo['DEC_LV']]['LEVEL_NAME'];
            $data['list'][$key]['EMP_LV_NAME'] = $empLevelConfig[$userBaseInfo['EMP_LV']]['LEVEL_NAME'];
        }
        $data['periodNum'] = $periodNum;
        $data['listTopDeep'] = $mainUserInfo['NETWORK_DEEP'];

        return static::notice($data);
    }

    /**
     * 会员推荐的BA会员
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionBrandAmbassadorList()
    {
        $condition = ' AND I.REC_UID = :REC_UID ';
        $params[':REC_UID'] = \Yii::$app->user->id;
        $data = BaUserInfo::lists($condition, $params, [
            'select' => 'I.USER_ID, I.USER_NAME, U.REAL_NAME, U.PERIOD_AT, U.WHETHER_UPGRADE, U.BA_UPGRADE_AT',
            'from' => BaUserInfo::tableName().' AS I',
            'join' => [
                ['INNER JOIN', BaUser::tableName().' AS U', 'I.USER_ID = U.ID'],
            ],
            'orderBy' => 'I.CREATED_AT DESC',
        ]);

        return static::notice($data);
    }
}