<?php
/**
 * Created by PhpStorm.
 * User: congli
 * Date: 2020/2/19
 * Time: 4:14 PM
 */
namespace console\models;

use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\models\EmployLevel;
use common\models\forms\UserForm;
use common\models\Period;
use common\models\TmpDeleteUser;
use common\models\TmpOldNetwork;
use common\models\TmpOldUser;
use common\models\User;
use common\models\UserInfo;
use console\controllers\ImportController;

class ImportForm {

    const TOP_UID = '670B84FD7C216D4EE055736AECE8644D';

    const VIP_DEC_LEVEL = '67ABCE0ECE705575E055736AECE8644D';
    const IMPORT_CACHE_USERNAME_ID_KEY = 'console:importCacheUserNameIdKey';
    const IMPORT_CACHE_USER_INFO_ID_KEY = 'console:importCacheUserInfoIdKey';

    public $_decPv;

    public function __construct()
    {
        $decLevelConfig = Cache::getDecLevelConfig();
        $this->_decPv = $decLevelConfig[self::VIP_DEC_LEVEL]['PERF'] ?? 9800;
    }

    /**
     * 添加会员信息
     * @param array $pageData
     * @throws \Exception
     * @return bool
     */
    public function addOnlineUser(array $pageData) {
        echo sprintf("会员【%s】开始写入".PHP_EOL, $pageData['USER_NAME']);
        $user = new User();
        $user->USER_NAME = $pageData['USER_NAME'];
        $user->PASSWORD_HASH = '$2y$10$RsvcKc/aAD5.ewmHlXpmZOIUymTD8IgBpi/xdWJm1bSNzHlGcuQOi';
        $user->PAY_PASSWORD = '$2y$10$RsvcKc/aAD5.ewmHlXpmZOIUymTD8IgBpi/xdWJm1bSNzHlGcuQOi';
        $user->NATION = 0;
        $user->REAL_NAME = $pageData['REAL_NAME'];
        $user->ID_CARD = '130324201102069854';
        $user->MOBILE = '18068686868';
        $user->ADDRESS = '无';
        $user->OPEN_BANK = '';
        $user->BANK_ADDRESS = '';
        $user->BANK_NO = '';
        $user->BANK_PROVINCE = '0';
        $user->BANK_CITY = '0';
        $user->BANK_COUNTY = '0';
        $user->CREATED_AT = Date::nowTime();
        $user->STATUS = 1;
        $user->DEC_LV = self::VIP_DEC_LEVEL;
        $user->LAST_DEC_LV = self::VIP_DEC_LEVEL;
//        $user->EMP_LV = EmployLevel::getDefaultLevelId();
        $user->EMP_LV = '67BE1C6C21F81B32E055736AECE8644D';
        $user->PROVINCE = '0';
        $user->CITY = '0';
        $user->COUNTY = '0';
        $user->AVATAR = 'avatar/1.png';
        $user->IS_DEC = 0;
        $user->DEC_ID = self::TOP_UID;
        $user->DEC_ROLE_ID = '';
        $user->VERIFIED = 1;
        $user->VERIFIED_AT = Date::nowTime();
//        $user->PERIOD_AT = Period::instance()->getNowPeriodNum();
        $user->PERIOD_AT = 103;
        $user->IS_DIRECT_SELLER = 0;
        if (!$user->save()) {
//            var_dump($user->getErrors());die;
            throw new \Exception('添加失败,原因：'.Form::formatErrorsForApi($user->getErrors()));
        }

//        $this->_cacheUserId($user->USER_NAME, $user->ID);

        unset($user, $period);

        return true;
    }


    /**
     * 添加用户关系
     * @param array $pageData
     * @return bool
     * @throws \Exception
     */
    public function addOnlineInfo(array $pageData) {
//        $oldUserData = TmpOldUser::find()->where('USER_NAME=:USER_NAME', [':USER_NAME'=>$pageData['USER_NAME']])->asArray()->one();
        echo sprintf("会员【%s】开始导入".PHP_EOL, $pageData['USER_NAME']);

        $userId = $this->_getUserIdFromCache($pageData['USER_NAME']);
        if( $pageData['PARENT_USER_NAME'] !== ImportController::TOP_USER_NAME ) {
            $recUid = $this->_getUserIdFromCache($pageData['PARENT_USER_NAME']);
        }else {
            $recUid = self::TOP_UID;
        }
        if( $pageData['NET_USER_NAME'] !== ImportController::TOP_USER_NAME ) {
            $conUid = $this->_getUserIdFromCache($pageData['NET_USER_NAME']);

        }else {
            $conUid = self::TOP_UID;
        }
        if( !$recUid || !$conUid ) {
            throw new \Exception(sprintf("no relation id,recUid:%s,conUid:%s,userName:%s", $recUid, $conUid, $pageData['USER_NAME']));
        }

        $conNum = UserInfo::find()->where('CON_UID=:CON_UID', [':CON_UID'=>$conUid])->count('ID');
        $nowPeriodNum = 103;
        $form = new UserForm();
        $form->scenario = 'addWithUid';
        $form->userId = $userId;
        $form->userName = $pageData['USER_NAME'];
        $form->zcPv = $this->_decPv;
        $form->zcAmount = $this->_decPv;
        $form->conUid = $conUid;
        $form->recUid = $recUid;
        $location = $conNum + 1;
        if($location > 3) {
            echo sprintf("超接点,用户编号: %s,用户姓名：%s,安置人编号：%s,安置人姓名：%s" . PHP_EOL, $pageData['USER_NAME'], $pageData['REAL_NAME'], $pageData['PARENT_USER_NAME'], $pageData['PARENT_REAL_NAME'], $pageData['NET_USER_NAME'], $pageData['NET_REAL_NAME']);
            return true;
        }
        $form->location = $location;
        unset($location);
        if($form->addForImport($nowPeriodNum)){
            echo sprintf("会员【%s】导入成功".PHP_EOL, $pageData['USER_NAME']);
        } else {
            echo "当前会员:" . $pageData['USER_NAME'] . PHP_EOL;
            echo "推荐人:" . $pageData['PARENT_USER_NAME'] . PHP_EOL;
            echo "安置人:" . $pageData['NET_USER_NAME'] . PHP_EOL;
            var_dump($form->getErrors());die;
//            throw new \Exception('添加失败,原因：'.Form::formatErrorsForApi($form->getErrors()));
        }


        unset($form, $oldUserData, $conNum);
        return true;

    }

