<?php
/**
 * Created by PhpStorm.
 * User: liang
 * Date: 2020/2/18
 * Time: 6:36 PM
 */
namespace console\controllers;


use common\models\UserInfo;
use common\models\UserNetwork;
use common\models\UserRelation;

class ChangeNetController extends BaseController {

    //顶点ID列表
    const TOP_ID_LIST = [
        '670B84FD7C216D4EE055736AECE8644D',
        '80552117701578757',
    ];
    //LOCATION缓存键
    const CHANGE_NET_CACHE_LOCATION_TAG_KEY = 'changeNet:cache:locationTag:key';

    /**
     * 清空缓存
     */
    public function actionClearCache() {
        $this->_clearTagCache();
    }

    /**
     * 加入安置数据
     * @param int $startPage
     * @throws \yii\db\Exception
     */
    public function actionAddNetwork($startPage=1) {
        $allCount = UserInfo::find()->where('1=1')->orderBy(' NETWORK_DEEP ASC,USER_ID ASC')->count('ID');
        $limit = 1000;
        $pageCount = ceil($allCount/$limit);
        unset($allCount);
        for($page=$startPage;$page<=$pageCount;$page++) {
            $userList = UserInfo::find()->where('1=1')->orderBy('NETWORK_DEEP ASC,USER_ID ASC')->limit($limit)->offset(($page-1)*$limit)->asArray()->all();
            $batchInsertList = [];
            foreach ($userList as $everyUser) {
                $netParentList = \Yii::$app->db->createCommand("SELECT * FROM AR_USER_NETWORK WHERE USER_ID=:USER_ID ORDER  BY PARENT_UID ASC")->bindValues([':USER_ID'=>$everyUser['USER_ID']])->queryAll();

                if( !$netParentList ) {
                    echo '不存在parentList :' . $everyUser['USER_ID'] . PHP_EOL;
                    continue;
                }
                $parentUidsStr = '';
                $topUid = '';
                $location = 0;
                foreach ($netParentList as $netParentData) {
                    if( !$netParentData['PARENT_UID'] ) continue;

                    if( !$topUid ) {
                        $topUid = $netParentData['TOP_UID'];
                    }
                    if(  $netParentData['PARENT_UID'] === $everyUser['CON_UID'] ) {
                        $location = $netParentData['LOCATION'];
                    }

                    $parentUidsStr .= $netParentData['PARENT_UID'] . ',';

                    unset($netParentData);
                }

                if( $location === 0 && !in_array($everyUser['USER_ID'], self::TOP_ID_LIST) ) {
                    echo 'location Error :' . $everyUser['USER_ID'] . PHP_EOL;
                    continue;
                }

                $parentUidsStr = rtrim($parentUidsStr, ',');
                unset($netParentList);

                $parentLocationTag = $this->_getLocationTagCache($everyUser['CON_UID']);
                if( $parentLocationTag ) {
                    $locationTag = $parentLocationTag . $location;
                }else {
                    $locationTag = '1';
                }
                if( $locationTag ==='1' && !in_array($everyUser['USER_ID'], self::TOP_ID_LIST) ) {
                    echo 'locationTag错误 :' . $everyUser['USER_ID'] . PHP_EOL;
                    continue;
                }

                $this->_addLocationTagCache($everyUser['USER_ID'], $locationTag);

                if( $topUid === '' && in_array($everyUser['USER_ID'], self::TOP_ID_LIST) ) {
                    $topUid = $everyUser['USER_ID'];
                }
                $batchInsertList[] = [
                    'USER_ID' => $everyUser['USER_ID'],
                    'PARENT_UID' => $everyUser['CON_UID'],
                    'LOCATION_TAG' => $locationTag,
                    'RELATIVE_LOCATION' => $location,
                    'TOP_UID' => $topUid,
                    'TOP_DEEP' => $everyUser['NETWORK_DEEP'],
                    'PARENT_UIDS' => $parentUidsStr,
                    'CREATED_AT' => $everyUser['CREATED_AT'],
//                    'UPDATED_AT' => '',
                ];

                unset($everyUser, $location, $locationTag, $topUid, $parentUidsStr);
            }
            unset($userList);

            UserNetwork::batchInsert($batchInsertList);
            unset($batchInsertList);

            echo sprintf("导入新网体表数据，总页数【%s】，当前页数：【%s】写入成功".PHP_EOL, $pageCount, $page);

        }

    }

    /**
     * 加入推荐数据
     * @param int $startPage
     * @throws \yii\db\Exception
     */
    public function actionAddRelation($startPage=1) {
        $allCount = UserInfo::find()->where('1=1')->orderBy(' RELATION_DEEP ASC,USER_ID ASC')->count('ID');
        $limit = 1000;
        $pageCount = ceil($allCount/$limit);
        unset($allCount);
        for($page=$startPage;$page<=$pageCount;$page++) {
            $userList = UserInfo::find()->where('1=1')->orderBy('RELATION_DEEP ASC,USER_ID ASC')->limit($limit)->offset(($page-1)*$limit)->asArray()->all();
            $batchInsertList = [];
            foreach ($userList as $everyUser) {
                $relationParentList = \Yii::$app->db->createCommand("SELECT * FROM AR_USER_RELATION WHERE USER_ID=:USER_ID ORDER  BY PARENT_UID ASC")->bindValues([':USER_ID'=>$everyUser['USER_ID']])->queryAll();

                if( !$relationParentList ) {
                    echo '不存在parentList :' . $everyUser['USER_ID'] . PHP_EOL;
                    continue;
                }
                $parentUidsStr = '';
                $topUid = '';
                foreach ($relationParentList as $relationParentData) {
                    if( !$relationParentData['PARENT_UID'] ) continue;

                    if( !$topUid ) {
                        $topUid = $relationParentData['TOP_UID'];
                    }

                    $parentUidsStr .= $relationParentData['PARENT_UID'] . ',';

                    unset($relationParentData);
                }

                $parentUidsStr = rtrim($parentUidsStr, ',');
                unset($relationParentList);

                if( $topUid === '' && in_array($everyUser['USER_ID'], self::TOP_ID_LIST) ) {
                    $topUid = $everyUser['USER_ID'];
                }
                $batchInsertList[] = [
                    'USER_ID' => $everyUser['USER_ID'],
                    'PARENT_UID' => $everyUser['REC_UID'],
                    'TOP_UID' => $topUid,
                    'TOP_DEEP' => $everyUser['RELATION_DEEP'],
                    'PARENT_UIDS' => $parentUidsStr,
                    'CREATED_AT' => $everyUser['CREATED_AT'],
//                    'UPDATED_AT' => '',
                ];


                unset($everyUser, $topUid, $parentUidsStr);
            }
            unset($userList);

            UserRelation::batchInsert($batchInsertList);
            unset($batchInsertList);

            echo sprintf("导入新推荐表数据，总页数【%s】，当前页数：【%s】写入成功".PHP_EOL, $pageCount, $page);

        }

    }

    /**
     * 添加网体标记Cache数据
     * @param $userId
     * @param $locationTag
     * @return mixed
     */
    private function _addLocationTagCache($userId, $locationTag) {
        return \Yii::$app->redis->hSet(self::CHANGE_NET_CACHE_LOCATION_TAG_KEY, $userId, $locationTag);
    }

    /**
     * 获取网体标记Cache数据
     * @param $userId
     * @return mixed
     */
    private function _getLocationTagCache($userId) {
        return \Yii::$app->redis->hGet(self::CHANGE_NET_CACHE_LOCATION_TAG_KEY, $userId);
    }

    /**
     * 清空网体标记Cache数据
     * @return mixed
     */
    private function _clearTagCache() {
        return \Yii::$app->redis->del(self::CHANGE_NET_CACHE_LOCATION_TAG_KEY);
    }

}