    public function cacheUserId($userName, $userId) {
        return $this->_cacheUserId($userName, $userId);
    }

    public function clearCache() {
        \Yii::$app->redis->del(self::IMPORT_CACHE_USERNAME_ID_KEY);
    }

    private function _cacheUserId($userName, $userId) {
        return \Yii::$app->redis->hSet(self::IMPORT_CACHE_USERNAME_ID_KEY, $userName, $userId);
    }

    private function _getUserIdFromCache($userName) {
        return \Yii::$app->redis->hGet(self::IMPORT_CACHE_USERNAME_ID_KEY, $userName);
    }

    public function clearInfoCache() {
        \Yii::$app->redis->del(self::IMPORT_CACHE_USER_INFO_ID_KEY);
    }

    public function cacheUserInfo($userId, $info) {
        return \Yii::$app->redis->hSet(self::IMPORT_CACHE_USER_INFO_ID_KEY, $userId, json_encode($info));
    }

    public function getCacheUserInfo($userId) {
        $infoJson =  \Yii::$app->redis->hGet(self::IMPORT_CACHE_USER_INFO_ID_KEY, $userId);

        return json_decode($infoJson, true);
    }

    /**
     * 删除某会员
     * @param $pageData
     */
    public function delTmpOldNetworkAllData($pageData) {
        echo sprintf("超点位删除,用户编号: %s,用户姓名：%s,安置人编号：%s,安置人姓名：%s" . PHP_EOL, $pageData['USER_NAME'], $pageData['REAL_NAME'], $pageData['PARENT_USER_NAME'], $pageData['PARENT_REAL_NAME'], $pageData['NET_USER_NAME'], $pageData['NET_REAL_NAME']);
        //删除这一条数据
        TmpOldNetwork::deleteAll("ID=:ID", ['ID'=>$pageData['ID']]);

        $this->delTmpOldNetworkRecData($pageData['USER_NAME']);
        $this->delTmpOldNetworkNetData($pageData['USER_NAME']);
    }

    /**
     * 删除某会员下面的接点会员
     * @param $parentUserName
     * @return bool
     */
    public function delTmpOldNetworkRecData($parentUserName) {
        $recData = TmpOldNetwork::find()->where("PARENT_USER_NAME=:PARENT_USER_NAME", ['PARENT_USER_NAME'=>$parentUserName])->asArray()->one();
        if( !$recData ) return true;
        echo sprintf("按推荐删除,用户编号: %s,用户姓名：%s,安置人编号：%s,安置人姓名：%s" . PHP_EOL, $recData['USER_NAME'], $recData['REAL_NAME'], $recData['PARENT_USER_NAME'], $recData['PARENT_REAL_NAME'], $recData['NET_USER_NAME'], $recData['NET_REAL_NAME']);
        //删除这个人的推荐会员
        TmpOldNetwork::deleteAll("ID=:ID", ['ID'=>$recData['ID']]);
        return $this->delTmpOldNetworkRecData($recData['USER_NAME']);
    }

    /**
     * 删除某会员下面的安置会员
     * @param $netUserName
     * @return bool
     */
    public function delTmpOldNetworkNetData($netUserName) {
        $netData = TmpOldNetwork::find()->where("NET_USER_NAME=:NET_USER_NAME", ['NET_USER_NAME'=>$netUserName])->asArray()->one();
        if( !$netData ) return true;
        //删除这个人的接点会员
        echo sprintf("按安置删除,用户编号: %s,用户姓名：%s,安置人编号：%s,安置人姓名：%s" . PHP_EOL, $netData['USER_NAME'], $netData['REAL_NAME'], $netData['PARENT_USER_NAME'], $netData['PARENT_REAL_NAME'], $netData['NET_USER_NAME'], $netData['NET_REAL_NAME']);
        TmpOldNetwork::deleteAll("ID=:ID", ['ID'=>$netData['ID']]);
        return $this->delTmpOldNetworkNetData($netData['USER_NAME']);
    }
}